diff --git a/src/leapflow/cli/context.py b/src/leapflow/cli/context.py index f3d7912..59c2f3d 100644 --- a/src/leapflow/cli/context.py +++ b/src/leapflow/cli/context.py @@ -2505,6 +2505,95 @@ def _on_insight(insight: Any) -> None: return _on_insight + async def _generate_session_summary(self) -> str | None: + """Generate a structured task summary from the session's conversation.""" + store = getattr(self, '_conversation_store', None) + if not store: + return None + session_id = getattr(self.engine, '_current_session_id', None) or "" + if not session_id: + return None + try: + # Fetch all messages (up to 200) to find both first user goal and final outcome. + # get_messages returns ASC order; we use a larger limit to capture session endpoints. + messages = store.get_messages(session_id, limit=200) + except Exception: + return None + if not messages or len(messages) < 2: + return None + + first_user = "" + for m in messages: + if getattr(m, 'role', '') == "user" and getattr(m, 'content', ''): + first_user = m.content[:150] + break + + tool_names = sorted(set( + getattr(m, 'tool_name', '') or '' + for m in messages + if getattr(m, 'tool_name', '') + ))[:8] + + last_assistant = "" + for m in reversed(messages): + content = getattr(m, 'content', '') or '' + if getattr(m, 'role', '') == "assistant" and len(content.strip()) > 20: + last_assistant = content[:200] + break + + if not first_user: + return None + + parts = [f"Goal: {first_user}"] + if tool_names: + parts.append(f"Tools: {', '.join(tool_names)}") + if last_assistant: + parts.append(f"Outcome: {last_assistant}") + return "\n".join(parts) + + async def _persist_session_summary(self) -> None: + """Generate and persist session summary at end of session.""" + try: + summary = await self._generate_session_summary() + if not summary: + return + + # Persist to memory via SemanticMemoryProvider + from leapflow.memory.protocol import MemoryEntry, MemoryKind, SignalDomain + session_id = getattr(self.engine, '_current_session_id', None) or "" + entry = MemoryEntry( + kind=MemoryKind.SESSION_SUMMARY, + domain=SignalDomain.SYSTEM, + content=summary, + metadata={ + "_session_id": session_id, + "workspace": str(self.settings.workspace_root), + }, + ) + if hasattr(self, 'memory') and self.memory: + await self.memory.insert(entry, session_id=session_id) + # MemoryManager routes SESSION_SUMMARY to narrative (MEMORY.md) first, + # but query_recent_summaries() reads from DuckDB (semantic provider). + # Explicitly persist to semantic to enable cross-session querying. + semantic = self.memory.get_provider("semantic") + if semantic is not None: + try: + await semantic.insert(entry, session_id=session_id) + except Exception: + logger.debug("semantic insert for session summary failed", exc_info=True) + logger.debug("Session summary persisted for session=%s", session_id[:8]) + + # Update session title with the goal line + goal_line = summary.split("\n")[0].removeprefix("Goal: ").strip() + conv_store = getattr(self, '_conversation_store', None) + if conv_store and session_id and goal_line: + try: + conv_store.end_session(session_id, title=goal_line) + except Exception: + logger.debug("session title update failed", exc_info=True) + except Exception: + logger.debug("session summary persistence failed", exc_info=True) + async def _on_session_end_learning(self) -> None: """End-of-session OPD learning pipeline (8 phases) with full observability. @@ -2893,6 +2982,8 @@ async def cleanup(self) -> None: # OPD end-of-session learning pipeline if self.settings.replay_on_session_end: await self._on_session_end_learning() + # Persist session summary before memory shutdown + await self._persist_session_summary() # Shutdown all memory providers (stops GC, closes DB) await self.memory.shutdown_all() if isinstance(self.rpc, CuaDriverClient): diff --git a/src/leapflow/config.py b/src/leapflow/config.py index d519d40..6839f22 100644 --- a/src/leapflow/config.py +++ b/src/leapflow/config.py @@ -321,6 +321,7 @@ class Settings: agent_iter_hard_cap: int = 500 agent_iter_extension_step: int = 25 agent_stall_rounds: int = 6 + agent_checkpoint_interval: int = 15 # Force checkpoint every N rounds in research posture agent_cost_ceiling_context_multiple: float = 0.0 agent_subagent_max_depth: int = 2 agent_subagent_max_concurrent: int = 3 @@ -860,6 +861,7 @@ def _build_settings_from_env( agent_iter_hard_cap = int(os.getenv("LEAPFLOW_AGENT_ITER_HARD_CAP", "500")) agent_iter_extension_step = int(os.getenv("LEAPFLOW_AGENT_ITER_EXTENSION_STEP", "25")) agent_stall_rounds = int(os.getenv("LEAPFLOW_AGENT_STALL_ROUNDS", "6")) + agent_checkpoint_interval = int(os.getenv("LEAPFLOW_AGENT_CHECKPOINT_INTERVAL", "15")) agent_cost_ceiling_context_multiple = float(os.getenv("LEAPFLOW_AGENT_COST_CEILING_CONTEXT_MULTIPLE", "0.0")) agent_subagent_max_depth = int(os.getenv("LEAPFLOW_AGENT_SUBAGENT_MAX_DEPTH", "2")) agent_subagent_max_concurrent = int(os.getenv("LEAPFLOW_AGENT_SUBAGENT_MAX_CONCURRENT", "3")) @@ -1217,6 +1219,7 @@ def _tuple_env(key: str, default: tuple) -> tuple: agent_iter_hard_cap=agent_iter_hard_cap, agent_iter_extension_step=agent_iter_extension_step, agent_stall_rounds=agent_stall_rounds, + agent_checkpoint_interval=agent_checkpoint_interval, agent_cost_ceiling_context_multiple=agent_cost_ceiling_context_multiple, agent_subagent_max_depth=agent_subagent_max_depth, agent_subagent_max_concurrent=agent_subagent_max_concurrent, diff --git a/src/leapflow/daemon/approval_coordinator.py b/src/leapflow/daemon/approval_coordinator.py index 76e3d86..6c62a47 100644 --- a/src/leapflow/daemon/approval_coordinator.py +++ b/src/leapflow/daemon/approval_coordinator.py @@ -213,6 +213,7 @@ def _normalize_decision(decision: str) -> str: "allow", "allow_once", "allow_session", + "allow_all_session", "allow_always", "deny", "deny_always", diff --git a/src/leapflow/engine/context_control.py b/src/leapflow/engine/context_control.py index 7316b97..2890003 100644 --- a/src/leapflow/engine/context_control.py +++ b/src/leapflow/engine/context_control.py @@ -756,6 +756,7 @@ class ContextGovernanceController: # exploration rounds; the ceiling prevents truly stuck tasks from running forever. convergence_round_ceiling: int = 40 convergence_scale: float = 2.0 + checkpoint_interval: int = 15 posture_config: ContextPostureConfig = field(default_factory=ContextPostureConfig) difficulty_config: DifficultyConfig = field(default_factory=DifficultyConfig) evidence_tools: frozenset[str] = _EVIDENCE_TOOLS @@ -784,6 +785,8 @@ def __post_init__(self) -> None: self._difficulty_ema_round = -1 self._evidence_by_round: dict[int, int] = {} self._evidence_round_hwm = -1 + self._last_tool_name: str = "" + self._last_tool_path: str = "" def reset_turn_scope(self) -> None: """Clear per-turn exploration state so posture never leaks across tasks.""" @@ -796,6 +799,8 @@ def reset_turn_scope(self) -> None: self._difficulty_ema_round = -1 self._evidence_by_round.clear() self._evidence_round_hwm = -1 + self._last_tool_name = "" + self._last_tool_path = "" reset_task_scope = reset_turn_scope @@ -811,28 +816,81 @@ def _effective_convergence_round(self, difficulty: float) -> int: extension = round(self.convergence_round * max(0.0, min(1.0, difficulty)) * self.convergence_scale) return min(self.convergence_round_ceiling, self.convergence_round + extension) + _WRITE_TOOLS = frozenset({ + "file_write", "gp_file_write", + "text_replace", "gp_text_replace", + "file_edit", "gp_file_edit", + }) + def compact_tool_result(self, tool_name: str, arguments: Dict[str, Any] | None, result: Any) -> Any: - """Return evidence and update the session exploration ledger.""" + """Return evidence and update the session exploration ledger. + + P0 convergence fixes: + - evidence_count only increments for genuinely new sources (not re-reads) + - Repeated reads beyond the limit are hard-gated: tool result is replaced + with an instruction to use research_note, unless the immediately preceding + tool call was a write/edit to the same path (post-edit verification is OK). + """ self._tool_counts[tool_name] = self._tool_counts.get(tool_name, 0) + 1 if isinstance(result, dict) and result.get("ok") is False: self._tool_failures += 1 - if tool_name in self.evidence_tools: - self._evidence_count += 1 + + gated_result: Any = None + if tool_name in {"file_read", "gp_file_read"}: path = str((arguments or {}).get("path") or (result.get("path") if isinstance(result, dict) else "")) if path: key = str(Path(path).expanduser()) + # Reset read count if the previous tool was a write/edit to this path + if self._last_tool_name in self._WRITE_TOOLS and self._last_tool_path == key: + self._reads[key] = 0 + is_new_source = key not in self._sources_seen self._reads[key] = self._reads.get(key, 0) + 1 self._sources_seen.add(key) + # Only count genuinely new sources as progress + if is_new_source: + self._evidence_count += 1 + # Hard gate: block re-reads beyond the limit + if self._reads[key] > self.repeated_read_limit: + gated_result = ( + f"[REPEATED READ \u2014 this file was already read {self._reads[key]} times in this turn. " + f"Content was processed in earlier rounds but compressed. " + f"Use research_note to record your findings instead of re-reading. " + f"File: {path}]" + ) elif tool_name in {"file_list", "gp_file_list"}: path = str((arguments or {}).get("path") or (result.get("path") if isinstance(result, dict) else "")) if path: key = str(Path(path).expanduser()) - # Track repeated directory listings alongside repeated file reads: - # both are evidence of an agent struggling to make progress, and - # both should push the posture toward converging. + is_new_source = key not in self._sources_seen self._reads[key] = self._reads.get(key, 0) + 1 self._sources_seen.add(key) + if is_new_source: + self._evidence_count += 1 + if self._reads[key] > self.repeated_read_limit: + gated_result = ( + f"[REPEATED READ \u2014 this directory was already listed {self._reads[key]} times in this turn. " + f"Content was processed in earlier rounds but compressed. " + f"Use research_note to record your findings instead of re-reading. " + f"Path: {path}]" + ) + elif tool_name in self.evidence_tools: + # shell_run and other non-path evidence tools: always new evidence + self._evidence_count += 1 + + # Track last tool for write-then-read exception + self._last_tool_name = tool_name + if tool_name in self._WRITE_TOOLS: + write_path = str((arguments or {}).get("path") or "") + self._last_tool_path = str(Path(write_path).expanduser()) if write_path else "" + elif tool_name in {"file_read", "gp_file_read", "file_list", "gp_file_list"}: + read_path = str((arguments or {}).get("path") or (result.get("path") if isinstance(result, dict) else "")) + self._last_tool_path = str(Path(read_path).expanduser()) if read_path else "" + else: + self._last_tool_path = "" + + if gated_result is not None: + return gated_result return self.evidence_builder.build(tool_name, arguments, result) def tool_metadata(self, tool_name: str, arguments: Dict[str, Any] | None, result: Any) -> Dict[str, Any]: @@ -1052,5 +1110,25 @@ def convergence_notice(self, round_number: int, *, open_questions: int | None = "prefer targeted reads, and synthesize the final answer." ) + def checkpoint_notice(self, round_number: int) -> str | None: + """Emit checkpoint instruction at configurable intervals during research.""" + interval = self.checkpoint_interval + if interval <= 0 or round_number < interval: + return None + if round_number % interval != 0: + return None + # Only checkpoint in research/expanding posture, not simple Q&A + snapshot = self.snapshot(round_number=round_number) + if snapshot.posture in (_POSTURE_BASELINE, _POSTURE_EXPANDED): + return None + return ( + f"SYSTEM CHECKPOINT (round {round_number}): " + "Persist your current findings NOW. " + "(1) Call research_note to record key conclusions that should survive context compression. " + "(2) Write intermediate results to a file if the task requires a deliverable. " + "(3) If you can answer partially, provide it now. " + "Remaining work should be declared as open_questions via research_note." + ) + LongTaskContextController = ContextGovernanceController diff --git a/src/leapflow/engine/context_disclosure.py b/src/leapflow/engine/context_disclosure.py index e29402d..7e9ba0a 100644 --- a/src/leapflow/engine/context_disclosure.py +++ b/src/leapflow/engine/context_disclosure.py @@ -234,7 +234,7 @@ def plan( level=level, tool_definitions=tuple(expanded_defs), catalog_definitions=tuple(tool_definitions), - memory=MemoryDisclosure.QUERY_RETRIEVAL if expanded_categories else MemoryDisclosure.NONE, + memory=MemoryDisclosure.QUERY_RETRIEVAL if expanded_categories else MemoryDisclosure.SESSION_SUMMARY, history=HistoryDisclosure.RECENT if expanded_categories else HistoryDisclosure.SHORT, # At the CORE floor (no Tier 1 category opened) skip reasoning entirely: a # turn that only needs the static low-risk whitelist is, by construction, not diff --git a/src/leapflow/engine/engine.py b/src/leapflow/engine/engine.py index fac4a2a..646486c 100644 --- a/src/leapflow/engine/engine.py +++ b/src/leapflow/engine/engine.py @@ -103,11 +103,31 @@ _TASK_CONTRACT_HEADING = "## Task Contract" -def _default_tool_registry() -> ToolRegistry: - """Return the canonical runtime tool registry.""" - from leapflow.tools.registry_bootstrap import TOOL_REGISTRY +_registry_cache: tuple[int, int, ToolRegistry] | None = None + - return TOOL_REGISTRY +def _default_tool_registry() -> ToolRegistry: + """Return the runtime tool registry, rebuilding when late-registered tools arrive.""" + global _registry_cache + from leapflow.tools.registry_bootstrap import ( + TOOL_DEFINITIONS, TOOL_HANDLERS, TOOL_REGISTRY, _BRIDGE_TOOLS, + ) + from leapflow.tools.name_resolver import TOOL_NAME_ALIASES + + size_key = (len(TOOL_DEFINITIONS), len(TOOL_HANDLERS)) + if _registry_cache is not None and _registry_cache[:2] == size_key: + return _registry_cache[2] + # First call: if sizes match the static registry, use it directly (no rebuild cost) + if _registry_cache is None and len(TOOL_REGISTRY.specs) >= len(TOOL_DEFINITIONS): + _registry_cache = (*size_key, TOOL_REGISTRY) + return TOOL_REGISTRY + # Late registrations detected — rebuild + registry = ToolRegistry.from_definitions( + TOOL_DEFINITIONS, TOOL_HANDLERS, + bridge_tools=_BRIDGE_TOOLS, aliases=TOOL_NAME_ALIASES, + ) + _registry_cache = (*size_key, registry) + return registry def _resolve_tool_name(tool_name: str, arguments: Dict[str, Any] | None = None) -> ToolResolution: @@ -786,7 +806,9 @@ def _last_tool_failures_recovery_message(messages: List[Dict[str, Any]]) -> str: platforms: List[str] = list(last.get("available_platforms") or []) if platforms: lines.append(f"Available platforms: {', '.join(platforms)}.") - elif "Missing required fields" in error: + elif failure_code == "missing_required_fields" or "Missing required fields" in error: + # TODO: migrate to failure_code-only once all producers emit + # failure_code="missing_required_fields" instead of bare error text. lines.append(f"Action parameter incomplete: {error}. Please provide the missing field(s) and retry.") elif error: lines.append(f"Action failed: {error}") @@ -1829,7 +1851,7 @@ def _build_task_contract(self, user_text: str) -> TaskContract: .expanduser() .resolve() ) - protocol = self._research_protocol_for(user_text) + protocol = self._research_protocol_for(user_text, self._settings) return TaskContract( task_id=f"turn-{self._session_turn_count}", original_request=user_text.strip(), @@ -1838,21 +1860,29 @@ def _build_task_contract(self, user_text: str) -> TaskContract: research_protocol=protocol, ) + _LARGE_TASK_PROTOCOL: tuple[str, ...] = ( + "DECOMPOSE before reading: identify sub-goals, then address each one.", + "PREFER targeted search (code_search, symbols) over full file reads.", + "RECORD findings with research_note after each sub-goal — they survive context compression.", + "WRITE intermediate results to a file if the task produces a deliverable.", + "AVOID reading files >500 lines in full — use outline mode or line ranges.", + ) + @staticmethod - def _research_protocol_for(user_text: str) -> tuple[str, ...]: - normalized = user_text.lower() - architecture_tokens = ( - "architecture", "diagram", "design", "架构", "架构图", "系统设计", "框图", - ) - if not any(token in normalized for token in architecture_tokens): - return () - return ( - "Identify the active project root before reading files.", - "Start from README, AGENTS, docs index, and top-level source layout.", - "Use outlines, symbols, and bounded ranges before raw full-file reads.", - "Cross-check entrypoints, core orchestration, representative modules, and tests.", - "Produce a concise subsystem map and Mermaid architecture diagram grounded in evidence.", + def _research_protocol_for(user_text: str, settings: Any = None) -> tuple[str, ...]: + """Inject research protocol based on structural signals (input complexity). + + Selection is driven by input length (a numeric structural signal), + NOT by keyword scanning. Post-first-round, the governance posture + and difficulty score handle escalation. + """ + threshold = ( + getattr(settings, 'research_protocol_length_threshold', 120) + if settings else 120 ) + if len(user_text.strip()) > threshold: + return AgentEngine._LARGE_TASK_PROTOCOL + return () def _task_scope_keywords(self, user_text: str) -> list[str]: keywords = _keywords_from_query(user_text) @@ -1956,6 +1986,12 @@ def _record_tool_focus( except (TypeError, ValueError, RuntimeError): logger.debug("semantic focus update failed for tool %s", tool_name, exc_info=True) + # Deprecated fallback: name-based context_plane inference. + # Tools should declare context_plane via x_leapflow metadata in their spec. + _EVIDENCE_TOOL_NAMES: frozenset[str] = frozenset( + {"file_read", "web_fetch", "code_search", "text_search", "memory_search"} + ) + def _tool_focus_metadata( self, tool_name: str, @@ -1964,14 +2000,31 @@ def _tool_focus_metadata( ) -> Dict[str, Any]: """Return compact metadata describing a tool result's context plane.""" name = str(tool_name or "").removeprefix("gp_") + + # Primary path: check tool manifest metadata (declarative) + spec = _default_tool_registry().specs.get(name) + if spec is not None: + declared_plane = getattr(spec, 'context_plane', None) + if declared_plane: + return {"context_plane": declared_plane} + + # Deprecated fallback: name-based inference (to be removed once all tools declare metadata) if name.startswith("config_"): + logger.debug( + "context_plane inferred from prefix for %s " + "(deprecated; declare x_leapflow.context_plane)", name, + ) metadata: Dict[str, Any] = {"context_plane": ContextPlane.CONTROL_PLANE.value} if isinstance(result, dict): key = str(result.get("key") or (arguments or {}).get("key") or "") if key: metadata["control_event_key"] = key return metadata - if name in {"file_read", "web_fetch", "code_search", "text_search", "memory_search"}: + if name in self._EVIDENCE_TOOL_NAMES: + logger.debug( + "context_plane inferred from name set for %s " + "(deprecated; declare x_leapflow.context_plane)", name, + ) return {"context_plane": ContextPlane.TOOL_EVIDENCE.value} return {} @@ -2201,6 +2254,65 @@ def _planned_tools_kwarg(self, plan: PromptAssemblyPlan) -> Dict[str, Any]: return {"tools": list(plan.tool_definitions)} return {} + # ------------------------------------------------------------------ + # P2-2: Pre-compression knowledge auto-extraction + # ------------------------------------------------------------------ + + @staticmethod + def _auto_extract_findings(messages: List[Dict[str, Any]]) -> List[str]: + """Extract key file-read findings before compression discards them.""" + findings: List[str] = [] + for msg in messages: + role = msg.get("role", "") + content = str(msg.get("content", "")) + # Only extract from tool results (file reads) with substantial content + if role not in ("tool", "function"): + continue + if len(content) < 300: + continue + # Prefer structured JSON check over substring sniffing + _skip = False + if content.lstrip().startswith('{'): + try: + parsed = json.loads(content) + if isinstance(parsed, dict) and parsed.get("ok") is False: + _skip = True + except (ValueError, TypeError): + pass + if _skip: + continue + finding = AgentEngine._extract_compact_finding(content) + if finding: + findings.append(finding) + return findings + + @staticmethod + def _extract_compact_finding(content: str, max_chars: int = 400) -> str: + """Extract a compact summary from a tool result.""" + lines = content.split('\n') + # Look for file path in first few lines + path_line = "" + for line in lines[:5]: + if '/' in line and ('.' in line.split('/')[-1]): + path_line = line.strip()[:120] + break + if not path_line: + # Fallback: take first non-empty line + for line in lines: + stripped = line.strip() + if stripped and len(stripped) > 10: + path_line = stripped[:120] + break + if not path_line: + return "" + # Take first substantial paragraph as context + body = content[:max_chars - len(path_line) - 20].strip() + # Truncate to last complete line + last_newline = body.rfind('\n') + if last_newline > 100: + body = body[:last_newline] + return f"[auto-extracted] {path_line}: {body[:max_chars - len(path_line) - 30]}" + def _prepare_llm_messages( self, messages: List[Dict[str, Any]], @@ -2211,7 +2323,13 @@ def _prepare_llm_messages( """Compress and hard-gate messages before sending them to the provider.""" context_length = self._active_context_length() token_count = self._context_controller.estimator.estimate_messages(messages) + # P2-2: extract findings from messages that may be discarded by compression + pre_compression_findings = self._auto_extract_findings(messages) prepared = self._compressor.compress(messages, token_count=token_count) + # Inject extracted findings into research ledger if compression actually ran + if len(prepared) < len(messages) and pre_compression_findings: + for finding in pre_compression_findings: + self._research_ledger.note("finding", finding) if ( getattr(self._settings, "agent_compression_writeback", False) and len(prepared) < len(messages) @@ -2244,8 +2362,9 @@ def _prepare_llm_messages( convergence = self._context_governance_controller.convergence_notice( round_number, open_questions=open_questions, ) + checkpoint_msg = self._context_governance_controller.checkpoint_notice(round_number) cost_notice = self._cost_ceiling_notice() - for notice in (warning, convergence, cost_notice): + for notice in (warning, convergence, checkpoint_msg, cost_notice): if notice: prepared = [*prepared, build_user_message_text(notice)] ledger_block = self._research_ledger.render() @@ -2426,9 +2545,10 @@ def _task_progress_marker(self) -> tuple: Combines the research-ledger shape (findings / open questions / decisions / next step) with governance evidence breadth (evidence count, - distinct sources). A change between rounds means the task advanced; an - unchanged marker across rounds indicates a stall. Works for ledger-using - tasks and, via governance signals, for tasks that never call research_note. + distinct sources, repeated reads). A change between rounds means the task + advanced; an unchanged marker across rounds indicates a stall. Including + repeated_reads ensures that growing re-reads (with no other progress) + keep the marker unchanged, so stalled_rounds increments correctly. """ d = self._research_ledger.as_dict() gov = self._last_context_snapshot.get("context_governance", {}) or {} @@ -2439,6 +2559,7 @@ def _task_progress_marker(self) -> tuple: d.get("next_step", ""), int(gov.get("evidence_count", 0) or 0), int(gov.get("sources_seen", 0) or 0), + int(gov.get("repeated_reads", 0) or 0), ) def _update_progress_and_stall(self, frame: AgentLoopFrame) -> None: @@ -2859,6 +2980,7 @@ def _new_governance(self) -> ContextGovernanceController: convergence_round=self._settings.long_task_convergence_round, convergence_round_ceiling=self._settings.convergence_round_ceiling, convergence_scale=self._settings.convergence_scale, + checkpoint_interval=self._settings.agent_checkpoint_interval, posture_config=ContextPostureConfig( expanded_ratio=self._settings.context_expanded_ratio, finalizing_ratio=( @@ -4980,7 +5102,7 @@ async def _prefetch_and_freeze_memory(self, user_text: str) -> str: if self._current_task_contract else "" ), scope_keywords=self._task_scope_keywords(user_text), - session_scope=self._current_session_id or "", + session_scope="", ), timeout=self._settings.memory_prefetch_timeout_s, ) @@ -4995,6 +5117,20 @@ async def _prefetch_and_freeze_memory(self, user_text: str) -> str: except Exception: logger.debug("memory.prefetch failed", exc_info=True) + # Layer 0: Recent task history (session summaries) + try: + semantic = self._memory_manager.get_provider("semantic") + if semantic is not None and hasattr(semantic, "query_recent_summaries"): + summaries = semantic.query_recent_summaries(limit=5) + if summaries: + history_lines = [] + for s in summaries: + history_lines.append(f"- {s['content'][:300]}") + history_block = "## Recent Task History\n" + "\n".join(history_lines) + parts.insert(0, history_block) + except Exception: + logger.debug("Layer 0 task history injection failed", exc_info=True) + self._memory_context_snapshot = "\n\n".join(parts) return self._memory_context_snapshot diff --git a/src/leapflow/engine/research_ledger.py b/src/leapflow/engine/research_ledger.py index 8db42df..af50367 100644 --- a/src/leapflow/engine/research_ledger.py +++ b/src/leapflow/engine/research_ledger.py @@ -20,8 +20,9 @@ # it as a finding, so the open-question set reflects only what remains. LEDGER_KINDS = ("finding", "open_question", "resolved", "decision", "next_step") -_MAX_ITEMS = 24 # per-list cap; keep the most recent (SNR over completeness) -_MAX_CHARS = 200 # per-note cap: one concise sentence (bounds every-round re-injection) +_MAX_ITEMS = 32 # per-list cap; keep the most recent (SNR over completeness) +_MAX_CHARS = 600 # per-note cap: one concise paragraph (bounds every-round re-injection) +_MAX_TOTAL_CHARS = 16_000 # total chars across all categories; FIFO eviction from largest bucket @dataclass @@ -30,6 +31,7 @@ class ResearchLedger: max_items: int = _MAX_ITEMS max_chars: int = _MAX_CHARS + max_total_chars: int = _MAX_TOTAL_CHARS def __post_init__(self) -> None: self._findings: List[str] = [] @@ -77,6 +79,34 @@ def _append(self, bucket: List[str], text: str) -> None: bucket.append(text) if len(bucket) > self.max_items: # keep most recent del bucket[: len(bucket) - self.max_items] + self._enforce_total_capacity() + + def _enforce_total_capacity(self) -> None: + """Evict oldest notes (FIFO) from the largest category until under budget.""" + while self._total_chars() > self.max_total_chars: + largest = self._largest_bucket() + if largest: + largest.pop(0) + continue + # No list buckets to evict; truncate next_step as last resort + if self._next_step: + self._next_step = self._next_step[:self.max_chars] + break + + def _total_chars(self) -> int: + return ( + sum(len(n) for n in self._findings) + + sum(len(n) for n in self._open_questions) + + sum(len(n) for n in self._decisions) + + len(self._next_step) + ) + + def _largest_bucket(self) -> List[str] | None: + buckets = [self._findings, self._open_questions, self._decisions] + non_empty = [b for b in buckets if b] + if not non_empty: + return None + return max(non_empty, key=lambda b: sum(len(n) for n in b)) def _resolve(self, text: str) -> None: low = text.lower() diff --git a/src/leapflow/memory/providers/semantic.py b/src/leapflow/memory/providers/semantic.py index 6e5a2b0..69f155f 100644 --- a/src/leapflow/memory/providers/semantic.py +++ b/src/leapflow/memory/providers/semantic.py @@ -374,6 +374,29 @@ def upsert_raw( ) return mid + def query_recent_summaries(self, limit: int = 5) -> list[dict]: + """Query recent session summaries for task history injection.""" + try: + con = self._ensure_connection() + results = con.execute( + "SELECT content, created_at, metadata FROM leap_memory " + "WHERE kind = 'session_summary' " + "ORDER BY created_at DESC LIMIT ?", + [limit], + ).fetchall() + entries = [] + for r in results: + meta = {} + if r[2]: + try: + meta = json.loads(r[2]) + except (json.JSONDecodeError, TypeError): + pass + entries.append({"content": r[0], "created_at": r[1], "metadata": meta}) + return entries + except Exception: + return [] + def search_keywords( self, keywords: Sequence[str], diff --git a/src/leapflow/prompts/templates.py b/src/leapflow/prompts/templates.py index 2dc48f8..a6c3f09 100644 --- a/src/leapflow/prompts/templates.py +++ b/src/leapflow/prompts/templates.py @@ -114,6 +114,7 @@ def build_react_system(language: str = "en", skill_catalog: str = "") -> str: 5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing. 6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output. 7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation. +8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions. ## Coding & Verification When working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an diff --git a/src/leapflow/storage/conversation_store.py b/src/leapflow/storage/conversation_store.py index 089c5c8..a505c9e 100644 --- a/src/leapflow/storage/conversation_store.py +++ b/src/leapflow/storage/conversation_store.py @@ -525,12 +525,21 @@ def mark_compacted(self, session_id: str, message_ids: List[str]) -> None: [session_id, *message_ids], ) - def end_session(self, session_id: str) -> None: - """Mark a session as inactive (completed/archived).""" + def end_session(self, session_id: str, *, title: str | None = None) -> None: + """Mark a session as inactive (completed/archived). + + If *title* is provided, the session title is also updated (truncated to 80 chars). + """ + now = time.time() self._execute_write( "UPDATE conversation_sessions SET is_active = FALSE, updated_at = ? WHERE session_id = ?", - [time.time(), session_id], + [now, session_id], ) + if title: + self._execute_write( + "UPDATE conversation_sessions SET title = ?, updated_at = ? WHERE session_id = ?", + [title[:80], now, session_id], + ) def fork_session( self, diff --git a/src/leapflow/tools/file_operations.py b/src/leapflow/tools/file_operations.py index dd4ab75..56f2d93 100644 --- a/src/leapflow/tools/file_operations.py +++ b/src/leapflow/tools/file_operations.py @@ -702,7 +702,8 @@ async def code_search(params: Dict[str, Any]) -> Dict[str, Any]: extra = [str(item) for item in extra_raw if str(item or "").strip()] if isinstance(extra_raw, (list, tuple)) else [] all_patterns = [p for p in [pattern, *extra] if p] if not all_patterns: - return {"ok": False, "error": "Missing required parameter: pattern"} + # LLM likely wants to browse files — silently redirect to file_list. + return await file_list({"path": params.get("path", "."), "depth": 2}) if len(all_patterns) > 1: pattern = "|".join(f"(?:{p})" for p in all_patterns) else: diff --git a/src/leapflow/tools/name_resolver.py b/src/leapflow/tools/name_resolver.py index 0d1ad89..de7e567 100644 --- a/src/leapflow/tools/name_resolver.py +++ b/src/leapflow/tools/name_resolver.py @@ -90,6 +90,12 @@ "run_command": "shell_run", "run_terminal": "shell_run", "exec": "shell_run", + # Terminal sessions + "shell_list": "terminal_list", + "shell_open": "terminal_open", + "shell_send": "terminal_send", + "shell_read": "terminal_read", + "shell_close": "terminal_close", # Search "grep": "text_search", "search": "text_search", diff --git a/src/leapflow/tools/registry_bootstrap.py b/src/leapflow/tools/registry_bootstrap.py index 1226365..d61186d 100644 --- a/src/leapflow/tools/registry_bootstrap.py +++ b/src/leapflow/tools/registry_bootstrap.py @@ -117,7 +117,8 @@ "function": { "name": "code_search", "description": ( - "Search file CONTENTS by regex across a directory tree (ripgrep-backed). " + "Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). " + "Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. " "Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, " "and returns structured path:line:column matches. Batch related lookups " "into ONE call via `patterns` (OR-combined, single pass) instead of " @@ -127,7 +128,7 @@ "parameters": { "type": "object", "properties": { - "pattern": {"type": "string", "description": "Regex pattern to search for"}, + "pattern": {"type": "string", "description": "Regex pattern to search for (REQUIRED — this tool searches file contents, not file names)"}, "patterns": { "type": "array", "items": {"type": "string"}, @@ -140,7 +141,7 @@ "max_results": {"type": "integer", "description": "Max matches to return (default: 200)"}, "context_lines": {"type": "integer", "description": "Lines of context before/after each match (default: 0, max 10)"}, }, - "required": ["pattern"], + "required": [], }, "x_leapflow": {"category": "file", "risk_level": "read_only", "schema_cost": "low", "requires_approval": False}, }, diff --git a/src/leapflow/tools/shell_tools.py b/src/leapflow/tools/shell_tools.py index 5a1bc40..68543e4 100644 --- a/src/leapflow/tools/shell_tools.py +++ b/src/leapflow/tools/shell_tools.py @@ -32,11 +32,26 @@ def _is_bypass_active() -> bool: - """Check if approval bypass mode is active for the current context.""" + """Check if approval bypass mode is active (config-level or session-level).""" ctx = current_tool_context() if ctx is None: return False - return getattr(ctx, 'approval_bypass', False) + if getattr(ctx, 'approval_bypass', False): + return True + # Session-level bypass: user selected "Allow ALL for this session" + orchestrator = getattr(ctx, 'orchestrator', None) or _approval_gate + if orchestrator is None: + return False + # Direct ApprovalOrchestrator → SessionAwareGate + gate = getattr(orchestrator, '_gate', None) + # SmartApprovalGate wrapper: penetrate _delegate + if gate is None: + delegate = getattr(orchestrator, '_delegate', None) + if delegate is not None: + gate = getattr(delegate, '_gate', None) + if gate is not None and getattr(gate, '_bypass_all', False): + return True + return False # Raw capture ceilings. These bound what the tool returns before the context @@ -314,7 +329,7 @@ async def shell_run(params: Dict[str, Any]) -> Dict[str, Any]: if not approved: return command_scope_error - if _is_dangerous(command): + if _is_dangerous(command) and not _is_bypass_active(): approved, message = await _approve_command(command, cwd) if not approved: return {"ok": False, "error": message} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-13576aa22eb13f37.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-13576aa22eb13f37.cassette.json new file mode 100644 index 0000000..0564e12 --- /dev/null +++ b/tests/_fixtures/cassettes/r1_conversation/cassette-model-13576aa22eb13f37.cassette.json @@ -0,0 +1,50 @@ +{ + "fingerprint": "13576aa22eb13f37f2c1178528c307aff293097afd8d94b88347fe88cb63f1bb", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [user] Say hello.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Say hello.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "user", + "content": "Say hello.\nSay hello." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Hello from LeapFlow.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-316873c4e8830dbd.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-316873c4e8830dbd.cassette.json new file mode 100644 index 0000000..09b3321 --- /dev/null +++ b/tests/_fixtures/cassettes/r1_conversation/cassette-model-316873c4e8830dbd.cassette.json @@ -0,0 +1,54 @@ +{ + "fingerprint": "316873c4e8830dbd2262e658e4c7396a125443f6014285070414e416a8a1ed30", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Hello from LeapFlow.\n- [user] Use the file_read tool on invoice.txt and report the total.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Use the file_read tool on invoice.txt and report the total.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Hello from LeapFlow." + }, + { + "role": "user", + "content": "Use the file_read tool on invoice.txt and report the total.\nUse the file_read tool on invoice.txt and report the total." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"\", \"tool_calls\": [{\"id\": \"call_1\", \"type\": \"function\", \"function\": {\"name\": \"file_read\", \"arguments\": \"{\\\"path\\\": \\\"invoice.txt\\\"}\"}}]}, \"finish_reason\": \"tool_calls\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-67c05c7fa65b427c.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-67c05c7fa65b427c.cassette.json new file mode 100644 index 0000000..dc18029 --- /dev/null +++ b/tests/_fixtures/cassettes/r1_conversation/cassette-model-67c05c7fa65b427c.cassette.json @@ -0,0 +1,67 @@ +{ + "fingerprint": "67c05c7fa65b427c2e2e730099bda46e5023ad65f865130432faacca8ba71d6f", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Semantic Focus Plane\nCurrent task focus:\n- Target: invoice.txt\n- Type: file\n- Evidence refs: file_read:invoice.txt\nResolved user reference:\n- file -> invoice.txt (task_semantic, confidence=0.92)\nUse Current task focus for deictic task references such as 'the above paper'; use control-plane events only when the user explicitly asks about runtime settings.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Is that the same invoice?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "user", + "content": "Say hello." + }, + { + "role": "assistant", + "content": "Hello from LeapFlow." + }, + { + "role": "user", + "content": "Use the file_read tool on invoice.txt and report the total." + }, + { + "role": "assistant", + "content": "[Called: file_read]\nThe invoice total is 128.50 USD." + }, + { + "role": "user", + "content": "Is that the same invoice?\nIs that the same invoice?" + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "edit_file", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Yes, that is the same invoice.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-76802162bb96917f.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-76802162bb96917f.cassette.json deleted file mode 100644 index 30c18ee..0000000 --- a/tests/_fixtures/cassettes/r1_conversation/cassette-model-76802162bb96917f.cassette.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "fingerprint": "76802162bb96917fbd14bb31afcdaa924a31afd51acd4846af9d1bbc2a57dd5e", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Say hello.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Say hello.\nSay hello." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Hello from LeapFlow.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-7e65b23368f3ad75.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-7e65b23368f3ad75.cassette.json deleted file mode 100644 index ca8126f..0000000 --- a/tests/_fixtures/cassettes/r1_conversation/cassette-model-7e65b23368f3ad75.cassette.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "fingerprint": "7e65b23368f3ad756b40aa2f9d026b9e489fa95b9fff6a810295ee01bfb37373", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Is that the same invoice?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Say hello." - }, - { - "role": "assistant", - "content": "Hello from LeapFlow." - }, - { - "role": "user", - "content": "Use the file_read tool on invoice.txt and report the total." - }, - { - "role": "assistant", - "content": "[Called: file_read]\nThe invoice total is 128.50 USD." - }, - { - "role": "user", - "content": "Is that the same invoice?\nIs that the same invoice?" - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "edit_file", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Yes, that is the same invoice.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-8a16792e03d455d4.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-8a16792e03d455d4.cassette.json deleted file mode 100644 index 0f5bd65..0000000 --- a/tests/_fixtures/cassettes/r1_conversation/cassette-model-8a16792e03d455d4.cassette.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "fingerprint": "8a16792e03d455d4eb21491dee30fcb9a118ec939bfeb9bd440396cae0c21f7d", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Semantic Focus Plane\nCurrent task focus:\n- Target: invoice.txt\n- Type: file\n- Evidence refs: file_read:invoice.txt\nResolved user reference:\n- file -> invoice.txt (task_semantic, confidence=0.92)\nUse Current task focus for deictic task references such as 'the above paper'; use control-plane events only when the user explicitly asks about runtime settings.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Is that the same invoice?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Say hello." - }, - { - "role": "assistant", - "content": "Hello from LeapFlow." - }, - { - "role": "user", - "content": "Use the file_read tool on invoice.txt and report the total." - }, - { - "role": "assistant", - "content": "[Called: file_read]\nThe invoice total is 128.50 USD." - }, - { - "role": "user", - "content": "Is that the same invoice?\nIs that the same invoice?" - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "edit_file", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Yes, that is the same invoice.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-99f7b337470a42f2.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-99f7b337470a42f2.cassette.json deleted file mode 100644 index 44a446f..0000000 --- a/tests/_fixtures/cassettes/r1_conversation/cassette-model-99f7b337470a42f2.cassette.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "fingerprint": "99f7b337470a42f2bc8cf89ce1143d60ee93d935c0a224bbe55d0f53d490280e", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Use the file_read tool on invoice.txt and report the total.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Hello from LeapFlow." - }, - { - "role": "user", - "content": "Use the file_read tool on invoice.txt and report the total.\nUse the file_read tool on invoice.txt and report the total." - }, - { - "role": "assistant", - "content": "", - "tool_calls": [ - "file_read" - ] - }, - { - "role": "tool", - "content": "{\"ok\": true, \"kind\": \"file_read_evidence\", \"path\": \"\", \"lines\": 2, \"truncated\": false, \"mode\": \"raw\", \"excerpt\": \"Invoice 42\\nTotal: 128.50 USD\", \"start_line\": 1, \"end_line\": 2, \"selected_lines\": 2}", - "tool_result": true - }, - { - "role": "assistant", - "content": "Operation interrupted. Continuing..." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"The invoice total is 128.50 USD.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-bba29ec49d45d0ce.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-bba29ec49d45d0ce.cassette.json deleted file mode 100644 index 197ab2c..0000000 --- a/tests/_fixtures/cassettes/r1_conversation/cassette-model-bba29ec49d45d0ce.cassette.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "fingerprint": "bba29ec49d45d0ce6412ba849678f40629c9a362754caa4983615a78b6bd9c0e", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Use the file_read tool on invoice.txt and report the total.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Hello from LeapFlow." - }, - { - "role": "user", - "content": "Use the file_read tool on invoice.txt and report the total.\nUse the file_read tool on invoice.txt and report the total." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"\", \"tool_calls\": [{\"id\": \"call_1\", \"type\": \"function\", \"function\": {\"name\": \"file_read\", \"arguments\": \"{\\\"path\\\": \\\"invoice.txt\\\"}\"}}]}, \"finish_reason\": \"tool_calls\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-c223eb3fe510faa7.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-c223eb3fe510faa7.cassette.json deleted file mode 100644 index fece558..0000000 --- a/tests/_fixtures/cassettes/r1_conversation/cassette-model-c223eb3fe510faa7.cassette.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "fingerprint": "c223eb3fe510faa7b5dd3b20779a15337c3332c58c5b53cc1367698a36d01e02", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Semantic Focus Plane\nCurrent task focus:\n- Target: invoice.txt\n- Type: file\n- Evidence refs: file_read:invoice.txt\nResolved user reference:\n- file -> invoice.txt (task_semantic, confidence=0.72)\nUse Current task focus for deictic task references such as 'the above paper'; use control-plane events only when the user explicitly asks about runtime settings.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Is that the same invoice?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Say hello." - }, - { - "role": "assistant", - "content": "Hello from LeapFlow." - }, - { - "role": "user", - "content": "Use the file_read tool on invoice.txt and report the total." - }, - { - "role": "assistant", - "content": "[Called: file_read]\nThe invoice total is 128.50 USD." - }, - { - "role": "user", - "content": "Is that the same invoice?\nIs that the same invoice?" - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "edit_file", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Yes, that is the same invoice.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r1_conversation/cassette-model-cb7ae20232980342.cassette.json b/tests/_fixtures/cassettes/r1_conversation/cassette-model-cb7ae20232980342.cassette.json new file mode 100644 index 0000000..489526b --- /dev/null +++ b/tests/_fixtures/cassettes/r1_conversation/cassette-model-cb7ae20232980342.cassette.json @@ -0,0 +1,70 @@ +{ + "fingerprint": "cb7ae202329803422fa5ade7b4f362063c52946fc97d852807afc105fd660b85", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Hello from LeapFlow.\n- [user] Use the file_read tool on invoice.txt and report the total.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Use the file_read tool on invoice.txt and report the total.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Hello from LeapFlow." + }, + { + "role": "user", + "content": "Use the file_read tool on invoice.txt and report the total.\nUse the file_read tool on invoice.txt and report the total." + }, + { + "role": "assistant", + "content": "", + "tool_calls": [ + "file_read" + ] + }, + { + "role": "tool", + "content": "{\"ok\": true, \"kind\": \"file_read_evidence\", \"path\": \"\", \"lines\": 2, \"truncated\": false, \"mode\": \"raw\", \"excerpt\": \"Invoice 42\\nTotal: 128.50 USD\", \"start_line\": 1, \"end_line\": 2, \"selected_lines\": 2}", + "tool_result": true + }, + { + "role": "assistant", + "content": "Operation interrupted. Continuing..." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"The invoice total is 128.50 USD.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r2_isolation/cassette-model-12bfc42c26dcfde5.cassette.json b/tests/_fixtures/cassettes/r2_isolation/cassette-model-12bfc42c26dcfde5.cassette.json new file mode 100644 index 0000000..574d0af --- /dev/null +++ b/tests/_fixtures/cassettes/r2_isolation/cassette-model-12bfc42c26dcfde5.cassette.json @@ -0,0 +1,54 @@ +{ + "fingerprint": "12bfc42c26dcfde51bc518bfde00c4d1345ef6020c1eeaf37da93ca386858718", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Workspace B acknowledged.\n- [user] Second B turn.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Second B turn.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Workspace B acknowledged." + }, + { + "role": "user", + "content": "Second B turn.\nSecond B turn." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Still workspace B.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r2_isolation/cassette-model-2d6d85edee8b24c3.cassette.json b/tests/_fixtures/cassettes/r2_isolation/cassette-model-2d6d85edee8b24c3.cassette.json deleted file mode 100644 index 03350da..0000000 --- a/tests/_fixtures/cassettes/r2_isolation/cassette-model-2d6d85edee8b24c3.cassette.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "fingerprint": "2d6d85edee8b24c300666391203a943b194de49b9a64c0e9804cda149a2ed073", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Second A turn.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Workspace A acknowledged." - }, - { - "role": "user", - "content": "Second A turn.\nSecond A turn." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Still workspace A.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r2_isolation/cassette-model-2f6cb6da00d596c3.cassette.json b/tests/_fixtures/cassettes/r2_isolation/cassette-model-2f6cb6da00d596c3.cassette.json new file mode 100644 index 0000000..fe3448f --- /dev/null +++ b/tests/_fixtures/cassettes/r2_isolation/cassette-model-2f6cb6da00d596c3.cassette.json @@ -0,0 +1,50 @@ +{ + "fingerprint": "2f6cb6da00d596c34e93fc303aaffbf924863db41a71767dc4e7e6a8824fffba", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [user] Hello from A.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Hello from A.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "user", + "content": "Hello from A.\nHello from A." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Workspace A acknowledged.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r2_isolation/cassette-model-5df3b81e677c98d6.cassette.json b/tests/_fixtures/cassettes/r2_isolation/cassette-model-5df3b81e677c98d6.cassette.json deleted file mode 100644 index b4c0906..0000000 --- a/tests/_fixtures/cassettes/r2_isolation/cassette-model-5df3b81e677c98d6.cassette.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "fingerprint": "5df3b81e677c98d6c3cf2dbad240708a7b39c62dccb628ba7f7e19c8d5cccffd", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Second B turn.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Workspace B acknowledged." - }, - { - "role": "user", - "content": "Second B turn.\nSecond B turn." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Still workspace B.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r2_isolation/cassette-model-6d759c6c949a15c4.cassette.json b/tests/_fixtures/cassettes/r2_isolation/cassette-model-6d759c6c949a15c4.cassette.json deleted file mode 100644 index dfb485a..0000000 --- a/tests/_fixtures/cassettes/r2_isolation/cassette-model-6d759c6c949a15c4.cassette.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "fingerprint": "6d759c6c949a15c4d57aba6fdcc94eb3f7e9e89e353299eaa4ac1c66ed071a7a", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Hello from A.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Hello from A.\nHello from A." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Workspace A acknowledged.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r2_isolation/cassette-model-7445d5ead1814f1e.cassette.json b/tests/_fixtures/cassettes/r2_isolation/cassette-model-7445d5ead1814f1e.cassette.json new file mode 100644 index 0000000..546b6f6 --- /dev/null +++ b/tests/_fixtures/cassettes/r2_isolation/cassette-model-7445d5ead1814f1e.cassette.json @@ -0,0 +1,54 @@ +{ + "fingerprint": "7445d5ead1814f1ec49ab659126d1cec546c8769ad4bdf1e09a99fedb1312ce0", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Workspace A acknowledged.\n- [user] Second A turn.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Second A turn.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Workspace A acknowledged." + }, + { + "role": "user", + "content": "Second A turn.\nSecond A turn." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Still workspace A.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r2_isolation/cassette-model-8e74cd7a8a60c7f8.cassette.json b/tests/_fixtures/cassettes/r2_isolation/cassette-model-8e74cd7a8a60c7f8.cassette.json new file mode 100644 index 0000000..4481825 --- /dev/null +++ b/tests/_fixtures/cassettes/r2_isolation/cassette-model-8e74cd7a8a60c7f8.cassette.json @@ -0,0 +1,50 @@ +{ + "fingerprint": "8e74cd7a8a60c7f8649ec2929521f8b7a3e8e3149f33c5c0aae1bec7006461f6", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [user] Hello from B.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Hello from B.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "user", + "content": "Hello from B.\nHello from B." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Workspace B acknowledged.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r2_isolation/cassette-model-d20387e834184f22.cassette.json b/tests/_fixtures/cassettes/r2_isolation/cassette-model-d20387e834184f22.cassette.json deleted file mode 100644 index 8cb6dde..0000000 --- a/tests/_fixtures/cassettes/r2_isolation/cassette-model-d20387e834184f22.cassette.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "fingerprint": "d20387e834184f222f0a3cda065f83f6c0187fbda97c5c3412b01e6645527ccc", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Hello from B.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Hello from B.\nHello from B." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Workspace B acknowledged.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r3_control_plane/cassette-model-37fb8eb582d3d681.cassette.json b/tests/_fixtures/cassettes/r3_control_plane/cassette-model-37fb8eb582d3d681.cassette.json new file mode 100644 index 0000000..d0d33ca --- /dev/null +++ b/tests/_fixtures/cassettes/r3_control_plane/cassette-model-37fb8eb582d3d681.cassette.json @@ -0,0 +1,50 @@ +{ + "fingerprint": "37fb8eb582d3d681aea859ad100d1c6d944d3bb3c00d8396e214446d597cb65d", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [user] Anything to report?\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Anything to report?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "user", + "content": "Anything to report?\nAnything to report?" + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Acknowledged.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r3_control_plane/cassette-model-466f8fe2c8e497df.cassette.json b/tests/_fixtures/cassettes/r3_control_plane/cassette-model-466f8fe2c8e497df.cassette.json deleted file mode 100644 index 41d2db2..0000000 --- a/tests/_fixtures/cassettes/r3_control_plane/cassette-model-466f8fe2c8e497df.cassette.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "fingerprint": "466f8fe2c8e497df5654533d8d4781e694e534a97782ba8a60cdf07d6fe1884d", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Anything to report?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Anything to report?\nAnything to report?" - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Acknowledged.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r4_recovery/cassette-model-0ea1fb58d9fb407a.cassette.json b/tests/_fixtures/cassettes/r4_recovery/cassette-model-0ea1fb58d9fb407a.cassette.json deleted file mode 100644 index 57b5714..0000000 --- a/tests/_fixtures/cassettes/r4_recovery/cassette-model-0ea1fb58d9fb407a.cassette.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "fingerprint": "0ea1fb58d9fb407ad9748b096f5a661d7ef8a8ff4c170b4d2a631e7515fbec14", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Keep going with more context.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Recovered after a server error." - }, - { - "role": "user", - "content": "Keep going with more context.\nKeep going with more context." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 400, - "content_type": "application/json", - "body": "{\"error\": {\"message\": \"This model's maximum context length is 8192 tokens. However, your messages resulted in 9001 tokens.\", \"type\": \"invalid_request_error\", \"code\": \"context_length_exceeded\"}}" - }, - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Recovered after compressing context.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r4_recovery/cassette-model-1010af940122b23a.cassette.json b/tests/_fixtures/cassettes/r4_recovery/cassette-model-1010af940122b23a.cassette.json deleted file mode 100644 index 30aad9a..0000000 --- a/tests/_fixtures/cassettes/r4_recovery/cassette-model-1010af940122b23a.cassette.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "fingerprint": "1010af940122b23a5bb9238cd9cce1487e0950cf0a9c56196abf10ad3e7f4287", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Summarize the situation.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Summarize the situation.\nSummarize the situation." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 429, - "content_type": "application/json", - "body": "{\"error\": {\"message\": \"Rate limit reached for requests\", \"type\": \"rate_limit_error\", \"code\": \"rate_limit_exceeded\"}}" - }, - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Recovered after a rate limit.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r4_recovery/cassette-model-22cfa61700986a25.cassette.json b/tests/_fixtures/cassettes/r4_recovery/cassette-model-22cfa61700986a25.cassette.json deleted file mode 100644 index 378ccef..0000000 --- a/tests/_fixtures/cassettes/r4_recovery/cassette-model-22cfa61700986a25.cassette.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "fingerprint": "22cfa61700986a25d1312d3388364f3c1f0f809b7edf67345f10671ce247a238", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: And now?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Recovered after a rate limit." - }, - { - "role": "user", - "content": "And now?\nAnd now?" - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 500, - "content_type": "application/json", - "body": "{\"error\": {\"message\": \"The server had an error\", \"type\": \"server_error\", \"code\": \"internal_error\"}}" - }, - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Recovered after a server error.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r4_recovery/cassette-model-43779b711adf1731.cassette.json b/tests/_fixtures/cassettes/r4_recovery/cassette-model-43779b711adf1731.cassette.json new file mode 100644 index 0000000..83dac03 --- /dev/null +++ b/tests/_fixtures/cassettes/r4_recovery/cassette-model-43779b711adf1731.cassette.json @@ -0,0 +1,59 @@ +{ + "fingerprint": "43779b711adf17317920c7e2267bc62651ff6051e24679142f60aba6cecbc14e", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Recovered after a rate limit.\n- [user] And now?\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: And now?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Recovered after a rate limit." + }, + { + "role": "user", + "content": "And now?\nAnd now?" + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 500, + "content_type": "application/json", + "body": "{\"error\": {\"message\": \"The server had an error\", \"type\": \"server_error\", \"code\": \"internal_error\"}}" + }, + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Recovered after a server error.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r4_recovery/cassette-model-5ea99feb8f3dcc24.cassette.json b/tests/_fixtures/cassettes/r4_recovery/cassette-model-5ea99feb8f3dcc24.cassette.json new file mode 100644 index 0000000..bfae456 --- /dev/null +++ b/tests/_fixtures/cassettes/r4_recovery/cassette-model-5ea99feb8f3dcc24.cassette.json @@ -0,0 +1,59 @@ +{ + "fingerprint": "5ea99feb8f3dcc24998d6d04553409d58ac6585b6d81bf9843efd36bab4f95fb", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Recovered after compressing context.\n- [user] Do the impossible thing.\n\n## Task Contract\n- Task ID: turn-4\n- Original user request: Do the impossible thing.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Recovered after compressing context." + }, + { + "role": "user", + "content": "Do the impossible thing.\nDo the impossible thing." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 400, + "content_type": "application/json", + "body": "{\"error\": {\"message\": \"The requested configuration is not supported by this model\", \"type\": \"invalid_request_error\", \"code\": \"unsupported_value\"}}" + }, + { + "status": 400, + "content_type": "application/json", + "body": "{\"error\": {\"message\": \"The requested configuration is not supported by this model\", \"type\": \"invalid_request_error\", \"code\": \"unsupported_value\"}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r4_recovery/cassette-model-71942fc109cbfbbc.cassette.json b/tests/_fixtures/cassettes/r4_recovery/cassette-model-71942fc109cbfbbc.cassette.json new file mode 100644 index 0000000..94f10a4 --- /dev/null +++ b/tests/_fixtures/cassettes/r4_recovery/cassette-model-71942fc109cbfbbc.cassette.json @@ -0,0 +1,59 @@ +{ + "fingerprint": "71942fc109cbfbbcce4902933bb340ee4363736ede9f671e82f454016b4085a7", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Recovered after a server error.\n- [user] Keep going with more context.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Keep going with more context.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Recovered after a server error." + }, + { + "role": "user", + "content": "Keep going with more context.\nKeep going with more context." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 400, + "content_type": "application/json", + "body": "{\"error\": {\"message\": \"This model's maximum context length is 8192 tokens. However, your messages resulted in 9001 tokens.\", \"type\": \"invalid_request_error\", \"code\": \"context_length_exceeded\"}}" + }, + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Recovered after compressing context.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r4_recovery/cassette-model-bfef2a5f8504ce5e.cassette.json b/tests/_fixtures/cassettes/r4_recovery/cassette-model-bfef2a5f8504ce5e.cassette.json new file mode 100644 index 0000000..f230294 --- /dev/null +++ b/tests/_fixtures/cassettes/r4_recovery/cassette-model-bfef2a5f8504ce5e.cassette.json @@ -0,0 +1,55 @@ +{ + "fingerprint": "bfef2a5f8504ce5e15c94f434203a17eeaf4544a8946ccd8f7fee92f2304872c", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [user] Summarize the situation.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Summarize the situation.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "user", + "content": "Summarize the situation.\nSummarize the situation." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 429, + "content_type": "application/json", + "body": "{\"error\": {\"message\": \"Rate limit reached for requests\", \"type\": \"rate_limit_error\", \"code\": \"rate_limit_exceeded\"}}" + }, + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Recovered after a rate limit.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r4_recovery/cassette-model-ffab8956d80a9c5c.cassette.json b/tests/_fixtures/cassettes/r4_recovery/cassette-model-ffab8956d80a9c5c.cassette.json deleted file mode 100644 index ffa77be..0000000 --- a/tests/_fixtures/cassettes/r4_recovery/cassette-model-ffab8956d80a9c5c.cassette.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "fingerprint": "ffab8956d80a9c5c25fea82fc9dab04e852d9dc507329393c3156825c915f810", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-4\n- Original user request: Do the impossible thing.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Recovered after compressing context." - }, - { - "role": "user", - "content": "Do the impossible thing.\nDo the impossible thing." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 400, - "content_type": "application/json", - "body": "{\"error\": {\"message\": \"The requested configuration is not supported by this model\", \"type\": \"invalid_request_error\", \"code\": \"unsupported_value\"}}" - }, - { - "status": 400, - "content_type": "application/json", - "body": "{\"error\": {\"message\": \"The requested configuration is not supported by this model\", \"type\": \"invalid_request_error\", \"code\": \"unsupported_value\"}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-1f122bf577f9e10e.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-1f122bf577f9e10e.cassette.json new file mode 100644 index 0000000..ff6a773 --- /dev/null +++ b/tests/_fixtures/cassettes/r5_learning/cassette-model-1f122bf577f9e10e.cassette.json @@ -0,0 +1,54 @@ +{ + "fingerprint": "1f122bf577f9e10ecedf65b26380379f372185e1742dbe416e7359cbc6da354c", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Noted the second step.\n- [user] Thanks, that is all.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Thanks, that is all.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Noted the second step." + }, + { + "role": "user", + "content": "Thanks, that is all.\nThanks, that is all." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"{\\\"title\\\": \\\"Tidy invoices\\\", \\\"trigger_phrases\\\": [\\\"tidy invoices\\\", \\\"sort invoices\\\"], \\\"steps\\\": [\\\"List the invoice folder\\\", \\\"Classify by month\\\", \\\"Move into folders\\\"], \\\"parameters\\\": [{\\\"name\\\": \\\"path\\\", \\\"description\\\": \\\"invoice folder\\\"}], \\\"pre_conditions\\\": [], \\\"confidence\\\": 0.7}\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-3f3d19a6e4450d6a.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-3f3d19a6e4450d6a.cassette.json deleted file mode 100644 index 61a500c..0000000 --- a/tests/_fixtures/cassettes/r5_learning/cassette-model-3f3d19a6e4450d6a.cassette.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "fingerprint": "3f3d19a6e4450d6ad6766569d84dd66431abcb255e84a5ffc75ccc0d85f52c6b", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Let me show you something.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Let me show you something.\nLet me show you something." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Noted the first step.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-4208c77b079bb4ef.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-4208c77b079bb4ef.cassette.json new file mode 100644 index 0000000..5a6622c --- /dev/null +++ b/tests/_fixtures/cassettes/r5_learning/cassette-model-4208c77b079bb4ef.cassette.json @@ -0,0 +1,21 @@ +{ + "fingerprint": "4208c77b079bb4ef55b376cb293373f234a23ec87ffcf9ca1736aa04f83d9940", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "user", + "content": "You are a workflow prediction assistant. Based on the user's current\noperational context, predict the most likely next action(s).\n\n## Current Context\n- Application: com.alibaba.alilang3.osx\n- Window: 阿里郎\n- Recent actions: fs.change:/Users/jason/work/github/leapflow/src/leapflow/tools/__pycache__/execution_context.cpython-314.pyc → fs.change:/Users/jason/work/github/leapflow/src/leapflow/tools/__pycache__/shell_tools.cpython-314.pyc → fs.change:/Users/jason/work/github/leapflow/src/leapflow/tools/__pycache__/name_resolver.cpython-314.pyc → fs.change:/Users/jason/work/github/leapflow/src/leapflow/cli/__pycache__/context.cpython-314.pyc → app.focus_change:com.alibaba.alilang3.osx\n- Time bucket: wed_11\n\n## Instructions\nReturn a JSON array of predicted next actions. Each element should have:\n {\"action\": \"\", \"confidence\": <0.0-1.0>, \"reasoning\": \"\"}\n\nReturn at most 3 predictions. Only include predictions with confidence > 0.3.\nReturn ONLY the JSON array, no additional text." + } + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Noted the second step.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-4243a112bcb29cbd.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-4243a112bcb29cbd.cassette.json deleted file mode 100644 index 8ccff8f..0000000 --- a/tests/_fixtures/cassettes/r5_learning/cassette-model-4243a112bcb29cbd.cassette.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "fingerprint": "4243a112bcb29cbd7863d2c7990d2a401bf64990ae703b6c59c6d04e900b9e95", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Thanks, that is all.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Noted the second step." - }, - { - "role": "user", - "content": "Thanks, that is all.\nThanks, that is all." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"{\\\"title\\\": \\\"Tidy invoices\\\", \\\"trigger_phrases\\\": [\\\"tidy invoices\\\", \\\"sort invoices\\\"], \\\"steps\\\": [\\\"List the invoice folder\\\", \\\"Classify by month\\\", \\\"Move into folders\\\"], \\\"parameters\\\": [{\\\"name\\\": \\\"path\\\", \\\"description\\\": \\\"invoice folder\\\"}], \\\"pre_conditions\\\": [], \\\"confidence\\\": 0.7}\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-7edc8015023176fe.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-7edc8015023176fe.cassette.json new file mode 100644 index 0000000..2975b89 --- /dev/null +++ b/tests/_fixtures/cassettes/r5_learning/cassette-model-7edc8015023176fe.cassette.json @@ -0,0 +1,54 @@ +{ + "fingerprint": "7edc8015023176feaa2d313374596f0c393310e7c86dfbd8c90ecb34e3a767a7", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Done — nothing further needed.\n- [user] Thanks, that is all.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Thanks, that is all.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Done — nothing further needed." + }, + { + "role": "user", + "content": "Thanks, that is all.\nThanks, that is all." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Done \\u2014 nothing further needed.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-90905a04cf1761fb.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-90905a04cf1761fb.cassette.json new file mode 100644 index 0000000..2474fb1 --- /dev/null +++ b/tests/_fixtures/cassettes/r5_learning/cassette-model-90905a04cf1761fb.cassette.json @@ -0,0 +1,50 @@ +{ + "fingerprint": "90905a04cf1761fb9b06dfa02247846d08201ae48ff08bebeeb99e26090927e1", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [user] Let me show you something.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Let me show you something.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "user", + "content": "Let me show you something.\nLet me show you something." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Noted the first step.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-96e0522afedb82cd.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-96e0522afedb82cd.cassette.json new file mode 100644 index 0000000..cfe4567 --- /dev/null +++ b/tests/_fixtures/cassettes/r5_learning/cassette-model-96e0522afedb82cd.cassette.json @@ -0,0 +1,54 @@ +{ + "fingerprint": "96e0522afedb82cd1e802525d50785aa0a0681be9453517a23c82755d7c77445", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Noted the first step.\n- [user] Now sort them by month.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Now sort them by month.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Noted the first step." + }, + { + "role": "user", + "content": "Now sort them by month.\nNow sort them by month." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Noted the second step.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-a9901ff84a60696a.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-a9901ff84a60696a.cassette.json new file mode 100644 index 0000000..ba94732 --- /dev/null +++ b/tests/_fixtures/cassettes/r5_learning/cassette-model-a9901ff84a60696a.cassette.json @@ -0,0 +1,62 @@ +{ + "fingerprint": "a9901ff84a60696a1f44e02caad29c875809da0fa0383f2af30f6eaee3751d13", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [assistant] Noted the second step.\n- [user] Thanks, that is all.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Thanks, that is all.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "assistant", + "content": "Noted the second step." + }, + { + "role": "user", + "content": "Thanks, that is all.\nThanks, that is all." + }, + { + "role": "assistant", + "content": "{\"title\": \"Tidy invoices\", \"trigger_phrases\": [\"tidy invoices\", \"sort invoices\"], \"steps\": [\"List the invoice folder\", \"Classify by month\", \"Move into folders\"], \"parameters\": [{\"name\": \"path\", \"description\": \"invoice folder\"}], \"pre_conditions\": [], \"confidence\": 0.7}" + }, + { + "role": "user", + "content": "Tool result (path):\n{\"ok\": false, \"error\": \"Unknown tool: path\", \"error_type\": \"unknown_tool\", \"retryable\": true}\nSYSTEM: The previous tool call used an unavailable tool name. Original tool: path. Resolution: unknown (no exact canonical tool name match). Suggested canonical tools: capability_expand, code_intel, code_search, config_get, config_list. Available tools include: capability_expand, code_intel, code_search, config_get, config_list, config_set, delegate_task, edit_file, env_info, file_find, file_list, file_read. Retry once using an exact canonical tool name from the available list and valid arguments. Do not invent tool names, use aliases, or infer a tool from argument shape; answer without a tool if no exact tool fits." + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Done \\u2014 nothing further needed.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-c2e43feadd61e3d1.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-c2e43feadd61e3d1.cassette.json deleted file mode 100644 index 5b1dcf2..0000000 --- a/tests/_fixtures/cassettes/r5_learning/cassette-model-c2e43feadd61e3d1.cassette.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "fingerprint": "c2e43feadd61e3d1e70604bdc1ef3f618cea986c6ef76a1b6b785c8883c9c86f", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-3\n- Original user request: Thanks, that is all.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Noted the second step." - }, - { - "role": "user", - "content": "Thanks, that is all.\nThanks, that is all." - }, - { - "role": "assistant", - "content": "{\"title\": \"Tidy invoices\", \"trigger_phrases\": [\"tidy invoices\", \"sort invoices\"], \"steps\": [\"List the invoice folder\", \"Classify by month\", \"Move into folders\"], \"parameters\": [{\"name\": \"path\", \"description\": \"invoice folder\"}], \"pre_conditions\": [], \"confidence\": 0.7}" - }, - { - "role": "user", - "content": "Tool result (path):\n{\"ok\": false, \"error\": \"Unknown tool: path\", \"error_type\": \"unknown_tool\", \"retryable\": true}\nSYSTEM: The previous tool call used an unavailable tool name. Original tool: path. Resolution: unknown (no exact canonical tool name match). Suggested canonical tools: capability_expand, code_intel, code_search, config_get, config_list. Available tools include: capability_expand, code_intel, code_search, config_get, config_list, config_set, delegate_task, edit_file, env_info, file_find, file_list, file_read. Retry once using an exact canonical tool name from the available list and valid arguments. Do not invent tool names, use aliases, or infer a tool from argument shape; answer without a tool if no exact tool fits." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Done \\u2014 nothing further needed.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r5_learning/cassette-model-d10ed33981125492.cassette.json b/tests/_fixtures/cassettes/r5_learning/cassette-model-d10ed33981125492.cassette.json deleted file mode 100644 index 142d783..0000000 --- a/tests/_fixtures/cassettes/r5_learning/cassette-model-d10ed33981125492.cassette.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "fingerprint": "d10ed339811254925842efddda2fd86f23594b7b3b15c2967507ff2f2e77c9fb", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-2\n- Original user request: Now sort them by month.\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "assistant", - "content": "Noted the first step." - }, - { - "role": "user", - "content": "Now sort them by month.\nNow sort them by month." - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Noted the second step.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_fixtures/cassettes/r6_lifecycle/cassette-model-00a92a39ba378e96.cassette.json b/tests/_fixtures/cassettes/r6_lifecycle/cassette-model-00a92a39ba378e96.cassette.json new file mode 100644 index 0000000..e659298 --- /dev/null +++ b/tests/_fixtures/cassettes/r6_lifecycle/cassette-model-00a92a39ba378e96.cassette.json @@ -0,0 +1,50 @@ +{ + "fingerprint": "00a92a39ba378e96488c2e11fa76a4cca9c7e161e2cc518b21a5a3fb7bfbe958", + "note": "captured in seed mode", + "request": { + "model": "cassette-model", + "stream": false, + "messages": [ + { + "role": "system", + "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex pattern across a directory tree (ripgrep-backed). Requires a regex pattern. NOT for listing or browsing directory contents — use file_list for that. Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n8. **Recall past work**: When the user references prior tasks or asks about past work, use session_search to recall relevant context from previous sessions.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n\n## Recent Session Summary\n- [user] Are you there?\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Are you there?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" + }, + { + "role": "user", + "content": "Are you there?\nAre you there?" + } + ], + "tools": [ + "capability_expand", + "code_intel", + "code_search", + "config_get", + "config_list", + "env_info", + "file_find", + "file_list", + "file_read", + "git_query", + "lint_check", + "memory_search", + "repo_map", + "research_note", + "schedule_reentry", + "skill_view", + "skills_list", + "terminal_list", + "terminal_read", + "test_run", + "text_search", + "time_get", + "web_fetch" + ] + }, + "responses": [ + { + "status": 200, + "content_type": "application/json", + "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Still here.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" + } + ] +} diff --git a/tests/_fixtures/cassettes/r6_lifecycle/cassette-model-8b284c8b613c8be3.cassette.json b/tests/_fixtures/cassettes/r6_lifecycle/cassette-model-8b284c8b613c8be3.cassette.json deleted file mode 100644 index 8f4bf0f..0000000 --- a/tests/_fixtures/cassettes/r6_lifecycle/cassette-model-8b284c8b613c8be3.cassette.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "fingerprint": "8b284c8b613c8be3b301712c01c84995acee6ac15d554192185a92ce2a91049f", - "note": "captured in seed mode", - "request": { - "model": "cassette-model", - "stream": false, - "messages": [ - { - "role": "system", - "content": "You are LeapFlow, an intelligent assistant that can both converse naturally and take real actions on the user's computer.\n\n## Capabilities\nThe tool index below lists **every** registered tool by name and a one-line summary — this is the complete\ncapability contract; nothing else exists. Only a subset is directly callable this turn (via native tool calling,\nnot a JSON block in your reply). If you need a tool from the index that is not yet callable, call\n`capability_expand` with its category name first — the matching tools become callable immediately after.\n- **file_list**(path, pattern, depth): List files and directories at a given path. Use depth=1 or depth=2 to get a recursive tree in one call instead of listing each sub-directory separately.\n- **file_read**(path, max_lines, start_line, max_chars, mode): Read text file content with adaptive context governance. For large or unfamiliar files, prefer mode='outline' or mode='symbols' first, then use mode='raw' with start_line/max_lines for the specific range you actually need. For LeapFlow's own settings, use config_list / config_get / config_set — its config files are outside the workspace and not readable here.\n- **file_write**(path, content, mode) [capability_expand category: write]: Write content to a file (overwrite or append).\n- **code_search**(pattern, patterns, path, glob, ignore_case, multiline, max_results, context_lines): Search file CONTENTS by regex across a directory tree (ripgrep-backed). Prefer this over shell_run grep: faster, skips VCS/dependency/build dirs, and returns structured path:line:column matches. Batch related lookups into ONE call via `patterns` (OR-combined, single pass) instead of issuing several separate searches. Use file_read for the surrounding context of a hit.\n- **file_find**(glob, path, max_results): Find files by a recursive glob pattern under a base path (e.g. '**/test_*.py' or '*.md'). Prefer this over shell_run find; skips VCS/dependency/build dirs.\n- **edit_file**(path, edits, dry_run, diff) [capability_expand category: file]: Apply targeted, anchored search-replace edits to an EXISTING text file (use file_write to create/overwrite). Each edit is {original_text, new_text, replace_all?}; original_text must match exactly and uniquely (or set replace_all) — a non-unique or missing anchor is rejected so files are never corrupted. Set dry_run to preview. Alternatively pass a unified 'diff' to apply its hunks as anchored edits. Far cheaper and safer than rewriting a whole file.\n- **code_intel**(path, operation): Precise document symbols (outline) for a source file: classes, functions, and methods with line ranges. Python uses an exact AST parse; other languages use a keyword-prefix scan. Prefer over file_read mode=symbols for accurate navigation before editing. Read-only.\n- **repo_map**(path): Compact project orientation for a repository root: languages, detected test/lint commands, top-level structure, entry points, manifest, and VCS branch. Call this first when entering an unfamiliar codebase. Read-only.\n- **shell_run**(command, cwd, timeout) [capability_expand category: shell]: Execute a one-shot shell command with timeout protection. Runs in the active workspace; paths resolving outside it are refused. Reach for a structured tool first when one fits — web_fetch for anything over HTTP(S), git_query/scm_sync for git, code_search/file_find/file_read for the repo, config_get/config_set for LeapFlow's own settings — because those report typed results, while a failed shell command can only be diagnosed from its exit code and stderr. Every shell run counts as an external side effect, so a failure stops the rest of the batch and is not retried automatically.\n- **scm_sync**(action, cwd, remote, pull_ref, push_ref, timeout) [capability_expand category: scm]: Run a typed git SCM action. Use this instead of shell_run for git pull/push/status. For 'pull origin main then push', set action='pull_then_push', remote='origin', pull_ref='main', and omit push_ref so LeapFlow pushes the current local branch.\n- **git_query**(action, cwd, ref, path, staged, max_count, stat): Read-only structured git inspection: action=diff|log|status|branch|show. Prefer over shell_run for reading repo state — output is clipped, redacted, and log/branch are parsed into structured fields. Use scm_sync for pull/push.\n- **git_write**(action, cwd, message, stage_all, name, ref, create) [capability_expand category: scm]: Mutating git actions: action=commit (message, stage_all), branch (create+switch), checkout (switch; create=true for -b). Approval-gated. Use scm_sync for pull/push and git_query for reads.\n- **time_get**(): Get current date and time.\n- **env_info**(): Get system environment information (OS, Python version, cwd).\n- **text_search**(text, pattern): Search for a regex pattern in text.\n- **text_replace**(text, old, new, count) [capability_expand category: write]: Replace occurrences of a substring in text.\n- **skills_list**(query, category, source): List available learned skills. Use when user asks about capabilities or you need a specific skill.\n- **skill_view**(name): View the full content of a specific skill document.\n- **memory_search**(query, limit): Search agent memory for relevant past experiences, observations, and facts.\n- **memory_add**(content, kind) [capability_expand category: write]: Store a new observation or insight in memory for future reference.\n- **research_note**(kind, text): Record a compact, structured note about the current task's state so it survives context compression on long / multi-step tasks. Use for durable findings, open questions still to resolve, decisions / excluded paths, and the immediate next step. One concise sentence per note.\n- **schedule_reentry**(kind, reason, delay_seconds, event_match, max_reentries, deadline_seconds): Register a re-entry so this task can resume later from its current orientation (findings / open questions / next step). Use when work must pause and continue after a delay (kind=time) or when a matching platform event arrives (kind=event), instead of finishing now. The research-ledger state is carried over automatically.\n- **capability_expand**(category): Fetch the full callable schema for every tool in a capability category. Current non-core categories that require expansion: config, delegate, file, gateway, hub, scm, shell, terminal, write. The compact tool index always lists every registered tool by name and a one-line summary tagged with its exact capability_expand category, but only a static low-risk subset is directly callable each turn. If you need a tool from the index that is not yet callable, call capability_expand with the exact category shown next to it; the matching tools become callable in this turn. Never invent a tool name — expand the category instead.\n- **delegate_task**(goal, context) [capability_expand category: delegate]: Delegate a complex sub-task to an isolated subagent. The subagent gets a fresh context and restricted tool access. Use when a task is self-contained and can be solved independently.\n- **test_run**(command, cwd, timeout): Run the project's test suite and return structured results (framework, passed/failed counts, failing tests). Auto-detects the runner (pytest/npm/go/cargo) or uses a configured/explicit command; executes via the governed shell. ok=true means the runner executed — see 'success' for pass/fail.\n- **lint_check**(command, cwd, timeout): Run the project's linter and return a structured clean/issue result. Auto-detects the linter (ruff/eslint/go vet/clippy) or uses a configured/explicit command; executes via the governed shell. ok=true means the linter ran — see 'clean'.\n- **terminal_open**(command, cwd, shell) [capability_expand category: terminal]: Open a PERSISTENT shell session (REPL/dev server/watch), returning a session_id for terminal_send/read/close. Disabled unless tools.terminal_session_enabled is set. For one-shot commands use shell_run instead.\n- **terminal_send**(session_id, input, wait) [capability_expand category: terminal]: Send a line of input to a persistent terminal session and return output captured shortly after.\n- **terminal_read**(session_id, wait): Drain buffered output from a persistent terminal session (optionally waiting briefly first).\n- **terminal_close**(session_id) [capability_expand category: terminal]: Terminate a persistent terminal session and release its process group.\n- **terminal_list**(): List active persistent terminal sessions.\n- **config_list**(category, limit): List LeapFlow's own writable settings (model, provider, daemon, memory, perception, gateway, …) with current values. Use this to discover the exact key before changing anything. Optionally narrow by `category`. This is the only correct way to inspect LeapFlow configuration — never read config files from disk.\n- **config_get**(key): Read one LeapFlow setting by key (e.g. 'llm.model', 'daemon.log_level'), returning its current value, type, scopes, and whether a change needs a daemon restart. Never read LeapFlow config files from disk — use this.\n- **config_set**(key, value, scope) [capability_expand category: config]: Change one LeapFlow setting by key, e.g. switch the model with key='llm.model'. Values are validated and coerced; credentials are stored in the vault automatically. Call config_list or config_get first if unsure of the key. The result states whether a `leap daemon restart` is required. Never edit LeapFlow config files directly.\n- **web_fetch**(url, select, timeout, max_bytes): Read a URL over HTTP(S) and get back extracted, context-sized content: parsed JSON for API endpoints, readable text plus links for web pages. Use this for anything on the internet — prices, docs, releases, articles — instead of running curl through shell_run: it reports real HTTP status codes, retries rate limits on its own, and is a plain read so a retry is always safe. For JSON APIs pass `select` with a dotted path (e.g. 'chart.result.0.meta') to return just that part instead of the whole payload.\n- **hub_push**(skill_name, visibility, version) [capability_expand category: hub]: Push a local skill to the ModelScope Hub for sharing or backup.\n- **hub_pull**(repo_id, version) [capability_expand category: hub]: Pull a skill from the ModelScope Hub to install locally.\n- **hub_search**(query) [capability_expand category: hub]: Search for skills on the Hub by keyword or description.\n- **hub_sync**(mode, dry_run) [capability_expand category: hub]: Preview or execute sync between local skills and Hub.\n- **platform_action**(platform, action, payload, backend_kind) [capability_expand category: gateway]: Execute an exact registered business action on an external platform through LeapFlow's App Connector layer. Actions must be copied from the App Connector Capability Index and are addressed as domain.operation, e.g. im.send_message or docs.create_markdown. All business fields (chat_id, text, query, etc.) MUST be placed inside `payload`, never at the top level. Example: {\"platform\":\"feishu\",\"action\":\"im.send_message\",\"payload\":{\"chat_id\":\"oc_xxx\",\"text\":\"hello\"}}. Do not invent action names, do not use management actions such as list/guide/connect/status here.\n- **platform_connect**(action, platform, credentials, options, checkpoint) [capability_expand category: gateway]: List, guide, connect, disconnect, remove, or check status for external platforms using the App Connector management namespace. Supports REST and CLI backends. Use this for management actions such as list/guide/preflight/connect/status; use platform_action only for exact registered business actions.\n- **gateway_send**(platform, chat_id, text, thread_id) [capability_expand category: gateway]: Send a message to a connected external platform (Feishu group, Telegram chat, DingTalk conversation, etc.). Requires the platform to be connected via gateway_connect first. Use gateway_connect with action='list' to see connected platforms and available chat IDs.\n- **gateway_connect**(action, platform, credentials, options) [capability_expand category: gateway]: Connect, configure, or manage external platform integrations (Feishu, DingTalk, Telegram, Slack, Discord, etc.). Conversational flow: 1) call 'guide' to get setup steps + required fields, 2) present the steps to the user and ask for ALL required credentials in a single message, 3) call 'connect' with the credentials. Goal: complete in 1–2 user turns. NEVER include credential values in your text response.\n- **session_search**(query, limit) [capability_expand category: unclassified]: Search past conversation sessions for relevant context.\n\n## App Connector Capability Index\nLeapFlow can onboard and manage external apps through `platform_connect` and execute exact registered business actions through `platform_action`.\nFor requests about connecting, setting up, configuring, enabling, or managing a supported app, use `platform_connect` first instead of generating SDK/Webhook sample code.\n`platform_connect.action` is the management namespace: list, guide, preflight, connect, disconnect, remove, status, events_start, events_stop, events_status.\n`platform_action.action` is only for exact registered platform business actions listed below, such as `im.send_message`; never use management actions like `list` or `guide` there.\nAll business fields MUST go inside `payload`; top-level keys are only `platform`, `action`, and `payload`.\nDo not invent platform IDs or platform action names. If the needed action is not listed, ask for discovery/clarification instead of guessing.\nUse `platform_connect` with `action='guide'` and the matching `platform` to start onboarding; use `action='list'` when the app is unclear.\nWhen a pending onboarding state is present, continue from that state with `platform_connect` instead of asking the user to restate the app.\nSupported apps:\n- `api_server`: API Server (OpenAI Compatible) (category=api; backend=adapter; platform_action actions=none registered)\n- `dingtalk`: 钉钉 (DingTalk) (category=im; backend=adapter; platform_action actions=none registered)\n- `feishu`: 飞书 (Feishu/Lark) (category=im; backend=cli)\n - `calendar.create_event` payload={summary*, start_time*, end_time*, attendees} [write/high]\n - `docs.create_markdown` payload={title*, markdown*, folder_token} [write/medium]\n - `drive.search` payload={query*, limit} [read/medium]\n - `im.add_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.download_resource` payload={message_id*, file_key*, type*} [read/low]\n - `im.get_messages` payload={message_ids*} [read/low]\n - `im.list_chats` payload={page_size} [read/low]\n - `im.list_messages` payload={chat_id*} [read/low]\n - `im.list_thread_messages` payload={thread*} [read/low]\n - `im.remove_reaction` payload={message_id*, emoji_type*} [write/low]\n - `im.reply_message` payload={message_id*, text*} [send/high]\n - `im.search_chats` payload={query*, page_size} [read/low]\n - `im.search_messages` payload={query*} [read/medium]\n - `im.send_message` payload={chat_id*, text*, thread_id} [send/high]\n - `im.update_card` payload={token*, card*} [write/medium]\n - `im.update_message` payload={message_id*, text*} [write/medium]\n - `mail.search_unread` payload={query, limit} [read/high]\n - `sheets.append_row` payload={spreadsheet_token*, sheet_id*, values*} [write/medium]\n - `task.create` payload={title*, description, due_time} [write/medium]\n- `telegram`: Telegram (category=social; backend=adapter; platform_action actions=none registered)\n- `webhook`: Webhook (Generic) (category=webhook; backend=adapter; platform_action actions=none registered)\n\n## Tool Usage\nTools are normally invoked through the native function-calling mechanism, not by writing JSON in your reply\ntext. Only if the provider signals that native function calling is unavailable for this turn, fall back to a\nsingle JSON code block: `{\"name\": \"tool_name\", \"arguments\": {\"key\": \"value\"}}` — use this fallback format\nonly, never both. Only call a tool whose exact name appears in the tool index above and is currently callable\n(or reachable via `capability_expand`). Never invent, rename, alias, or guess a tool name, platform ID, or\nplatform action from argument shape or wording — if the index does not list it, it does not exist.\n`platform_connect.action` (list/guide/preflight/connect/disconnect/remove/status/events_start/events_stop/\nevents_status) is the App Connector management namespace; `platform_action.action` only accepts exact\nregistered business actions such as `im.send_message` shown in the App Connector Capability Index — never mix\nthe two namespaces. If a tool call returns an unknown/unavailable result, use the returned suggestions or\navailable names for a single retry instead of trying further variations of the same guess.\n\n**Side-effect action rule** (`platform_action` with effect=send/write/execute):\n- Call each unique action+payload **exactly once**. Never include duplicates in the same turn.\n- Once the result returns `\"completed\": true`, that action is DONE for this task. Do NOT call it again\n in any subsequent turn — immediately summarize the result for the user instead.\n- The system enforces idempotency: duplicate calls are blocked and will not execute.\n- If the user explicitly requests sending/writing multiple times, use distinct payloads per call.\n\n**Resource identifier provenance rule**:\n- NEVER fabricate, guess, or infer resource identifiers (chat_id, message_id, file_key, user_id, etc.).\n Every resource ID used in a side-effect action MUST come from a successful API response in this session.\n- If a read/list action fails (e.g. authorization error), you do NOT have valid resource IDs.\n Report the failure to the user — do NOT attempt the dependent write/send action with a guessed ID.\n- When a tool result contains `\"llm_instruction\"`, follow it exactly.\n\n## Guidelines\n1. **Direct answers first**: If you already know the answer, respond directly without tools.\n2. **Avoid redundant tool calls**: Do not call the same tool with the same arguments more than once in the same user turn. When an existing tool result already answers the user's request, stop calling tools and answer directly.\n3. **Use tools proactively**: When the user asks about files, time, system state, or needs actions performed, use the appropriate tool.\n4. **Chain tools when needed**: You can call multiple tools in sequence (e.g., list files → read file → summarize).\n5. **Handle failures gracefully**: If a tool fails, explain what went wrong and suggest alternatives. If it failed because of an unknown tool/platform/action name, retry once with an exact name from the returned suggestions, then explain rather than keep guessing.\n6. **Summarize results naturally**: After tool execution, synthesize the results into a helpful answer rather than dumping raw output.\n7. **Stay conversational**: Maintain a natural, helpful tone. Acknowledge context from earlier in the conversation.\n\n## Coding & Verification\nWhen working with code, prefer the precise built-in tools over ad-hoc shell: use `repo_map` to orient in an\nunfamiliar project, `code_search`/`file_find` to locate and `code_intel` for symbols, `edit_file` (anchored\nsearch-replace, or a unified `diff`) to change files — never rewrite a whole file to change a few lines — and\n`git_query` to inspect diffs/log. After edits, check `syntax_ok` in the result and run `test_run`/`lint_check`\nbefore declaring the work done. Batch independent read-only calls (search/read/query) into a single turn — they\nrun in parallel.\n\n## Presentation Style\n1. **Polished Markdown only**: Format user-facing answers with clean Markdown headings, short paragraphs, and concise bullets. Use tables only when they improve comparison or scanning.\n2. **Terminal-friendly layout**: Keep lines readable in a TUI; avoid dense walls of text, deeply nested lists, oversized ASCII art, or heavy visual blocks.\n3. **Elegant emphasis**: Use bold text sparingly for key terms and conclusions. Avoid excessive emojis, decorative symbols, repeated separators, or visual noise.\n4. **Theme-safe colors**: Do not emit ANSI escape codes, HTML color tags, Rich markup, or hardcoded color names. Rely on the TUI theme to render Markdown professionally.\n5. **No leaked tool protocol**: Never show tool-call JSON, internal schemas, raw observations, tool result payloads, or hidden reasoning in the final answer unless the user explicitly asks for raw/debug output. Treat any prior `{\"name\": ..., \"arguments\": ...}` blocks and `Tool result (...)` messages as internal execution context only.\n6. **Professional closure**: End with a concise conclusion or next step when helpful; avoid rambling after the useful answer is complete.\n\nWhen finished with all tool calls, respond normally without a JSON block, tool-call transcript, or process log.\n\n## Task Contract\n- Task ID: turn-1\n- Original user request: Are you there?\n- Workspace root: \n- Allowed roots: \n- Treat relative project paths as relative to the workspace root; never infer `.` as the project root when a workspace root is provided.\n- Workspace boundary is enforced by tools: do not read, search, edit, or run commands against paths outside the allowed roots unless the user explicitly requests an external path and the tool/approval policy permits it.\n- LeapFlow workspace config is optional at `/.leapflow/config.yaml`; runtime config is loaded from `~/.leapflow/config/user.yaml` and `~/.leapflow/profiles//config/*.yaml`.\n- Preserve this task contract across summarization, compression, tool loops, and memory retrieval.\n" - }, - { - "role": "user", - "content": "Are you there?\nAre you there?" - } - ], - "tools": [ - "capability_expand", - "code_intel", - "code_search", - "config_get", - "config_list", - "env_info", - "file_find", - "file_list", - "file_read", - "git_query", - "lint_check", - "memory_search", - "repo_map", - "research_note", - "schedule_reentry", - "skill_view", - "skills_list", - "terminal_list", - "terminal_read", - "test_run", - "text_search", - "time_get", - "web_fetch" - ] - }, - "responses": [ - { - "status": 200, - "content_type": "application/json", - "body": "{\"id\": \"chatcmpl-cassette\", \"object\": \"chat.completion\", \"model\": \"cassette-model\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Still here.\"}, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 64, \"completion_tokens\": 16, \"total_tokens\": 80}}" - } - ] -} diff --git a/tests/_harness/leapd.py b/tests/_harness/leapd.py index 6ca9fd5..8ddde24 100644 --- a/tests/_harness/leapd.py +++ b/tests/_harness/leapd.py @@ -112,6 +112,9 @@ def hermetic_env( # The mock host reports perception online; keep desktop tools out of # the prompt so cassette fingerprints stay stable. "LEAPFLOW_DESKTOP_TOOLS_ENABLED": "0", + # Copilot can schedule background LLM predictions from ambient desktop + # signals; journeys only cassette the foreground product contract. + "LEAPFLOW_COPILOT_ENABLED": "0", "LEAPFLOW_LLM_API_KEY": llm_api_key, "LEAPFLOW_LLM_BASE_URL": llm_base_url, "LEAPFLOW_LLM_MODEL": llm_model,