Skip to content

Commit 7a6fb1d

Browse files
authored
feat: add OpenCode agent profile (#124)
Add support for OpenCode (anomalyco/opencode) as a dashboard agent. OpenCode is an open-source AI coding agent with multi-provider support (Anthropic, OpenAI, Gemini, Copilot, Bedrock, etc.). Profile configuration: - Install via npm (opencode-ai package) - Session resume via --continue flag - OTLP traces and logs enabled via OTEL_EXPORTER_OTLP_ENDPOINT - MCP server detection from ~/.opencode/config.json - Permission prompt detection for tool approval dialogs - spawn_settings patches experimental.openTelemetry into config Known limitations: - OTEL_SERVICE_NAME is hardcoded to 'opencode' in the CLI (anomalyco/opencode#25839). Agent ID resolution falls back to tool-type matching in _resolve_agent_id(). - No OTLP metrics export — token usage, cost, and activity counters are not available. Dashboard cards show model and activity from span attributes but no token/cost data. Also includes: - _merge_missing_keys(): Deep-merge for spawn_settings to support nested JSON config (e.g. experimental.openTelemetry). Replaces the flat key-only check that couldn't handle nested dicts. Backward compatible — flat keys work as before. - OpenCode fallback in _resolve_agent_id() for the hardcoded 'opencode' service.name. - 5 new unit tests (agent ID resolution + deep merge). Co-authored-by: Claude [email protected]
1 parent 5964f40 commit 7a6fb1d

3 files changed

Lines changed: 174 additions & 5 deletions

File tree

‎agent/host_daemon.py‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,31 @@ def get_git_info(self, path: str):
637637

638638
return branch, project, remote_url
639639

640+
@staticmethod
641+
def _merge_missing_keys(target, defaults):
642+
"""Deep-merge default keys into target dict.
643+
644+
Only adds keys that are missing in the target.
645+
For nested dicts, recurses so that sub-keys can
646+
be added without overwriting sibling keys.
647+
648+
Args:
649+
target: Dict to update in place.
650+
defaults: Dict of keys/values to add if missing.
651+
652+
Returns:
653+
True if any key was added, False otherwise.
654+
"""
655+
changed = False
656+
for key, value in defaults.items():
657+
if key not in target:
658+
target[key] = value
659+
changed = True
660+
elif isinstance(value, dict) and isinstance(target[key], dict):
661+
if HostDaemon._merge_missing_keys(target[key], value):
662+
changed = True
663+
return changed
664+
640665
def _detect_mcp_servers(self, project_dir, tool):
641666
"""Detects MCP servers configured for the given tool.
642667
@@ -883,11 +908,7 @@ async def spawn_agent(
883908
if os.path.exists(filepath):
884909
with open(filepath, "r", encoding="utf-8") as f:
885910
existing = json.load(f)
886-
changed = False
887-
for key, value in required_keys.items():
888-
if key not in existing:
889-
existing[key] = value
890-
changed = True
911+
changed = self._merge_missing_keys(existing, required_keys)
891912
if changed:
892913
os.makedirs(
893914
os.path.dirname(filepath),
@@ -1492,6 +1513,8 @@ def _resolve_agent_id(self, res_attrs):
14921513
tool_hint = "claude"
14931514
elif "pi" == svc.lower() or "pi-otel" in all_vals:
14941515
tool_hint = "pi"
1516+
elif "opencode" in svc.lower() or "opencode" in all_vals:
1517+
tool_hint = "opencode"
14951518

14961519
if tool_hint:
14971520
# Build candidate list. When the hint is

‎agent/profiles/opencode.yaml‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# OpenCode agent profile (anomalyco/opencode)
2+
# Open-source AI coding agent with multi-provider
3+
# support. TypeScript/Node.js, distributed as the
4+
# opencode-ai npm package.
5+
#
6+
# OTLP telemetry: Partial. Traces and logs are
7+
# exported when OTEL_EXPORTER_OTLP_ENDPOINT is set.
8+
# Metrics (token usage, cost) are NOT exported.
9+
# OTEL_SERVICE_NAME is currently ignored (hardcoded
10+
# to "opencode") — multi-instance tracking relies
11+
# on the daemon's fallback agent ID resolution.
12+
# Tracked upstream:
13+
# - Service name: anomalyco/opencode#25839
14+
name: opencode
15+
display_name: OpenCode
16+
color: amber
17+
binary: opencode
18+
19+
commands:
20+
new: ["opencode"]
21+
resume: ["bash", "-c", "opencode --continue || opencode"]
22+
23+
# OTEL_EXPORTER_OTLP_ENDPOINT is the master switch
24+
# for OpenCode's OTLP export. Setting it enables
25+
# trace and log export to the daemon's receiver.
26+
# OTEL_EXPORTER_OTLP_PROTOCOL is not needed —
27+
# OpenCode uses http/json by default.
28+
env:
29+
OTEL_EXPORTER_OTLP_PROTOCOL: "http/json"
30+
31+
# No auth gate — OpenCode supports many providers
32+
# (Anthropic, OpenAI, Gemini, Copilot, Bedrock,
33+
# etc.) with their own API key env vars. Binary
34+
# presence is sufficient. If no provider is
35+
# configured, OpenCode prompts at startup.
36+
37+
# Spawn-time settings — ensure experimental OTLP
38+
# span generation is enabled for richer traces.
39+
spawn_settings:
40+
~/.opencode/config.json:
41+
experimental:
42+
openTelemetry: true
43+
44+
mcp:
45+
user_files:
46+
- ~/.opencode/config.json
47+
48+
# No telemetry metrics section — OpenCode does not
49+
# export OTLP metrics (token usage, cost, activity).
50+
# Traces provide model name and current activity
51+
# via span attributes, which the daemon extracts
52+
# in _update_telemetry_from_attrs().
53+
54+
permission_patterns:
55+
- "Allow"
56+
- "Grant"
57+
- "approve"
58+
59+
# Build-time provisioning metadata
60+
provisioning:
61+
install:
62+
npm:
63+
- "opencode-ai"
64+
config_files:
65+
- path: "/root/.opencode"
66+
mkdir: true
67+
- path: "/root/.opencode/config.json"
68+
content: '{"experimental": {"openTelemetry": true}}'
69+
verify: "opencode --version"
70+
mounts:
71+
- host: "~/.opencode"
72+
container: "/root/.opencode"
73+
mode: rw
74+
passthrough_env:
75+
- ANTHROPIC_API_KEY
76+
- OPENAI_API_KEY
77+
- GEMINI_API_KEY
78+
- GITHUB_TOKEN
79+
- AWS_ACCESS_KEY_ID
80+
- AWS_SECRET_ACCESS_KEY
81+
- AWS_REGION
82+
- AZURE_OPENAI_API_KEY
83+
- AZURE_OPENAI_BASE_URL
84+
- XAI_API_KEY
85+
- OPENROUTER_API_KEY

‎agent/tests/test_host_daemon.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,16 @@ def test_agy_hint_does_not_match_gemini(self, daemon):
456456
# Falls back to single-agent last resort
457457
assert result == "g-1"
458458

459+
def test_opencode_fallback_service_name(self, daemon):
460+
"""OpenCode hardcodes service.name to 'opencode'.
461+
The fallback matches it to opencode agents."""
462+
daemon.agents["oc-1"] = {
463+
"tool": "opencode",
464+
"last_output_time": 1.0,
465+
}
466+
result = daemon._resolve_agent_id({"service.name": "opencode"})
467+
assert result == "oc-1"
468+
459469

460470
# ── E. get_git_info ──────────────────────────────────────────
461471

@@ -1077,6 +1087,57 @@ def test_base_not_modified(self):
10771087
# ── I. Multi-Root Projects ─────────────────────────────
10781088

10791089

1090+
# ── J. _merge_missing_keys ─────────────────────────────
1091+
1092+
1093+
class TestMergeMissingKeys:
1094+
"""Tests for _merge_missing_keys deep merge."""
1095+
1096+
def test_flat_keys_added(self, daemon):
1097+
"""Missing flat keys are added."""
1098+
target = {"a": 1}
1099+
changed = daemon._merge_missing_keys(target, {"b": 2})
1100+
assert changed is True
1101+
assert target == {"a": 1, "b": 2}
1102+
1103+
def test_existing_keys_preserved(self, daemon):
1104+
"""Existing keys are not overwritten."""
1105+
target = {"a": 1}
1106+
changed = daemon._merge_missing_keys(target, {"a": 99})
1107+
assert changed is False
1108+
assert target == {"a": 1}
1109+
1110+
def test_nested_keys_added(self, daemon):
1111+
"""Missing nested keys are added without
1112+
overwriting sibling keys."""
1113+
target = {"experimental": {"existingKey": True}}
1114+
defaults = {"experimental": {"openTelemetry": True}}
1115+
changed = daemon._merge_missing_keys(target, defaults)
1116+
assert changed is True
1117+
assert target == {
1118+
"experimental": {
1119+
"existingKey": True,
1120+
"openTelemetry": True,
1121+
}
1122+
}
1123+
1124+
def test_nested_existing_preserved(self, daemon):
1125+
"""Existing nested keys are not overwritten."""
1126+
target = {"experimental": {"openTelemetry": False}}
1127+
defaults = {"experimental": {"openTelemetry": True}}
1128+
changed = daemon._merge_missing_keys(target, defaults)
1129+
assert changed is False
1130+
assert target["experimental"]["openTelemetry"] is False
1131+
1132+
def test_new_nested_dict_added(self, daemon):
1133+
"""Entirely missing nested dict is added."""
1134+
target = {}
1135+
defaults = {"experimental": {"openTelemetry": True}}
1136+
changed = daemon._merge_missing_keys(target, defaults)
1137+
assert changed is True
1138+
assert target == {"experimental": {"openTelemetry": True}}
1139+
1140+
10801141
class TestMultiRoot:
10811142
"""Tests for multi-root PROJECTS_ROOT support."""
10821143

0 commit comments

Comments
 (0)