diff --git a/packages/adapters/hermes/README.md b/packages/adapters/hermes/README.md index 53c4ca3901c..c2c43be08c3 100644 --- a/packages/adapters/hermes/README.md +++ b/packages/adapters/hermes/README.md @@ -128,11 +128,18 @@ Then create an agent with adapter type `hermes_gateway`: "apiKey": "", "paperclipApiUrl": "http://127.0.0.1:3100", "sessionKeyStrategy": "issue", - "timeoutSec": 120 + "timeoutSec": 600 } } ``` +If the URL you have is the default Hermes dashboard at +`http://127.0.0.1:9119` or the default chat URL at +`http://127.0.0.1:9119/chat`, Paperclip maps it to +`http://127.0.0.1:9119/api` before calling Hermes API routes. `/chat` and the +dashboard root are browser UI routes; Paperclip tests `/api/health` and starts +runs with `/api/v1/runs` after mapping them to the API base. + This mode does not start Hermes. It creates runs with `POST /v1/runs`, streams Hermes events with SSE, polls run status as a fallback, and stops timed-out runs with `POST /v1/runs/{run_id}/stop`. diff --git a/packages/adapters/hermes/src/gateway/index.ts b/packages/adapters/hermes/src/gateway/index.ts index dd89113df8c..6d10a1d4ea8 100644 --- a/packages/adapters/hermes/src/gateway/index.ts +++ b/packages/adapters/hermes/src/gateway/index.ts @@ -33,13 +33,14 @@ Don't use when: Required fields: - apiBaseUrl (string): Hermes API server base URL, for example http://127.0.0.1:8642. + The default Hermes dashboard root or chat URL, for example http://127.0.0.1:9119 or http://127.0.0.1:9119/chat, is also accepted and maps to /api. - apiKey (string): Hermes API_SERVER_KEY. Sent as Authorization: Bearer . Optional fields: - headers (object or JSON string): extra noncritical headers. Authorization, Content-Type, Accept, Idempotency-Key, and X-Hermes-Session-Key are generated by the adapter. - paperclipApiUrl (string): Paperclip API URL reachable from the Hermes host. This is not a credential. - sessionKeyStrategy (issue | agent | run | none): defaults to issue. -- timeoutSec (number): defaults to 120. +- timeoutSec (number): defaults to 600. - eventReconnectMs (number): defaults to 2000. - instructions (string): stable Hermes instructions sent separately from wake input. diff --git a/packages/adapters/hermes/src/gateway/server/config-schema.ts b/packages/adapters/hermes/src/gateway/server/config-schema.ts index ad27054d233..18511fce1f6 100644 --- a/packages/adapters/hermes/src/gateway/server/config-schema.ts +++ b/packages/adapters/hermes/src/gateway/server/config-schema.ts @@ -10,14 +10,14 @@ export function getConfigSchema(): AdapterConfigSchema { label: "API base URL", type: "text", required: true, - hint: "Hermes API server base URL, such as http://127.0.0.1:8642 or a private HTTPS URL.", + hint: "Hermes API server base URL, such as http://127.0.0.1:8642 or a private HTTPS URL. The default dashboard root or chat URL, such as http://127.0.0.1:9119/chat, is accepted and maps to /api.", }, { key: "apiKey", label: "API key", type: "text", required: true, - hint: "Hermes API_SERVER_KEY. Stored as a Paperclip secret reference.", + hint: "Hermes API_SERVER_KEY, not PAPERCLIP_API_KEY. Stored as a Paperclip secret reference.", meta: { secret: true }, }, { diff --git a/packages/adapters/hermes/src/gateway/server/execute.test.ts b/packages/adapters/hermes/src/gateway/server/execute.test.ts index de3c165756e..6e58a06f290 100644 --- a/packages/adapters/hermes/src/gateway/server/execute.test.ts +++ b/packages/adapters/hermes/src/gateway/server/execute.test.ts @@ -144,6 +144,94 @@ describe("execute", () => { expect(body.session_id).toBe("paperclip:company:company-1:agent:agent-1:issue:issue-1"); }); + it("routes a bare Hermes dashboard URL on port 9119 through the API prefix", async () => { + const fetchMock = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url === "http://127.0.0.1:9119/api/v1/runs") { + return new Response(JSON.stringify({ run_id: "run-hermes-1", status: "started" }), { status: 200 }); + } + if (url === "http://127.0.0.1:9119/api/v1/runs/run-hermes-1/events") { + return new Response( + sseStream( + [ + "event: run.completed", + "data: {\"status\":\"completed\",\"output\":\"done\"}", + "", + ].join("\n"), + ), + { status: 200, headers: { "content-type": "text/event-stream" } }, + ); + } + return new Response(JSON.stringify({ status: "completed", output: "done" }), { status: 200 }); + }); + vi.stubGlobal("fetch", fetchMock); + + const ctx = makeCtx({ + apiBaseUrl: "http://127.0.0.1:9119", + apiKey: "secret-key", + timeoutSec: 5, + }); + const result = await execute(ctx); + + expect(result.exitCode).toBe(0); + expect(ctx.onMeta).toHaveBeenCalledWith( + expect.objectContaining({ + commandArgs: ["http://127.0.0.1:9119/api/v1/runs"], + }), + ); + expect((ctx.onLog as ReturnType).mock.calls.map(([, line]) => String(line)).join("\n")) + .toContain("creating run at http://127.0.0.1:9119/api/v1/runs"); + expect(fetchMock.mock.calls.map(([input]) => String(input))).toEqual( + expect.arrayContaining([ + "http://127.0.0.1:9119/api/v1/runs", + "http://127.0.0.1:9119/api/v1/runs/run-hermes-1/events", + ]), + ); + }); + + it("routes the default Hermes dashboard chat URL on port 9119 through the API prefix", async () => { + const fetchMock = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url === "http://127.0.0.1:9119/api/v1/runs") { + return new Response(JSON.stringify({ run_id: "run-hermes-chat", status: "started" }), { status: 200 }); + } + if (url === "http://127.0.0.1:9119/api/v1/runs/run-hermes-chat/events") { + return new Response( + sseStream( + [ + "event: run.completed", + "data: {\"status\":\"completed\",\"output\":\"done\"}", + "", + ].join("\n"), + ), + { status: 200, headers: { "content-type": "text/event-stream" } }, + ); + } + return new Response(JSON.stringify({ status: "completed", output: "done" }), { status: 200 }); + }); + vi.stubGlobal("fetch", fetchMock); + + const ctx = makeCtx({ + apiBaseUrl: "http://127.0.0.1:9119/chat", + apiKey: "secret-key", + timeoutSec: 5, + }); + const result = await execute(ctx); + + expect(result.exitCode).toBe(0); + expect(ctx.onMeta).toHaveBeenCalledWith( + expect.objectContaining({ + commandArgs: ["http://127.0.0.1:9119/api/v1/runs"], + }), + ); + expect(fetchMock.mock.calls.map(([input]) => String(input))).toEqual( + expect.arrayContaining([ + "http://127.0.0.1:9119/api/v1/runs", + "http://127.0.0.1:9119/api/v1/runs/run-hermes-chat/events", + ]), + ); + }); + it("redacts echoed auth material from stream logs and summaries", async () => { const ctx = makeCtx({ apiBaseUrl: "http://127.0.0.1:8642", @@ -275,6 +363,25 @@ describe("execute", () => { })); expect(result.exitCode).toBe(1); expect(result.errorCode).toBe("hermes_gateway_auth_failed"); + expect(result.errorMessage).toContain("Check adapterConfig.apiKey matches the Hermes API_SERVER_KEY"); + }); + + it("includes network causes in connection failure messages", async () => { + const cause = Object.assign(new Error("getaddrinfo ENOTFOUND host.docker.internal"), { code: "ENOTFOUND" }); + vi.stubGlobal("fetch", vi.fn(async () => { + throw Object.assign(new Error("fetch failed"), { cause }); + })); + + const result = await execute(makeCtx({ + apiBaseUrl: "http://host.docker.internal:8642", + apiKey: "secret-key", + dangerouslyAllowInsecureRemoteHttp: true, + })); + + expect(result.exitCode).toBe(1); + expect(result.errorCode).toBe("hermes_gateway_connect_failed"); + expect(result.errorMessage).toContain("ENOTFOUND"); + expect(result.errorMessage).toContain("host.docker.internal"); }); it("redacts echoed auth material from HTTP error payloads", async () => { @@ -396,6 +503,117 @@ describe("testEnvironment", () => { ); expect(fetchMock).toHaveBeenCalled(); }); + + it("fails test environment checks when Hermes health is unreachable", async () => { + const cause = Object.assign(new Error("getaddrinfo ENOTFOUND host.docker.internal"), { code: "ENOTFOUND" }); + vi.stubGlobal("fetch", vi.fn(async () => { + throw Object.assign(new Error("fetch failed"), { cause }); + })); + + const result = await testEnvironment({ + companyId: "company-1", + adapterType: "hermes_gateway", + config: { + apiBaseUrl: "http://host.docker.internal:8642", + apiKey: "secret-key", + dangerouslyAllowInsecureRemoteHttp: true, + }, + }); + + expect(result.status).toBe("fail"); + expect(result.checks).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "hermes_gateway_health_unreachable", + level: "error", + detail: expect.stringContaining("ENOTFOUND"), + }), + ]), + ); + }); + + it("fails test environment checks when Hermes health returns a non-ok status", async () => { + vi.stubGlobal("fetch", vi.fn(async () => new Response("bad key", { status: 401 }))); + + const result = await testEnvironment({ + companyId: "company-1", + adapterType: "hermes_gateway", + config: { + apiBaseUrl: "http://127.0.0.1:8642", + apiKey: "wrong-key", + }, + }); + + expect(result.status).toBe("fail"); + expect(result.checks).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "hermes_gateway_health_failed", + level: "error", + message: "Hermes Gateway health endpoint returned HTTP 401.", + }), + ]), + ); + }); + + it("tests a bare Hermes dashboard URL on port 9119 through the API prefix", async () => { + const fetchMock = vi.fn(async () => new Response("{}", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); + + const result = await testEnvironment({ + companyId: "company-1", + adapterType: "hermes_gateway", + config: { + apiBaseUrl: "http://127.0.0.1:9119", + apiKey: "secret-key", + }, + }); + + expect(result.status).toBe("pass"); + expect(result.checks).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "hermes_gateway_dashboard_root_mapped", + level: "info", + message: "Default Hermes dashboard root mapped to API base http://127.0.0.1:9119/api.", + hint: expect.stringContaining("/api/v1/runs"), + }), + ]), + ); + expect(fetchMock).toHaveBeenCalledWith( + "http://127.0.0.1:9119/api/health", + expect.objectContaining({ method: "GET" }), + ); + }); + + it("tests a Hermes dashboard chat URL on port 9119 through the API prefix", async () => { + const fetchMock = vi.fn(async () => new Response("{}", { status: 200 })); + vi.stubGlobal("fetch", fetchMock); + + const result = await testEnvironment({ + companyId: "company-1", + adapterType: "hermes_gateway", + config: { + apiBaseUrl: "http://127.0.0.1:9119/chat", + apiKey: "secret-key", + }, + }); + + expect(result.status).toBe("pass"); + expect(result.checks).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "hermes_gateway_dashboard_root_mapped", + level: "info", + message: "Default Hermes dashboard root mapped to API base http://127.0.0.1:9119/api.", + }), + ]), + ); + expect(fetchMock).toHaveBeenCalledWith( + "http://127.0.0.1:9119/api/health", + expect.objectContaining({ method: "GET" }), + ); + }); }); describe("mapFinalResultForTest", () => { diff --git a/packages/adapters/hermes/src/gateway/server/execute.ts b/packages/adapters/hermes/src/gateway/server/execute.ts index f28ccea4fec..9ec76e09652 100644 --- a/packages/adapters/hermes/src/gateway/server/execute.ts +++ b/packages/adapters/hermes/src/gateway/server/execute.ts @@ -84,6 +84,8 @@ const TERMINAL_STATUSES = new Set([ const FAILURE_STATUSES = new Set(["failed", "error"]); const CANCELLED_STATUSES = new Set(["cancelled", "canceled", "stopped", "interrupted"]); +const DEFAULT_HERMES_DASHBOARD_PORT = "9119"; +const HERMES_DASHBOARD_API_PATHS = new Set(["", "/", "/chat"]); function asRecord(value: unknown): Record | null { if (typeof value !== "object" || value === null || Array.isArray(value)) return null; @@ -118,7 +120,15 @@ function normalizeBaseUrl(value: string): URL | null { try { const url = new URL(value); if (url.protocol !== "http:" && url.protocol !== "https:") return null; - url.pathname = url.pathname.replace(/\/+$/, ""); + const normalizedPath = url.pathname.replace(/\/+$/, "") || "/"; + if ( + url.port === DEFAULT_HERMES_DASHBOARD_PORT && + HERMES_DASHBOARD_API_PATHS.has(normalizedPath) + ) { + url.pathname = "/api"; + } else { + url.pathname = url.pathname.replace(/\/+$/, ""); + } url.search = ""; url.hash = ""; return url; @@ -323,13 +333,24 @@ function classifyHttpError(status: number): { code: string; family: AdapterExecu return { code: "hermes_gateway_protocol_error", family: null }; } +function fetchFailureMessage(err: unknown): string { + const message = err instanceof Error ? err.message : String(err); + const cause = err instanceof Error ? (err as { cause?: unknown }).cause : null; + if (!cause || typeof cause !== "object") return message; + + const causeRecord = cause as { code?: unknown; message?: unknown }; + const causeMessage = typeof causeRecord.message === "string" ? causeRecord.message : ""; + const causeCode = typeof causeRecord.code === "string" ? causeRecord.code : ""; + if (!causeMessage || causeMessage === message) return causeCode ? `${message} (${causeCode})` : message; + return causeCode ? `${message} (${causeCode}: ${causeMessage})` : `${message} (${causeMessage})`; +} + async function fetchJson(input: RequestInfo | URL, init: RequestInit): Promise { let response: Response; try { response = await fetch(input, init); } catch (err) { - const message = err instanceof Error ? err.message : String(err); - const fetchErr = new Error(`Hermes gateway request failed: ${message}`) as HermesHttpError; + const fetchErr = new Error(`Hermes gateway request failed: ${fetchFailureMessage(err)}`) as HermesHttpError; fetchErr.code = "hermes_gateway_connect_failed"; throw fetchErr; } @@ -716,6 +737,9 @@ function errorResult(err: unknown, redactText: TextRedactor = sanitizeSensitiveT const hermesError = err as HermesHttpError; const code = hermesError.code ?? "hermes_gateway_protocol_error"; const classified = hermesError.status ? classifyHttpError(hermesError.status) : null; + const errorMessage = code === "hermes_gateway_auth_failed" + ? `${redactErrorMessage(err, redactText)}. Check adapterConfig.apiKey matches the Hermes API_SERVER_KEY for the running gateway.` + : redactErrorMessage(err, redactText); return { exitCode: 1, signal: null, @@ -723,7 +747,7 @@ function errorResult(err: unknown, redactText: TextRedactor = sanitizeSensitiveT errorCode: code, errorFamily: classified?.family ?? (code === "hermes_gateway_connect_failed" ? "transient_upstream" : null), retryNotBefore: hermesError.retryNotBefore ?? null, - errorMessage: redactErrorMessage(err, redactText), + errorMessage, errorMeta: { ...(hermesError.status ? { status: hermesError.status } : {}), ...(hermesError.body ? { body: redactForLog(hermesError.body, [], 0, redactText) as Record } : {}), @@ -809,11 +833,12 @@ export async function execute(ctx: AdapterExecutionContext): Promise { @@ -44,6 +72,7 @@ export async function testEnvironment( } const parsed = apiBaseUrl ? normalizeBaseUrl(apiBaseUrl) : null; + const mappedDefaultDashboardRoot = Boolean(parsed && isDefaultDashboardApiEntry(new URL(apiBaseUrl))); if (apiBaseUrl && !parsed) { checks.push({ code: "hermes_gateway_api_base_url_invalid", @@ -61,6 +90,15 @@ export async function testEnvironment( }); } + if (parsed && mappedDefaultDashboardRoot) { + checks.push({ + code: "hermes_gateway_dashboard_root_mapped", + level: "info", + message: `Default Hermes dashboard root mapped to API base ${parsed.toString()}.`, + hint: "Hermes dashboard routes such as /chat are browser UI routes. Paperclip gateway calls use /api/health and /api/v1/runs.", + }); + } + if (parsed && isRemotePlainHttp(parsed) && !allowsInsecureRemoteHttp(ctx.config)) { checks.push({ code: "hermes_gateway_plain_http_remote_denied", @@ -93,7 +131,7 @@ export async function testEnvironment( } try { - const healthUrl = new URL("/health", parsed); + const healthUrl = apiUrl(parsed, "/health"); const response = await fetch(healthUrl, { method: "GET", headers: { @@ -104,17 +142,21 @@ export async function testEnvironment( }); checks.push({ code: response.ok ? "hermes_gateway_health_ok" : "hermes_gateway_health_failed", - level: response.ok ? "info" : "warn", + level: response.ok ? "info" : "error", message: response.ok ? "Hermes Gateway health endpoint is reachable." : `Hermes Gateway health endpoint returned HTTP ${response.status}.`, + hint: response.ok + ? undefined + : "Check apiBaseUrl, API_SERVER_KEY, and that the Hermes API server is reachable from Paperclip.", }); } catch (err) { checks.push({ code: "hermes_gateway_health_unreachable", - level: "warn", + level: "error", message: "Could not reach Hermes Gateway health endpoint.", - detail: err instanceof Error ? err.message : String(err), + detail: errorDetail(err), + hint: "Check apiBaseUrl and make sure the Hermes API server is running where Paperclip can reach it.", }); } diff --git a/packages/adapters/hermes/src/gateway/shared/constants.ts b/packages/adapters/hermes/src/gateway/shared/constants.ts index de974c47a7f..5f128e42c4c 100644 --- a/packages/adapters/hermes/src/gateway/shared/constants.ts +++ b/packages/adapters/hermes/src/gateway/shared/constants.ts @@ -1,7 +1,7 @@ export const ADAPTER_TYPE = "hermes_gateway"; export const ADAPTER_LABEL = "Hermes Gateway"; -export const DEFAULT_TIMEOUT_SEC = 120; +export const DEFAULT_TIMEOUT_SEC = 600; export const DEFAULT_EVENT_RECONNECT_MS = 2_000; export const DEFAULT_POLL_INTERVAL_MS = 1_000; export const STOP_GRACE_MS = 10_000; diff --git a/server/src/__tests__/invite-accept-gateway-defaults.test.ts b/server/src/__tests__/invite-accept-gateway-defaults.test.ts index cec0f913b63..8f37397f74a 100644 --- a/server/src/__tests__/invite-accept-gateway-defaults.test.ts +++ b/server/src/__tests__/invite-accept-gateway-defaults.test.ts @@ -194,6 +194,62 @@ describe("normalizeAgentDefaultsForJoin (hermes_gateway)", () => { ]), ); }); + + it("maps the default Hermes dashboard root to the API base path", () => { + const normalized = normalizeAgentDefaultsForJoin({ + adapterType: "hermes_gateway", + defaultsPayload: { + apiBaseUrl: "http://127.0.0.1:9119", + apiKey: "hermes-key-1234567890", + }, + deploymentMode: "authenticated", + deploymentExposure: "private", + bindHost: "127.0.0.1", + allowedHostnames: [], + }); + + expect(normalized.fatalErrors).toEqual([]); + expect(normalized.normalized?.apiBaseUrl).toBe("http://127.0.0.1:9119/api"); + expect(normalized.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "hermes_gateway_dashboard_root_mapped", + level: "info", + hint: expect.stringContaining("/api/v1/runs"), + }), + expect.objectContaining({ + code: "hermes_gateway_api_base_url_configured", + message: "Hermes gateway endpoint set to http://127.0.0.1:9119/api", + }), + ]), + ); + }); + + it("maps the default Hermes dashboard chat URL to the API base path", () => { + const normalized = normalizeAgentDefaultsForJoin({ + adapterType: "hermes_gateway", + defaultsPayload: { + apiBaseUrl: "http://127.0.0.1:9119/chat", + apiKey: "hermes-key-1234567890", + }, + deploymentMode: "authenticated", + deploymentExposure: "private", + bindHost: "127.0.0.1", + allowedHostnames: [], + }); + + expect(normalized.fatalErrors).toEqual([]); + expect(normalized.normalized?.apiBaseUrl).toBe("http://127.0.0.1:9119/api"); + expect(normalized.diagnostics).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + code: "hermes_gateway_dashboard_root_mapped", + level: "info", + hint: expect.stringContaining("/api/v1/runs"), + }), + ]), + ); + }); }); describeEmbeddedPostgres("prepareAgentDefaultsPayloadForJoinPersistence (hermes_gateway)", () => { diff --git a/server/src/__tests__/invite-onboarding-text.test.ts b/server/src/__tests__/invite-onboarding-text.test.ts index e08828a907a..41fa6d19174 100644 --- a/server/src/__tests__/invite-onboarding-text.test.ts +++ b/server/src/__tests__/invite-onboarding-text.test.ts @@ -55,6 +55,7 @@ describe("buildInviteOnboardingTextDocument", () => { expect(text).toContain('"adapterType": "hermes_gateway"'); expect(text).toContain("API_SERVER_ENABLED=true"); expect(text).toContain("API_SERVER_KEY"); + expect(text).toContain("Set agentDefaultsPayload.apiKey to the exact same value as API_SERVER_KEY"); expect(text).toContain("hermes gateway run --replace --accept-hooks"); expect(text).toContain("Default Hermes API server port: 8642"); expect(text).toContain("agentDefaultsPayload.apiBaseUrl"); @@ -62,12 +63,22 @@ describe("buildInviteOnboardingTextDocument", () => { expect(text).toContain("hermes_local"); expect(text).toContain("Hermes-originated Paperclip API usage"); expect(text).toContain("http://127.0.0.1:8642"); + expect(text).toContain("http://127.0.0.1:9119"); + expect(text).toContain("http://127.0.0.1:9119/chat"); + expect(text).toContain("map to /api"); + expect(text).toContain("/chat and the dashboard root are browser UI routes"); + expect(text).toContain("/api/v1/runs"); + expect(text).toContain("Do not rotate or invent a Paperclip key manually"); expect(text).toContain("http://192.168.1.25:8642"); expect(text).toContain("tailnet-name.ts.net:8642"); expect(text).toContain("http://host.docker.internal:8642"); expect(text).toContain("https://hermes-gateway.example"); expect(text).toContain("set the first reachable candidate as agentDefaultsPayload.paperclipApiUrl"); expect(text).toContain("PAPERCLIP_API_KEY"); + expect(text).toContain("Store the parsed token field from the raw HTTP JSON response"); + expect(text).toContain("A token value containing literal ... or [redacted]"); + expect(text).toContain("The response body includes the full token exactly once"); + expect(text).toContain("Do not persist displayed previews containing literal ... or [redacted]"); expect(text).toContain("Use your runtime's normal skill or instruction installation path."); expect(text).toContain("Decide which Paperclip adapter type matches your runtime."); }); diff --git a/server/src/adapters/hermes-gateway-doc.ts b/server/src/adapters/hermes-gateway-doc.ts index 8fc2716806c..75538fce9ec 100644 --- a/server/src/adapters/hermes-gateway-doc.ts +++ b/server/src/adapters/hermes-gateway-doc.ts @@ -14,13 +14,15 @@ Don't use when: Runtime distinction: - hermes_local: Paperclip starts Hermes on the Paperclip host through the built-in local adapter. - hermes_gateway: Paperclip calls an already-running Hermes API server using agentDefaultsPayload.apiBaseUrl. -- Hermes-originated Paperclip API usage: Hermes calls Paperclip with PAPERCLIP_API_URL and PAPERCLIP_BRIDGE_API_KEY. Create that Paperclip key with scope.kind = "task_bridge" and an approved parent/project boundary; do not expose a normal claimed agent key to Hermes-facing chat/webhook surfaces. Do not use agentDefaultsPayload.apiBaseUrl for Paperclip API calls. +- Hermes-originated Paperclip API usage: Hermes calls Paperclip with PAPERCLIP_API_URL and the Paperclip API key claimed through the standard join approval flow. Do not use agentDefaultsPayload.apiBaseUrl for Paperclip API calls. For internet-facing Hermes chat/webhook task bridges, use a separate task_bridge key instead of exposing the normal claimed agent key. Hermes gateway process setup: - Set API_SERVER_ENABLED=true. - Set API_SERVER_KEY to a generated secret value. Do not paste a real key into tickets, docs, screenshots, or tests. - Start Hermes with: hermes gateway run --replace --accept-hooks - Default Hermes API server port: 8642. +- Default Hermes dashboard port: 9119. If Paperclip is configured with a default dashboard root or chat URL such as http://127.0.0.1:9119 or http://127.0.0.1:9119/chat, it maps the base URL to /api automatically. +- Watch out: /chat and the dashboard root are browser UI routes. Paperclip tests /api/health and starts runs with /api/v1/runs after mapping them to the API base. Join request minimum: { @@ -36,13 +38,14 @@ Join request minimum: } Core fields: -- agentDefaultsPayload.apiBaseUrl (string, required): Base URL for the Hermes API server as reachable from the Paperclip server. -- agentDefaultsPayload.apiKey (string, required unless the adapter package documents another auth field): Hermes API server key matching API_SERVER_KEY. +- agentDefaultsPayload.apiBaseUrl (string, required): Base URL for the Hermes API server as reachable from the Paperclip server. A default dashboard root or chat URL such as http://127.0.0.1:9119 or http://127.0.0.1:9119/chat is accepted and maps to http://127.0.0.1:9119/api. +- agentDefaultsPayload.apiKey (string, required unless the adapter package documents another auth field): Hermes API server key matching API_SERVER_KEY. This is the Hermes gateway key, not the claimed Paperclip API key. - agentDefaultsPayload.paperclipApiUrl (string, strongly recommended): Paperclip base URL as reachable from Hermes for invite, claim, skill bootstrap, and later Paperclip API calls. - agentDefaultsPayload.timeoutSec or timeoutMs (number, optional): Runtime request timeout when supported by the installed Hermes gateway adapter. Network examples: - Local loopback on one host: agentDefaultsPayload.apiBaseUrl = "http://127.0.0.1:8642"; agentDefaultsPayload.paperclipApiUrl = "http://127.0.0.1:3100". +- Local dashboard root or chat URL on one host: agentDefaultsPayload.apiBaseUrl = "http://127.0.0.1:9119" or "http://127.0.0.1:9119/chat"; Paperclip maps it to "http://127.0.0.1:9119/api". - LAN/private network: agentDefaultsPayload.apiBaseUrl = "http://192.168.1.25:8642"; agentDefaultsPayload.paperclipApiUrl = "http://192.168.1.10:3100". Use private IPs or hostnames reachable from both machines. - Private overlay: agentDefaultsPayload.apiBaseUrl = "http://hermes-host.tailnet-name.ts.net:8642"; agentDefaultsPayload.paperclipApiUrl = "http://paperclip-host.tailnet-name.ts.net:3100". Add the Paperclip hostname with pnpm paperclipai allowed-hostname when authenticated/private mode requires it. - Docker: if Hermes runs on the host and Paperclip runs in Docker, use agentDefaultsPayload.apiBaseUrl = "http://host.docker.internal:8642". If Hermes runs in another container, use the Compose service DNS name such as "http://hermes:8642". @@ -50,6 +53,7 @@ Network examples: Security notes: - Treat API_SERVER_KEY and PAPERCLIP_BRIDGE_API_KEY as secrets. +- When claiming the normal Paperclip agent API key, store the parsed token field from the raw claim response before printing or summarizing it. Hermes/tool displays may redact secrets with literal ... or [redacted]; those previews are not valid keys. - Never use a normal claimed Paperclip agent API key for internet-facing Hermes-originated task bridge calls; task_bridge keys cannot use company-wide issue list/search/read surfaces and can only mutate bridge-created or assigned issues. - Prefer private network or TLS for non-loopback gateway access. - Use placeholders such as in docs and tests. diff --git a/server/src/routes/access.ts b/server/src/routes/access.ts index 0de06e57c79..2e28b579343 100644 --- a/server/src/routes/access.ts +++ b/server/src/routes/access.ts @@ -290,6 +290,9 @@ type JoinDiagnostic = { hint?: string; }; +const DEFAULT_HERMES_DASHBOARD_PORT = "9119"; +const HERMES_DASHBOARD_API_PATHS = new Set(["", "/", "/chat"]); + function isPlainObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } @@ -305,6 +308,26 @@ function isLoopbackHost(hostname: string): boolean { ); } +function normalizeHermesGatewayApiBaseUrl(url: URL): URL { + const normalized = new URL(url.toString()); + const normalizedPath = normalized.pathname.replace(/\/+$/, "") || "/"; + if ( + normalized.port === DEFAULT_HERMES_DASHBOARD_PORT && + HERMES_DASHBOARD_API_PATHS.has(normalizedPath) + ) { + normalized.pathname = "/api"; + } + return normalized; +} + +function isDefaultHermesDashboardRoot(url: URL): boolean { + const normalizedPath = url.pathname.replace(/\/+$/, "") || "/"; + return ( + url.port === DEFAULT_HERMES_DASHBOARD_PORT && + HERMES_DASHBOARD_API_PATHS.has(normalizedPath) + ); +} + function normalizeHostname(value: string | null | undefined): string | null { if (!value) return null; const trimmed = value.trim(); @@ -703,12 +726,14 @@ export function normalizeAgentDefaultsForJoin(input: { code: "hermes_gateway_api_base_url_missing", level: "warn", message: "Hermes gateway apiBaseUrl is missing.", - hint: "Set agentDefaultsPayload.apiBaseUrl to the Hermes API server URL.", + hint: "Set agentDefaultsPayload.apiBaseUrl to the Hermes API server URL. The default dashboard root or chat URL on port 9119 is accepted and maps to /api.", }); fatalErrors.push("agentDefaultsPayload.apiBaseUrl is required"); } else { try { - const apiBaseUrl = new URL(rawApiBaseUrl); + const rawParsedApiBaseUrl = new URL(rawApiBaseUrl); + const mappedDefaultDashboardRoot = isDefaultHermesDashboardRoot(rawParsedApiBaseUrl); + const apiBaseUrl = normalizeHermesGatewayApiBaseUrl(rawParsedApiBaseUrl); if (apiBaseUrl.protocol !== "http:" && apiBaseUrl.protocol !== "https:") { diagnostics.push({ code: "hermes_gateway_api_base_url_protocol", @@ -732,6 +757,14 @@ export function normalizeAgentDefaultsForJoin(input: { ); } else { normalized.apiBaseUrl = apiBaseUrl.toString(); + if (mappedDefaultDashboardRoot) { + diagnostics.push({ + code: "hermes_gateway_dashboard_root_mapped", + level: "info", + message: `Default Hermes dashboard root mapped to API base ${apiBaseUrl.toString()}`, + hint: "Hermes dashboard and /chat routes are browser UI routes. Paperclip gateway calls use /api/health and /api/v1/runs.", + }); + } if (apiBaseUrl.protocol === "http:" && !isLoopbackHost(apiBaseUrl.hostname)) { diagnostics.push({ code: "hermes_gateway_plain_http_remote_unsafe_allowed", @@ -1695,7 +1728,7 @@ function buildInviteOnboardingManifest( ), onboarding: { instructions: - "Join as an external Paperclip agent, save your one-time claim secret, wait for board approval, then claim your API key. Use requestType='agent', include your agentName and capabilities, and set adapterType plus agentDefaultsPayload for your runtime when applicable. OpenClaw Gateway agents must use adapterType='openclaw_gateway', set agentDefaultsPayload.url to a ws:// or wss:// gateway endpoint, and include agentDefaultsPayload.headers.x-openclaw-token. Hermes Gateway agents must use adapterType='hermes_gateway', start Hermes with API_SERVER_ENABLED=true, API_SERVER_KEY, and `hermes gateway run --replace --accept-hooks`, then set agentDefaultsPayload.apiBaseUrl and agentDefaultsPayload.paperclipApiUrl.", + "Join as an external Paperclip agent, save your one-time claim secret, wait for board approval, then claim your Paperclip API key through the standard claim endpoint. Use requestType='agent', include your agentName and capabilities, and set adapterType plus agentDefaultsPayload for your runtime when applicable. Hermes Gateway agents must use adapterType='hermes_gateway', start a clean Hermes install with API_SERVER_ENABLED=true and a fresh API_SERVER_KEY, then run `hermes gateway run --replace --accept-hooks`. Put the Hermes gateway URL in agentDefaultsPayload.apiBaseUrl, put the exact API_SERVER_KEY value in agentDefaultsPayload.apiKey, and put the reachable Paperclip base URL in agentDefaultsPayload.paperclipApiUrl. If you use the default Hermes dashboard root or /chat URL on port 9119, Paperclip maps it to /api automatically. OpenClaw Gateway agents must use adapterType='openclaw_gateway', set agentDefaultsPayload.url to a ws:// or wss:// gateway endpoint, and include agentDefaultsPayload.headers.x-openclaw-token.", inviteMessage: extractInviteMessage(invite), recommendedAdapterType: null, requiredFields: { @@ -1705,7 +1738,7 @@ function buildInviteOnboardingManifest( "Adapter type for this runtime. Use 'openclaw_gateway' only for OpenClaw Gateway agents. Use 'hermes_gateway' only for Hermes Gateway agents.", capabilities: "Optional capability summary", agentDefaultsPayload: - "Runtime-specific adapter config. OpenClaw Gateway agents must include url (ws:// or wss://) and headers.x-openclaw-token. Hermes Gateway agents must include apiBaseUrl, API_SERVER_KEY-backed auth, and paperclipApiUrl. Other runtimes should include the config their adapter expects." + "Runtime-specific adapter config. OpenClaw Gateway agents must include url (ws:// or wss://) and headers.x-openclaw-token. Hermes Gateway agents must include apiBaseUrl, apiKey set to the Hermes API_SERVER_KEY, and paperclipApiUrl. A default Hermes dashboard root or /chat URL such as http://127.0.0.1:9119/chat is accepted and maps to /api. Other runtimes should include the config their adapter expects." }, registrationEndpoint: { method: "POST", @@ -1856,13 +1889,17 @@ export function buildInviteOnboardingTextDocument( Hermes Gateway setup: - adapterType: "hermes_gateway" - - Start Hermes with API_SERVER_ENABLED=true and API_SERVER_KEY=. + - For a clean Hermes install, generate a fresh random gateway key and start Hermes with API_SERVER_ENABLED=true and API_SERVER_KEY=. - Run: hermes gateway run --replace --accept-hooks - Default Hermes API server port: 8642. - Set agentDefaultsPayload.apiBaseUrl to the Hermes gateway URL Paperclip can reach. + - Set agentDefaultsPayload.apiKey to the exact same value as API_SERVER_KEY. This is the Hermes gateway key, not the Paperclip key. + - If you only have the default Hermes dashboard or chat URL, http://127.0.0.1:9119 and http://127.0.0.1:9119/chat are accepted and map to /api automatically. + - Watch out: /chat and the dashboard root are browser UI routes. Paperclip tests /api/health and starts runs with /api/v1/runs after mapping them to the API base. - Set agentDefaultsPayload.paperclipApiUrl to the Paperclip base URL Hermes can reach. - Use hermes_local when Paperclip should start Hermes on the Paperclip host. - Use hermes_gateway when Paperclip should call an already-running Hermes API server. + - After board approval, claim the Paperclip API key once with the claim endpoint below and save it as PAPERCLIP_API_KEY. Store the parsed token field from the raw HTTP JSON response before printing or summarizing it; do not copy token values from chat, transcript, or tool-output previews. A token value containing literal ... or [redacted] is a masked display preview, not a valid key. Do not rotate or invent a Paperclip key manually. - Hermes-originated Paperclip API usage means Hermes calls Paperclip with PAPERCLIP_API_URL and PAPERCLIP_API_KEY after approval/key claim. Do not confuse that with agentDefaultsPayload.apiBaseUrl, which points Paperclip to Hermes. Hermes Gateway payload example: @@ -1879,7 +1916,8 @@ export function buildInviteOnboardingTextDocument( } Hermes Gateway network examples: - - Local loopback: agentDefaultsPayload.apiBaseUrl = "http://127.0.0.1:8642" and agentDefaultsPayload.paperclipApiUrl = "http://127.0.0.1:3100". + - Local loopback API server: agentDefaultsPayload.apiBaseUrl = "http://127.0.0.1:8642" and agentDefaultsPayload.paperclipApiUrl = "http://127.0.0.1:3100". + - Local loopback dashboard root or chat URL: agentDefaultsPayload.apiBaseUrl = "http://127.0.0.1:9119" or "http://127.0.0.1:9119/chat"; Paperclip maps either one to "http://127.0.0.1:9119/api". - LAN/private network: use reachable private addresses, for example agentDefaultsPayload.apiBaseUrl = "http://192.168.1.25:8642" and agentDefaultsPayload.paperclipApiUrl = "http://192.168.1.10:3100". - Private overlay: use overlay DNS names, for example agentDefaultsPayload.apiBaseUrl = "http://hermes-host.tailnet-name.ts.net:8642" and agentDefaultsPayload.paperclipApiUrl = "http://paperclip-host.tailnet-name.ts.net:3100". - Docker: if Paperclip runs in Docker and Hermes runs on the host, use agentDefaultsPayload.apiBaseUrl = "http://host.docker.internal:8642"; if both run in Compose, use the Hermes service name. @@ -1903,7 +1941,7 @@ export function buildInviteOnboardingTextDocument( "claimSecret": "" } - On successful claim, save the full JSON response somewhere private for your runtime and set PAPERCLIP_API_KEY and PAPERCLIP_API_URL for future Paperclip API calls. + On successful claim, save the full JSON response somewhere private for your runtime and set PAPERCLIP_API_KEY and PAPERCLIP_API_URL for future Paperclip API calls. The response body includes the full token exactly once, but runtime displays and tool summaries may mask or truncate it. Write the raw response token directly to private storage before logging anything, then verify it with an authenticated Paperclip API call. Do not persist displayed previews containing literal ... or [redacted]. Important: - claim secrets expire diff --git a/ui/src/adapters/hermes-gateway/config-fields.test.tsx b/ui/src/adapters/hermes-gateway/config-fields.test.tsx new file mode 100644 index 00000000000..d3d98546db1 --- /dev/null +++ b/ui/src/adapters/hermes-gateway/config-fields.test.tsx @@ -0,0 +1,84 @@ +// @vitest-environment jsdom + +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { HermesGatewayConfigFields } from "./config-fields"; +import type { AdapterConfigFieldsProps } from "../types"; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; + +function renderFields(overrides: Partial = {}) { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + const mark = vi.fn(); + const set = vi.fn(); + const props: AdapterConfigFieldsProps = { + mode: "edit", + isCreate: false, + adapterType: "hermes_gateway", + values: null, + set: null, + config: {}, + eff: (_group, _field, original) => original, + mark, + models: [], + ...overrides, + }; + + act(() => { + root.render( + + + , + ); + }); + + return { container, root, mark, set }; +} + +describe("HermesGatewayConfigFields", () => { + const roots: Root[] = []; + + afterEach(() => { + for (const root of roots.splice(0)) { + act(() => root.unmount()); + } + document.body.innerHTML = ""; + }); + + it("shows the gateway URL and runtime fields in edit mode", () => { + const result = renderFields({ + config: { + apiBaseUrl: "http://127.0.0.1:8642", + apiKey: { type: "secret_ref", secretId: "11111111-1111-4111-8111-111111111111", version: "latest" }, + paperclipApiUrl: "http://127.0.0.1:3100", + sessionKeyStrategy: "issue", + }, + }); + roots.push(result.root); + + const text = result.container.textContent ?? ""; + expect(text).toContain("API base URL"); + expect(text).toContain("API key"); + expect(text).toContain("Paperclip API URL"); + expect(text).toContain("Session key strategy"); + expect(text).toContain("Timeout seconds"); + expect(text).toContain("Event reconnect ms"); + expect(text).toContain("Dangerously allow remote HTTP"); + expect(text).toContain("Extra headers"); + expect(text).toContain("Instructions"); + + const urlInput = result.container.querySelector('input[value="http://127.0.0.1:8642"]'); + expect(urlInput).toBeTruthy(); + + const apiKeyInput = Array.from(result.container.querySelectorAll('input[type="password"]')) + .find((input) => input.placeholder.includes("Stored secret")); + expect(apiKeyInput).toBeTruthy(); + + expect(result.container.querySelector('button[aria-label="Show API key"]')).toBeTruthy(); + }); +}); diff --git a/ui/src/adapters/hermes-gateway/config-fields.tsx b/ui/src/adapters/hermes-gateway/config-fields.tsx new file mode 100644 index 00000000000..3d04dbc997e --- /dev/null +++ b/ui/src/adapters/hermes-gateway/config-fields.tsx @@ -0,0 +1,252 @@ +import { useEffect, useState } from "react"; +import { Eye, EyeOff } from "lucide-react"; +import type { AdapterConfigFieldsProps, CreateConfigValues } from "../types"; +import { + DraftInput, + DraftNumberInput, + DraftTextarea, + Field, + ToggleField, +} from "../../components/agent-config-primitives"; + +const inputClass = + "w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40"; + +const DEFAULT_SESSION_KEY_STRATEGY = "issue"; +const DEFAULT_TIMEOUT_SEC = 600; +const DEFAULT_EVENT_RECONNECT_MS = 2000; + +type SecretRef = { + type: "secret_ref"; + secretId: string; + version?: number | "latest"; +}; + +function isSecretRef(value: unknown): value is SecretRef { + return ( + typeof value === "object" && + value !== null && + !Array.isArray(value) && + (value as { type?: unknown }).type === "secret_ref" && + typeof (value as { secretId?: unknown }).secretId === "string" + ); +} + +function readCreateValue(values: CreateConfigValues | null, key: string, fallback: unknown): unknown { + return values?.adapterSchemaValues?.[key] ?? fallback; +} + +function writeCreateValue( + values: CreateConfigValues | null, + set: ((patch: Partial) => void) | null, + key: string, + value: unknown, +) { + set?.({ + adapterSchemaValues: { + ...values?.adapterSchemaValues, + [key]: value, + }, + }); +} + +function stringifyHeaders(value: unknown): string { + if (typeof value === "string") return value; + if (value && typeof value === "object" && !Array.isArray(value)) { + return JSON.stringify(value, null, 2); + } + return ""; +} + +function SecretField({ + label, + value, + onCommit, + placeholder, + stored, +}: { + label: string; + value: string; + onCommit: (v: string) => void; + placeholder?: string; + stored?: boolean; +}) { + const [visible, setVisible] = useState(false); + return ( + +
+ + +
+
+ ); +} + +export function HermesGatewayConfigFields({ + isCreate, + values, + set, + config, + eff, + mark, +}: AdapterConfigFieldsProps) { + const storedApiKey = config.apiKey; + const hasStoredApiKey = isSecretRef(storedApiKey) || typeof storedApiKey === "string"; + const editApiKeyValue = typeof storedApiKey === "string" ? String(eff("adapterConfig", "apiKey", storedApiKey)) : ""; + + const configuredHeaders = stringifyHeaders(config.headers); + const editHeaders = eff("adapterConfig", "headers", configuredHeaders); + const [headersDraft, setHeadersDraft] = useState(String(editHeaders ?? "")); + + useEffect(() => { + if (!isCreate) setHeadersDraft(String(editHeaders ?? "")); + }, [editHeaders, isCreate]); + + const readValue = (key: string, fallback: unknown) => + isCreate ? readCreateValue(values, key, fallback) : eff("adapterConfig", key, (config[key] ?? fallback) as never); + + const writeValue = (key: string, value: unknown) => { + if (isCreate) { + writeCreateValue(values, set, key, value); + } else { + mark("adapterConfig", key, value); + } + }; + + const apiBaseUrl = String(readValue("apiBaseUrl", "") ?? ""); + const paperclipApiUrl = String(readValue("paperclipApiUrl", "") ?? ""); + const sessionKeyStrategy = String(readValue("sessionKeyStrategy", DEFAULT_SESSION_KEY_STRATEGY) ?? DEFAULT_SESSION_KEY_STRATEGY); + const timeoutSec = Number(readValue("timeoutSec", DEFAULT_TIMEOUT_SEC) ?? DEFAULT_TIMEOUT_SEC); + const eventReconnectMs = Number(readValue("eventReconnectMs", DEFAULT_EVENT_RECONNECT_MS) ?? DEFAULT_EVENT_RECONNECT_MS); + const allowInsecureRemoteHttp = Boolean(readValue("dangerouslyAllowInsecureRemoteHttp", false)); + const instructions = String(readValue("instructions", "") ?? ""); + const headers = isCreate + ? String(readCreateValue(values, "headers", "") ?? "") + : headersDraft; + + return ( + <> + + writeValue("apiBaseUrl", v || undefined)} + immediate + className={inputClass} + placeholder="http://127.0.0.1:8642" + /> + + + writeValue("apiKey", v || undefined)} + placeholder="Hermes API_SERVER_KEY, not PAPERCLIP_API_KEY" + stored={!isCreate && hasStoredApiKey && !editApiKeyValue} + /> + + + writeValue("paperclipApiUrl", v || undefined)} + immediate + className={inputClass} + placeholder="http://127.0.0.1:3100" + /> + + + + + + + + writeValue("timeoutSec", v)} + immediate + className={inputClass} + /> + + + + writeValue("eventReconnectMs", v)} + immediate + className={inputClass} + /> + + + writeValue("dangerouslyAllowInsecureRemoteHttp", v)} + /> + + +