Skip to content

The agent that grows with you

refactor(acp): share one OpenAI bridge between the ACP clients

Alexander Prendota083c5920e5a0
diff --git a/agent/acp_openai_bridge.py b/agent/acp_openai_bridge.py
new file mode 100644
index 00000000000..4b66350a28f
--- /dev/null
+++ b/agent/acp_openai_bridge.py
@@ -0,0 +1,287 @@
+"""OpenAI-shape bridge shared by Hermes' ACP clients.
+
+An ACP agent (``copilot --acp``, and the ACP CLIs that reach Hermes as
+providers) speaks the Agent Client Protocol, which has no OpenAI-style
+``tools``/``tool_calls`` channel: a prompt is text, and a response is text plus
+the agent's *own* tool notifications. Hermes' agentic surface — ``memory``,
+``todo``, ``skill_manage`` and friends — is dispatched from OpenAI-shaped
+``tool_calls``, so on an ACP provider it can only work if the schemas travel
+*into* the prompt as text and the calls are parsed back *out* of the response
+text.
+
+``agent/copilot_acp_client.py`` already carried a private copy of that bridge.
+This module is that code, lifted verbatim into one place so every ACP client
+shares it instead of re-deriving the wire contract:
+
+* :func:`render_tool_bridge_sections` — prompt sections describing the
+ forwarded tools and the ``<tool_call>{...}</tool_call>`` contract.
+* :func:`extract_tool_calls_from_text` — parse those blocks back into
+ ``ChatCompletionMessageToolCall`` objects and return the response text with
+ the blocks stripped.
+* :func:`completion_to_stream_chunks` — re-shape a one-shot ACP response as
+ OpenAI stream chunks for callers that asked for ``stream=True`` (an ACP turn
+ is inherently one-shot from Hermes' perspective).
+
+The one axis clients differ on is *which* tools they forward, so
+``render_tool_bridge_sections`` takes an optional allowlist. A CLI with no tools
+of its own (Copilot) forwards everything Hermes offers; a CLI that is an
+autonomous agent with its own read/edit/execute tools must forward only Hermes'
+agent-level tools, because re-offering the overlapping ones makes Hermes re-run
+work the agent already finished.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from types import SimpleNamespace
+from typing import Any, Iterable
+
+from openai.types.chat.chat_completion_message_tool_call import (
+ ChatCompletionMessageToolCall,
+ Function,
+)
+
+TOOL_CALL_BLOCK_RE = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.DOTALL)
+TOOL_CALL_JSON_RE = re.compile(
+ r"\{\s*\"id\"\s*:\s*\"[^\"]+\"\s*,\s*\"type\"\s*:\s*\"function\"\s*,\s*\"function\"\s*:\s*\{.*?\}\s*\}",
+ re.DOTALL,
+)
+
+# The contract sentence shared by every ACP client: how to emit a call.
+TOOL_CALL_CONTRACT = (
+ "Available tools (OpenAI function schema). "
+ "When using a tool, emit ONLY <tool_call>{...}</tool_call> with one JSON object "
+ "containing id/type/function{name,arguments}. arguments must be a JSON string."
+)
+
+__all__ = [
+ "TOOL_CALL_BLOCK_RE",
+ "TOOL_CALL_JSON_RE",
+ "TOOL_CALL_CONTRACT",
+ "StreamChunks",
+ "build_openai_tool_call",
+ "tool_specs_from_openai_tools",
+ "render_tool_bridge_sections",
+ "extract_tool_calls_from_text",
+ "completion_to_stream_chunks",
+]
+
+
+class StreamChunks(list):
+ """Stream chunks that can still carry response-level attributes.
+
+ Hermes reads provider-level extras off the object returned by
+ ``chat.completions.create`` (e.g. ``hermes_projected_messages``, consumed by
+ ``agent/provider_projection.py``). A plain list of chunks would silently drop
+ them on the ``stream=True`` path, so ACP clients return this instead and copy
+ the extras onto it.
+ """
+
+
+def completion_to_stream_chunks(completion: SimpleNamespace) -> StreamChunks:
+ """Convert a one-shot ACP response into OpenAI-style stream chunks.
+
+ Response-level attributes other than ``choices``/``usage``/``model`` are
+ copied onto the returned object so nothing a caller reads off the completion
+ is lost when it asked to stream.
+ """
+ choice = completion.choices[0]
+ message = choice.message
+ tool_call_deltas = None
+ if message.tool_calls:
+ tool_call_deltas = []
+ for index, tool_call in enumerate(message.tool_calls):
+ tool_call_deltas.append(
+ SimpleNamespace(
+ index=index,
+ id=getattr(tool_call, "id", None),
+ type=getattr(tool_call, "type", "function"),
+ function=SimpleNamespace(
+ name=getattr(tool_call.function, "name", None),
+ arguments=getattr(tool_call.function, "arguments", None),
+ ),
+ )
+ )
+
+ delta = SimpleNamespace(
+ role="assistant",
+ content=message.content or None,
+ tool_calls=tool_call_deltas,
+ reasoning_content=getattr(message, "reasoning_content", None),
+ reasoning=getattr(message, "reasoning", None),
+ )
+ data_chunk = SimpleNamespace(
+ choices=[
+ SimpleNamespace(
+ index=0,
+ delta=delta,
+ finish_reason=choice.finish_reason,
+ )
+ ],
+ model=completion.model,
+ usage=None,
+ )
+ usage_chunk = SimpleNamespace(
+ choices=[],
+ model=completion.model,
+ usage=completion.usage,
+ )
+ chunks = StreamChunks([data_chunk, usage_chunk])
+ for key, value in vars(completion).items():
+ if key not in ("choices", "usage", "model"):
+ setattr(chunks, key, value)
+ return chunks
+
+
+def build_openai_tool_call(
+ *,
+ call_id: str,
+ name: str,
+ arguments: str,
+) -> ChatCompletionMessageToolCall:
+ """Build an OpenAI-compatible tool-call object for downstream handling."""
+ return ChatCompletionMessageToolCall(
+ id=call_id,
+ call_id=call_id,
+ response_item_id=None,
+ type="function",
+ function=Function(name=name, arguments=arguments),
+ )
+
+
+def tool_specs_from_openai_tools(
+ tools: list[dict[str, Any]] | None,
+ *,
+ allowlist: Iterable[str] | None = None,
+) -> list[dict[str, Any]]:
+ """Flatten OpenAI ``tools`` into ``{name, description, parameters}`` specs.
+
+ Malformed entries are skipped. When ``allowlist`` is given, only tools whose
+ name is in it survive — that is how a client forwards just Hermes'
+ agent-level tools instead of the whole toolset.
+ """
+ allowed = {str(n).strip() for n in allowlist} if allowlist is not None else None
+ specs: list[dict[str, Any]] = []
+ for t in tools or []:
+ if not isinstance(t, dict):
+ continue
+ fn = t.get("function") or {}
+ if not isinstance(fn, dict):
+ continue
+ name = fn.get("name")
+ if not isinstance(name, str) or not name.strip():
+ continue
+ name = name.strip()
+ if allowed is not None and name not in allowed:
+ continue
+ specs.append(
+ {
+ "name": name,
+ "description": fn.get("description", ""),
+ "parameters": fn.get("parameters", {}),
+ }
+ )
+ return specs
+
+
+def render_tool_bridge_sections(
+ tools: list[dict[str, Any]] | None,
+ tool_choice: Any = None,
+ *,
+ allowlist: Iterable[str] | None = None,
+) -> list[str]:
+ """Prompt sections that carry the forwarded tool schemas + choice hint.
+
+ Returns an empty list when no tool survives filtering and no choice hint was
+ requested, so callers can splice the result into their section list
+ unconditionally.
+ """
+ specs = tool_specs_from_openai_tools(tools, allowlist=allowlist)
+ sections: list[str] = []
+ if specs:
+ sections.append(
+ TOOL_CALL_CONTRACT + "\n" + json.dumps(specs, ensure_ascii=False)
+ )
+ if tool_choice is not None:
+ sections.append(f"Tool choice hint: {json.dumps(tool_choice, ensure_ascii=False)}")
+ return sections
+
+
+def extract_tool_calls_from_text(
+ text: str,
+) -> tuple[list[ChatCompletionMessageToolCall], str]:
+ """Pull ``<tool_call>`` blocks out of an ACP response.
+
+ Returns ``(tool_calls, cleaned_text)`` where ``cleaned_text`` is the
+ response with the consumed blocks removed, so the assistant message doesn't
+ show raw JSON to the user.
+ """
+ if not isinstance(text, str) or not text.strip():
+ return [], ""
+
+ extracted: list[ChatCompletionMessageToolCall] = []
+ consumed_spans: list[tuple[int, int]] = []
+
+ def _try_add_tool_call(raw_json: str) -> None:
+ try:
+ obj = json.loads(raw_json)
+ except Exception:
+ return
+ if not isinstance(obj, dict):
+ return
+ fn = obj.get("function")
+ if not isinstance(fn, dict):
+ return
+ fn_name = fn.get("name")
+ if not isinstance(fn_name, str) or not fn_name.strip():
+ return
+ fn_args = fn.get("arguments", "{}")
+ if not isinstance(fn_args, str):
+ fn_args = json.dumps(fn_args, ensure_ascii=False)
+ call_id = obj.get("id")
+ if not isinstance(call_id, str) or not call_id.strip():
+ call_id = f"acp_call_{len(extracted)+1}"
+
+ extracted.append(
+ build_openai_tool_call(
+ call_id=call_id,
+ name=fn_name.strip(),
+ arguments=fn_args,
+ )
+ )
+
+ for m in TOOL_CALL_BLOCK_RE.finditer(text):
+ raw = m.group(1)
+ _try_add_tool_call(raw)
+ consumed_spans.append((m.start(), m.end()))
+
+ # Only try bare-JSON fallback when no XML blocks were found.
+ if not extracted:
+ for m in TOOL_CALL_JSON_RE.finditer(text):
+ raw = m.group(0)
+ _try_add_tool_call(raw)
+ consumed_spans.append((m.start(), m.end()))
+
+ if not consumed_spans:
+ return extracted, text.strip()
+
+ consumed_spans.sort()
+ merged: list[tuple[int, int]] = []
+ for start, end in consumed_spans:
+ if not merged or start > merged[-1][1]:
+ merged.append((start, end))
+ else:
+ merged[-1] = (merged[-1][0], max(merged[-1][1], end))
+
+ parts: list[str] = []
+ cursor = 0
+ for start, end in merged:
+ if cursor < start:
+ parts.append(text[cursor:start])
+ cursor = max(cursor, end)
+ if cursor < len(text):
+ parts.append(text[cursor:])
+
+ cleaned = "\n".join(p.strip() for p in parts if p and p.strip()).strip()
+ return extracted, cleaned
diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.py
index 42be04395d7..a547895b261 100644
--- a/agent/copilot_acp_client.py
+++ b/agent/copilot_acp_client.py
@@ -21,11 +21,11 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Any
-from openai.types.chat.chat_completion_message_tool_call import (
- ChatCompletionMessageToolCall,
- Function,
+from agent.acp_openai_bridge import (
+ completion_to_stream_chunks as _completion_to_stream_chunks,
+ extract_tool_calls_from_text as _extract_tool_calls_from_text,
+ render_tool_bridge_sections as _render_tool_bridge_sections,
)
-
from agent.file_safety import get_read_block_error, get_write_denied_error, is_write_approval_required
from agent.redact import redact_sensitive_text
from tools.environments.local import hermes_subprocess_env
@@ -33,9 +33,6 @@ from tools.environments.local import hermes_subprocess_env
ACP_MARKER_BASE_URL = "acp://copilot"
_DEFAULT_TIMEOUT_SECONDS = 900.0
-_TOOL_CALL_BLOCK_RE = re.compile(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", re.DOTALL)
-_TOOL_CALL_JSON_RE = re.compile(r"\{\s*\"id\"\s*:\s*\"[^\"]+\"\s*,\s*\"type\"\s*:\s*\"function\"\s*,\s*\"function\"\s*:\s*\{.*?\}\s*\}", re.DOTALL)
-
# Stderr fingerprint of the deprecated `gh copilot` CLI extension
# (https://github.blog/changelog/2025-09-25-upcoming-deprecation-of-gh-copilot-cli-extension).
# We require BOTH the literal product name ("gh-copilot") AND a deprecation
@@ -203,34 +200,9 @@ def _format_messages_as_prompt(
if model:
sections.append(f"Hermes requested model hint: {model}")
- if isinstance(tools, list) and tools:
- tool_specs: list[dict[str, Any]] = []
- for t in tools:
- if not isinstance(t, dict):
- continue
- fn = t.get("function") or {}
- if not isinstance(fn, dict):
- continue
- name = fn.get("name")
- if not isinstance(name, str) or not name.strip():
- continue
- tool_specs.append(
- {
- "name": name.strip(),
- "description": fn.get("description", ""),
- "parameters": fn.get("parameters", {}),
- }
- )
- if tool_specs:
- sections.append(
- "Available tools (OpenAI function schema). "
- "When using a tool, emit ONLY <tool_call>{...}</tool_call> with one JSON object "
- "containing id/type/function{name,arguments}. arguments must be a JSON string.\n"
- + json.dumps(tool_specs, ensure_ascii=False)
- )
-
- if tool_choice is not None:
- sections.append(f"Tool choice hint: {json.dumps(tool_choice, ensure_ascii=False)}")
+ # Copilot has no tools of its own that would collide with Hermes', so it
+ # forwards the whole toolset (no allowlist).
+ sections.extend(_render_tool_bridge_sections(tools, tool_choice))
transcript: list[str] = []
for message in messages:
@@ -287,140 +259,6 @@ def _render_message_content(content: Any) -> str:
return str(content).strip()
-def _build_openai_tool_call(
- *,
- call_id: str,
- name: str,
- arguments: str,
-) -> ChatCompletionMessageToolCall:
- """Build an OpenAI-compatible tool-call object for downstream handling."""
- return ChatCompletionMessageToolCall(
- id=call_id,
- call_id=call_id,
- response_item_id=None,
- type="function",
- function=Function(name=name, arguments=arguments),
- )
-
-
-def _completion_to_stream_chunks(completion: SimpleNamespace) -> list[SimpleNamespace]:
- """Convert a one-shot ACP response into OpenAI-style stream chunks."""
- choice = completion.choices[0]
- message = choice.message
- tool_call_deltas = None
- if message.tool_calls:
- tool_call_deltas = []
- for index, tool_call in enumerate(message.tool_calls):
- tool_call_deltas.append(
- SimpleNamespace(
- index=index,
- id=getattr(tool_call, "id", None),
- type=getattr(tool_call, "type", "function"),
- function=SimpleNamespace(
- name=getattr(tool_call.function, "name", None),
- arguments=getattr(tool_call.function, "arguments", None),
- ),
- )
- )
-
- delta = SimpleNamespace(
- role="assistant",
- content=message.content or None,
- tool_calls=tool_call_deltas,
- reasoning_content=message.reasoning_content,
- reasoning=message.reasoning,
- )
- data_chunk = SimpleNamespace(
- choices=[
- SimpleNamespace(
- index=0,
- delta=delta,
- finish_reason=choice.finish_reason,
- )
- ],
- model=completion.model,
- usage=None,
- )
- usage_chunk = SimpleNamespace(
- choices=[],
- model=completion.model,
- usage=completion.usage,
- )
- return [data_chunk, usage_chunk]
-
-
-def _extract_tool_calls_from_text(text: str) -> tuple[list[ChatCompletionMessageToolCall], str]:
- if not isinstance(text, str) or not text.strip():
- return [], ""
-
- extracted: list[ChatCompletionMessageToolCall] = []
- consumed_spans: list[tuple[int, int]] = []
-
- def _try_add_tool_call(raw_json: str) -> None:
- try:
- obj = json.loads(raw_json)
- except Exception:
- return
- if not isinstance(obj, dict):
- return
- fn = obj.get("function")
- if not isinstance(fn, dict):
- return
- fn_name = fn.get("name")
- if not isinstance(fn_name, str) or not fn_name.strip():
- return
- fn_args = fn.get("arguments", "{}")
- if not isinstance(fn_args, str):
- fn_args = json.dumps(fn_args, ensure_ascii=False)
- call_id = obj.get("id")
- if not isinstance(call_id, str) or not call_id.strip():
- call_id = f"acp_call_{len(extracted)+1}"
-
- extracted.append(
- _build_openai_tool_call(
- call_id=call_id,
- name=fn_name.strip(),
- arguments=fn_args,
- )
- )
-
- for m in _TOOL_CALL_BLOCK_RE.finditer(text):
- raw = m.group(1)
- _try_add_tool_call(raw)
- consumed_spans.append((m.start(), m.end()))
-
- # Only try bare-JSON fallback when no XML blocks were found.
- if not extracted:
- for m in _TOOL_CALL_JSON_RE.finditer(text):
- raw = m.group(0)
- _try_add_tool_call(raw)
- consumed_spans.append((m.start(), m.end()))
-
- if not consumed_spans:
- return extracted, text.strip()
-
- consumed_spans.sort()
- merged: list[tuple[int, int]] = []
- for start, end in consumed_spans:
- if not merged or start > merged[-1][1]:
- merged.append((start, end))
- else:
- merged[-1] = (merged[-1][0], max(merged[-1][1], end))
-
- parts: list[str] = []
- cursor = 0
- for start, end in merged:
- if cursor < start:
- parts.append(text[cursor:start])
- cursor = max(cursor, end)
- if cursor < len(text):
- parts.append(text[cursor:])
-
- cleaned = "\n".join(p.strip() for p in parts if p and p.strip()).strip()
- return extracted, cleaned
-
-
-
def _ensure_path_within_cwd(path_text: str, cwd: str) -> Path:
candidate = Path(path_text)
if not candidate.is_absolute():
diff --git a/tests/agent/test_acp_openai_bridge.py b/tests/agent/test_acp_openai_bridge.py
new file mode 100644
index 00000000000..d1c04026045
--- /dev/null
+++ b/tests/agent/test_acp_openai_bridge.py
@@ -0,0 +1,212 @@
+"""The ACP text bridge is what makes Hermes' own tools reachable on an ACP provider.
+
+ACP has no OpenAI ``tools``/``tool_calls`` channel, so ``memory``,
+``skill_manage``, ``todo`` and friends only work if the schemas travel into the
+prompt as text and the calls are parsed back out of the response text. These
+tests pin both halves plus the streaming shape, and check that the in-tree
+consumer (``agent/copilot_acp_client.py``) still produces the same prompt it did
+when it owned a private copy of this code.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from types import SimpleNamespace
+
+_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+if _REPO_ROOT not in sys.path:
+ sys.path.insert(0, _REPO_ROOT)
+
+from agent.acp_openai_bridge import ( # noqa: E402
+ StreamChunks,
+ completion_to_stream_chunks,
+ extract_tool_calls_from_text,
+ render_tool_bridge_sections,
+ tool_specs_from_openai_tools,
+)
+
+_TOOLS = [
+ {"type": "function", "function": {"name": "memory", "description": "d1", "parameters": {"a": 1}}},
+ {"type": "function", "function": {"name": "read_file", "description": "d2", "parameters": {}}},
+]
+
+
+# ── prompt side ──────────────────────────────────────────────────────────────
+
+
+def test_specs_are_flattened_and_malformed_entries_skipped():
+ specs = tool_specs_from_openai_tools(
+ [*_TOOLS, "junk", None, {"function": None}, {"function": {"name": " "}}]
+ )
+ assert [s["name"] for s in specs] == ["memory", "read_file"]
+ assert specs[0] == {"name": "memory", "description": "d1", "parameters": {"a": 1}}
+
+
+def test_allowlist_forwards_only_the_named_tools():
+ """An agent-as-provider runs its own read/edit tools; re-offering them would
+ make Hermes re-run finished work, so those clients forward an allowlist."""
+ specs = tool_specs_from_openai_tools(_TOOLS, allowlist=["memory"])
+ assert [s["name"] for s in specs] == ["memory"]
+ # No allowlist at all means "forward everything" — not "forward nothing".
+ assert len(tool_specs_from_openai_tools(_TOOLS)) == 2
+ assert tool_specs_from_openai_tools(_TOOLS, allowlist=[]) == []
+
+
+def test_rendered_sections_carry_the_contract_and_the_schemas():
+ sections = render_tool_bridge_sections(_TOOLS, {"type": "function"})
+ assert len(sections) == 2
+ assert "<tool_call>" in sections[0]
+ payload = json.loads(sections[0].split("\n", 1)[1])
+ assert [s["name"] for s in payload] == ["memory", "read_file"]
+ assert sections[1].startswith("Tool choice hint:")
+
+
+def test_no_tools_and_no_choice_render_nothing():
+ """Callers splice the result unconditionally, so it must be safe to be empty."""
+ assert render_tool_bridge_sections(None) == []
+ assert render_tool_bridge_sections([]) == []
+ assert render_tool_bridge_sections([{"function": {}}]) == []
+
+
+# ── response side ────────────────────────────────────────────────────────────
+
+
+def test_tool_call_block_is_parsed_and_stripped_from_the_text():
+ calls, cleaned = extract_tool_calls_from_text(
+ 'Sure.\n<tool_call>{"id": "c1", "type": "function", "function": '
+ '{"name": "memory", "arguments": "{\\"action\\": \\"add\\"}"}}</tool_call>\nDone.'
+ )
+ assert [c.function.name for c in calls] == ["memory"]
+ assert calls[0].id == "c1"
+ assert json.loads(calls[0].function.arguments) == {"action": "add"}
+ # The user must not see the raw JSON.
+ assert "<tool_call>" not in cleaned
+ assert cleaned == "Sure.\nDone."
+
+
+def test_multiple_blocks_are_all_parsed():
+ text = "".join(
+ f'<tool_call>{{"id": "c{i}", "type": "function", '
+ f'"function": {{"name": "todo", "arguments": "{{}}"}}}}</tool_call>'
+ for i in range(3)
+ )
+ calls, cleaned = extract_tool_calls_from_text(text)
+ assert [c.id for c in calls] == ["c0", "c1", "c2"]
+ assert cleaned == ""
+
+
+def test_non_string_arguments_are_json_encoded_and_missing_ids_synthesised():
+ calls, _ = extract_tool_calls_from_text(
+ '<tool_call>{"type": "function", "function": '
+ '{"name": "todo", "arguments": {"op": "list"}}}</tool_call>'
+ )
+ assert calls[0].function.arguments == '{"op": "list"}'
+ assert calls[0].id == "acp_call_1"
+
+
+def test_bare_json_is_a_fallback_only_when_no_block_matched():
+ bare = '{"id": "c9", "type": "function", "function": {"name": "memory", "arguments": "{}"}}'
+ calls, cleaned = extract_tool_calls_from_text(f"before {bare} after")
+ assert [c.id for c in calls] == ["c9"]
+ assert cleaned == "before\nafter"
+
+ # With a real block present the bare-JSON scan must not double-count.
+ both = f'<tool_call>{bare}</tool_call> and {bare}'
+ calls, _ = extract_tool_calls_from_text(both)
+ assert len(calls) == 1
+
+
+def test_malformed_and_empty_input_never_raises():
+ assert extract_tool_calls_from_text("") == ([], "")
+ assert extract_tool_calls_from_text(None) == ([], "")
+ calls, cleaned = extract_tool_calls_from_text("<tool_call>{not json}</tool_call>plain")
+ assert calls == []
+ assert cleaned == "plain"
+ # Well-formed JSON that isn't a tool call is ignored, text preserved.
+ calls, cleaned = extract_tool_calls_from_text('<tool_call>{"function": 5}</tool_call>hi')
+ assert calls == []
+ assert cleaned == "hi"
+
+
+# ── streaming shape ──────────────────────────────────────────────────────────
+
+
+def _completion(**extras):
+ message = SimpleNamespace(
+ content="hello",
+ tool_calls=[
+ SimpleNamespace(
+ id="c1", type="function",
+ function=SimpleNamespace(name="memory", arguments="{}"),
+ )
+ ],
+ reasoning=None,
+ reasoning_content=None,
+ )
+ return SimpleNamespace(
+ choices=[SimpleNamespace(message=message, finish_reason="tool_calls")],
+ usage=SimpleNamespace(total_tokens=3),
+ model="acp",
+ **extras,
+ )
+
+
+def test_stream_chunks_carry_the_delta_then_the_usage():
+ chunks = completion_to_stream_chunks(_completion())
+ assert len(chunks) == 2
+ delta = chunks[0].choices[0].delta
+ assert delta.content == "hello"
+ assert delta.tool_calls[0].function.name == "memory"
+ assert delta.tool_calls[0].index == 0
+ assert chunks[0].choices[0].finish_reason == "tool_calls"
+ # Usage arrives on its own trailing chunk, as OpenAI does it.
+ assert chunks[0].usage is None
+ assert chunks[1].usage.total_tokens == 3
+ assert chunks[1].choices == []
+
+
+def test_response_level_extras_survive_the_stream_conversion():
+ """Hermes reads provider extras off the returned object; a plain list would
+ drop them and silently disable the projection on stream=True."""
+ chunks = completion_to_stream_chunks(
+ _completion(hermes_projected_messages=[{"role": "tool", "content": "x"}])
+ )
+ assert isinstance(chunks, StreamChunks)
+ assert isinstance(chunks, list)
+ assert chunks.hermes_projected_messages == [{"role": "tool", "content": "x"}]
+
+
+def test_a_text_only_completion_streams_without_tool_call_deltas():
+ completion = _completion()
+ completion.choices[0].message.tool_calls = []
+ completion.choices[0].finish_reason = "stop"
+ chunks = completion_to_stream_chunks(completion)
+ assert chunks[0].choices[0].delta.tool_calls is None
+
+
+# ── the in-tree consumer still speaks the same wire ──────────────────────────
+
+
+def test_copilot_prompt_still_carries_the_contract_and_the_tools():
+ """copilot-acp lost its private copy of the bridge; its prompt must not
+ change shape."""
+ from agent.copilot_acp_client import _format_messages_as_prompt
+
+ prompt = _format_messages_as_prompt(
+ [{"role": "user", "content": "hi"}], model="gpt-5", tools=_TOOLS,
+ )
+ assert "<tool_call>{...}</tool_call>" in prompt
+ assert '"name": "memory"' in prompt
+ assert '"name": "read_file"' in prompt # copilot forwards everything
+ assert "Hermes requested model hint: gpt-5" in prompt
+ assert "hi" in prompt
+
+
+def test_copilot_prompt_omits_the_tool_section_when_there_are_no_tools():
+ from agent.copilot_acp_client import _format_messages_as_prompt
+
+ prompt = _format_messages_as_prompt([{"role": "user", "content": "hi"}])
+ assert "Available tools" not in prompt
+ assert "Tool choice hint" not in prompt