Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

fix(security): provider error taxonomy, tool leak hardening, hook gate, atomic cleanup

Geronimoa3c24818bb28
diff --git a/scripts/hooks/run-with-flags.js b/scripts/hooks/run-with-flags.js
index 9f6de3722..cd69ed6cc 100755
--- a/scripts/hooks/run-with-flags.js
+++ b/scripts/hooks/run-with-flags.js
@@ -207,7 +207,18 @@ async function main() {
// which would interfere with the parent process or cause double execution.
let hookModule;
const src = fs.readFileSync(scriptPath, 'utf8');
- const hasRunExport = /\bmodule\.exports\b/.test(src) && /\brun\b/.test(src);
+ // Gate require() on concrete export syntax, not a bare word match: the old
+ // /\bmodule\.exports\b/ && /\brun\b/ test fired on comments, strings, and
+ // unrelated properties, causing require() — and its module-scope side
+ // effects — to run for hooks that export no run(). Still lexical (no parser
+ // dependency), but requires an actual export assignment form.
+ const RUN_EXPORT_PATTERNS = [
+ /module\.exports\s*\.\s*run\s*=/,
+ /exports\s*\.\s*run\s*=/,
+ /module\.exports\s*=\s*\{[^}]*\brun\b/,
+ /module\.exports\s*=\s*(async\s+)?function\s+run\b/,
+ ];
+ const hasRunExport = RUN_EXPORT_PATTERNS.some(re => re.test(src));
if (hasRunExport) {
try {
diff --git a/scripts/lib/codex-legacy-sync.js b/scripts/lib/codex-legacy-sync.js
index 5eb92d180..12cdc392b 100644
--- a/scripts/lib/codex-legacy-sync.js
+++ b/scripts/lib/codex-legacy-sync.js
@@ -131,8 +131,15 @@ function removeOpenedRegularFile(filePath, opened) {
function atomicWriteJson(filePath, value) {
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
- fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
- fs.renameSync(tempPath, filePath);
+ try {
+ fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
+ fs.renameSync(tempPath, filePath);
+ } catch (error) {
+ // A failed write/rename must not leave a .tmp-<pid>-<timestamp> file
+ // beside the canonical state file; repeated failures would accumulate them.
+ fs.rmSync(tempPath, { force: true });
+ throw error;
+ }
}
function readState(statePath) {
diff --git a/src/llm/providers/ollama.py b/src/llm/providers/ollama.py
index 2f83338d0..793f0aa6b 100644
--- a/src/llm/providers/ollama.py
+++ b/src/llm/providers/ollama.py
@@ -8,6 +8,7 @@ from typing import Any
from llm.core.interface import (
AuthenticationError,
ContextLengthError,
+ LLMError,
LLMProvider,
RateLimitError,
)
@@ -100,13 +101,33 @@ class OllamaProvider(LLMProvider):
)
except Exception as e:
msg = str(e)
- if "401" in msg or "connection" in msg.lower():
- raise AuthenticationError(f"Ollama connection failed: {msg}", provider=ProviderType.OLLAMA) from e
- if "429" in msg or "rate_limit" in msg.lower():
+ lowered = msg.lower()
+ if "401" in msg or "unauthorized" in lowered or "forbidden" in lowered:
+ raise AuthenticationError(f"Ollama authentication failed: {msg}", provider=ProviderType.OLLAMA) from e
+ if "429" in msg or "rate_limit" in lowered:
raise RateLimitError(msg, provider=ProviderType.OLLAMA) from e
- if "context" in msg.lower() and "length" in msg.lower():
+ if "context" in lowered and "length" in lowered:
raise ContextLengthError(msg, provider=ProviderType.OLLAMA) from e
- raise
+ if (
+ "connection" in lowered
+ or "refused" in lowered
+ or "timed out" in lowered
+ or "timeout" in lowered
+ or "unreachable" in lowered
+ or "name resolution" in lowered
+ or "nodename nor servname" in lowered
+ or isinstance(e, (ConnectionError, TimeoutError))
+ ):
+ raise LLMError(
+ f"Ollama connection failed: {type(e).__name__}",
+ provider=ProviderType.OLLAMA,
+ code="connection_error",
+ ) from e
+ raise LLMError(
+ f"Ollama request failed: {type(e).__name__}",
+ provider=ProviderType.OLLAMA,
+ code="provider_error",
+ ) from e
def list_models(self) -> list[ModelInfo]:
return self._models.copy()
diff --git a/src/llm/tools/executor.py b/src/llm/tools/executor.py
index e4a859b34..e59311c1e 100644
--- a/src/llm/tools/executor.py
+++ b/src/llm/tools/executor.py
@@ -2,9 +2,12 @@
from __future__ import annotations
+import inspect
+import logging
from collections.abc import Callable
from typing import Any
+from llm.core.interface import LLMError
from llm.core.types import (
LLMInput,
LLMOutput,
@@ -15,6 +18,21 @@ from llm.core.types import (
ToolResult,
)
+logger = logging.getLogger(__name__)
+
+# Model-facing failure text. Raw exception details (credentials, local paths,
+# request data, upstream responses) must never reach the model; diagnostics go
+# to trusted logs only.
+GENERIC_TOOL_FAILURE = "Error executing {name}: tool failed"
+
+
+def _generic_failure(tool_call: ToolCall) -> ToolResult:
+ return ToolResult(
+ tool_call_id=tool_call.id,
+ content=GENERIC_TOOL_FAILURE.format(name=tool_call.name),
+ is_error=True,
+ )
+
ToolFunc = Callable[..., Any]
@@ -55,18 +73,50 @@ class ToolExecutor:
try:
result = func(**tool_call.arguments)
+ if inspect.isawaitable(result):
+ logger.warning(
+ "Async tool '%s' called via sync execute(); use execute_async()",
+ tool_call.name,
+ )
+ return ToolResult(
+ tool_call_id=tool_call.id,
+ content=GENERIC_TOOL_FAILURE.format(name=tool_call.name),
+ is_error=True,
+ )
content = result if isinstance(result, str) else str(result)
return ToolResult(tool_call_id=tool_call.id, content=content)
- except Exception as e:
+ except Exception:
+ logger.exception("Tool '%s' failed", tool_call.name)
+ return _generic_failure(tool_call)
+
+ async def execute_async(self, tool_call: ToolCall) -> ToolResult:
+ func = self.registry.get(tool_call.name)
+ if not func:
return ToolResult(
tool_call_id=tool_call.id,
- content=f"Error executing {tool_call.name}: {e}",
+ content=f"Error: Tool '{tool_call.name}' not found",
is_error=True,
)
+ try:
+ result = func(**tool_call.arguments)
+ if inspect.isawaitable(result):
+ result = await result
+ content = result if isinstance(result, str) else str(result)
+ return ToolResult(tool_call_id=tool_call.id, content=content)
+ except Exception:
+ logger.exception("Tool '%s' failed", tool_call.name)
+ return _generic_failure(tool_call)
+
def execute_all(self, tool_calls: list[ToolCall]) -> list[ToolResult]:
return [self.execute(tc) for tc in tool_calls]
+ async def execute_all_async(self, tool_calls: list[ToolCall]) -> list[ToolResult]:
+ results: list[ToolResult] = []
+ for tc in tool_calls:
+ results.append(await self.execute_async(tc))
+ return results
+
class ReActAgent:
def __init__(
@@ -92,7 +142,14 @@ class ReActAgent:
tools=tools,
)
- output: LLMOutput = self.provider.generate(input_copy)
+ try:
+ output: LLMOutput = self.provider.generate(input_copy)
+ except LLMError as e:
+ logger.warning("Provider failed during agent run: %s", e.code or type(e).__name__)
+ return LLMOutput(
+ content=f"Provider error: {e.code or type(e).__name__}",
+ stop_reason="provider_error",
+ )
if not output.has_tool_calls:
return output
@@ -105,7 +162,7 @@ class ReActAgent:
)
)
- results = self.executor.execute_all(output.tool_calls or [])
+ results = await self.executor.execute_all_async(output.tool_calls or [])
for result in results:
messages.append(
diff --git a/tests/test_executor.py b/tests/test_executor.py
index 749c4d1b4..75f522ff7 100644
--- a/tests/test_executor.py
+++ b/tests/test_executor.py
@@ -1,5 +1,5 @@
-from llm.core.types import ToolCall, ToolDefinition
-from llm.tools import ToolExecutor, ToolRegistry
+from llm.core.types import LLMInput, LLMOutput, Message, Role, ToolCall, ToolDefinition
+from llm.tools import ReActAgent, ToolExecutor, ToolRegistry
class TestToolRegistry:
@@ -83,3 +83,55 @@ class TestToolExecutor:
assert len(results) == 2
assert results[0].content == "result1"
assert results[1].content == "result2"
+
+
+class TestAsyncTools:
+ def test_execute_async_awaits_coroutine(self):
+ import asyncio
+
+ registry = ToolRegistry()
+
+ async def fetch(url: str = "") -> str:
+ return f"fetched:{url}"
+
+ registry.register(ToolDefinition(name="fetch", description="", parameters={}), fetch)
+
+ executor = ToolExecutor(registry)
+ result = asyncio.run(
+ executor.execute_async(ToolCall(id="1", name="fetch", arguments={"url": "x"}))
+ )
+
+ assert result.tool_call_id == "1"
+ assert result.content == "fetched:x"
+ assert result.is_error is False
+
+ def test_react_agent_runs_awaitable_tool(self):
+ import asyncio
+
+ async def lookup(key: str = "") -> str:
+ return f"value:{key}"
+
+ registry = ToolRegistry()
+ registry.register(ToolDefinition(name="lookup", description="", parameters={}), lookup)
+
+ seen = {}
+
+ class FakeProvider:
+ def generate(self, agent_input):
+ if "done" not in seen:
+ seen["done"] = True
+ return LLMOutput(
+ content="",
+ tool_calls=[ToolCall(id="1", name="lookup", arguments={"key": "k"})],
+ )
+ tool_messages = [m for m in agent_input.messages if m.role == Role.TOOL]
+ assert len(tool_messages) == 1
+ assert tool_messages[0].content == "value:k"
+ return LLMOutput(content="done")
+
+ agent = ReActAgent(provider=FakeProvider(), executor=ToolExecutor(registry))
+ output = asyncio.run(
+ agent.run(LLMInput(messages=[Message(role=Role.USER, content="hi")]))
+ )
+
+ assert output.content == "done"