fix(openclaw): return structured retrieval tool results (#4707)

## Description

The registered `headroom_retrieve` tool returns a string today. OpenClaw
Code Mode expects an `AgentToolResult` and rejects the string during
transcript capture. Return a text block and structured details for
success, validation errors, HTTP errors, and network failures. Both
invocation signatures now use this result shape. Consumers of the
exported factory can read the text from `content[0].text`.

<!-- Briefly explain the change and why it is needed. -->

Closes #4700.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- Preserve the original successful response text and expose the parsed
response as `details`.
- Use OpenClaw’s `details.status: "error"` convention and preserve the
error message, response detail, or expiry hint.

## Testing

<!-- Check what you actually ran, then paste the real command output
below. -->

- [ ] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [ ] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
cd plugins/openclaw
npm test         # 11 files, 158 tests passed on Node 22.22.2
npm run typecheck
npm run build
git diff --check
```

## Real Behavior Proof

- Environment: macOS arm64, Node 26.12.1, built plugin, loopback HTTP
fixture with synthetic stored content.
- Exact command / steps: run `npm run build` in `plugins/openclaw`.
Import `registerHeadroomPlugin` from `dist/index.js`, configure the
loopback `proxyUrl` with `autoStart: false` and `routeCodexViaProxy:
false`, and capture the factory passed to `registerTool`. Call
`execute(callId, { hash })` with an uppercase 12-hex hash and a 24-hex
hash against successful JSON object and string responses. Then call it
with an invalid hash, a missing key returning HTTP 404, and a valid hash
after stopping the server.
- Observed result: all five paths returned strings on `main` and result
objects after the patch. Request counts were `1, 1, 0, 1, 0` in both
runs. The fix preserved success text and exposed the three failures as
`details.status: "error"`. Seven expectations in the focused regression
file failed on `main`.
- Not tested: full OpenClaw host dispatch or a remote Headroom proxy.
The smoke test used actual plugin registration and HTTP with a small
host API shim.

## Runtime Rollout Safety

- Rollout-managed feature(s): retrieval tool in the OpenClaw plugin.
- Minimum rollout channel: existing plugin channel.
- Stable/default behavior changed: the registered tool returns a
structured result.
- Kill switch / disable path: existing OpenClaw plugin enablement.
- Unsafe override required: none.
- Qualification impact: plugin test suite and loopback verification
above.
- Rollback path: revert the commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

Add screenshots to help explain your changes.

## Additional Notes

AI assistance was used for investigation, implementation, and tests.

<!-- Mention any N/A checklist items, tradeoffs, follow-ups, or
maintainer context. -->

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4707"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->
This commit is contained in:
123XieC
2026-11-09 21:27:43 -06:00
committed by GitHub
parent b21479e0fa
commit e6b5777806
3 changed files with 67 additions and 12 deletions
@@ -12,6 +12,11 @@ export interface RetrieveToolConfig {
proxyUrl: string;
}
function retrievalResult(details: unknown) {
const text = typeof details === "string" ? details : JSON.stringify(details);
return { content: [{ type: "text" as const, text }], details };
}
export function createHeadroomRetrieveTool(config: RetrieveToolConfig) {
const proxyOrigin = normalizeAndValidateProxyUrl(config.proxyUrl);
@@ -39,13 +44,14 @@ export function createHeadroomRetrieveTool(config: RetrieveToolConfig) {
execute: async (
toolCallIdOrArgs: string | { hash: string },
params?: { hash: string },
): Promise<string> => {
) => {
const args = typeof toolCallIdOrArgs === "string" ? params : toolCallIdOrArgs;
const hash = typeof args?.hash === "string" ? args.hash : "";
// Validate hash format
if (!/^(?:[a-f0-9]{12}|[a-f0-9]{24})$/i.test(hash)) {
return JSON.stringify({
return retrievalResult({
status: "error",
error: "Invalid hash format. Expected 12 or 24 hex characters.",
});
}
@@ -62,16 +68,17 @@ export function createHeadroomRetrieveTool(config: RetrieveToolConfig) {
if (!resp.ok) {
const body = await resp.text().catch(() => "");
return JSON.stringify({
return retrievalResult({
status: "error",
error: `Retrieval failed: HTTP ${resp.status}`,
details: body,
});
}
const data = await resp.json();
return typeof data === "string" ? data : JSON.stringify(data);
return retrievalResult(await resp.json());
} catch (error) {
return JSON.stringify({
return retrievalResult({
status: "error",
error: `Retrieval failed: ${error}`,
hint: "The compressed content may have expired (default TTL: 30 minutes)",
});
@@ -28,7 +28,10 @@ describe("headroom_retrieve execute arguments (#4638)", () => {
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(String(fetchMock.mock.calls[0][0])).toBe(`http://127.0.0.1:8080/v1/retrieve/${HASH}`);
expect(JSON.parse(result)).toEqual({ original_content: "offline fixture" });
expect(result).toEqual({
content: [{ type: "text", text: '{"original_content":"offline fixture"}' }],
details: { original_content: "offline fixture" },
});
});
it("still accepts a direct execute({ hash }) call", async () => {
@@ -38,7 +41,7 @@ describe("headroom_retrieve execute arguments (#4638)", () => {
const result = await tool.execute({ hash: HASH });
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(JSON.parse(result)).toEqual({ original_content: "offline fixture" });
expect(result.details).toEqual({ original_content: "offline fixture" });
});
it("rejects a bad hash in params without sending a request", async () => {
@@ -48,7 +51,10 @@ describe("headroom_retrieve execute arguments (#4638)", () => {
const result = await tool.execute("call_fixture", { hash: "not-a-hash" });
expect(fetchMock).not.toHaveBeenCalled();
expect(result).toContain("Invalid hash format");
expect(result.details).toEqual({
status: "error",
error: "Invalid hash format. Expected 12 or 24 hex characters.",
});
});
it("rejects a missing params object without sending a request", async () => {
@@ -58,6 +64,47 @@ describe("headroom_retrieve execute arguments (#4638)", () => {
const result = await tool.execute("call_fixture");
expect(fetchMock).not.toHaveBeenCalled();
expect(result).toContain("Invalid hash format");
expect(result.details).toMatchObject({
status: "error",
error: expect.stringContaining("Invalid hash format"),
});
});
it("preserves a string response as model-visible text", async () => {
stubFetch().mockResolvedValueOnce(Response.json("original text"));
const tool = createHeadroomRetrieveTool({ proxyUrl: "http://127.0.0.1:8080" });
expect(await tool.execute("call_fixture", { hash: HASH })).toEqual({
content: [{ type: "text", text: "original text" }],
details: "original text",
});
});
it("returns an error result when the proxy returns HTTP 404", async () => {
stubFetch().mockResolvedValueOnce(new Response("not found", { status: 404 }));
const tool = createHeadroomRetrieveTool({ proxyUrl: "http://127.0.0.1:8080" });
const result = await tool.execute("call_fixture", { hash: HASH });
expect(result.details).toEqual({
status: "error",
error: "Retrieval failed: HTTP 404",
details: "not found",
});
expect(result.content).toEqual([{ type: "text", text: JSON.stringify(result.details) }]);
});
it("returns an error result when the request rejects", async () => {
stubFetch().mockRejectedValueOnce(new Error("connection reset"));
const tool = createHeadroomRetrieveTool({ proxyUrl: "http://127.0.0.1:8080" });
const result = await tool.execute("call_fixture", { hash: HASH });
expect(result.details).toMatchObject({
status: "error",
error: "Retrieval failed: Error: connection reset",
hint: expect.stringContaining("expired"),
});
expect(result.content).toEqual([{ type: "text", text: JSON.stringify(result.details) }]);
});
});
@@ -23,9 +23,10 @@ function stubRetrieveOk() {
return mock;
}
function retrieve(hash: string) {
async function retrieve(hash: string) {
const tool = createHeadroomRetrieveTool({ proxyUrl: PROXY_URL });
return tool.execute({ hash });
const result = await tool.execute({ hash });
return result.content[0].text;
}
afterEach(() => {