Merge remote-tracking branch 'origin/master' into feature/upload-company-logo

This commit is contained in:
JonCSykes
2026-03-06 22:55:25 -05:00
14 changed files with 909 additions and 57 deletions

View File

@@ -218,7 +218,8 @@ By default, agents run on scheduled heartbeats and event-based triggers (task as
## Development ## Development
```bash ```bash
pnpm dev # Full dev (API + UI) pnpm dev # Full dev (API + UI, watch mode)
pnpm dev:once # Full dev without file watching
pnpm dev:server # Server only pnpm dev:server # Server only
pnpm build # Build all pnpm build # Build all
pnpm typecheck # Type checking pnpm typecheck # Type checking

View File

@@ -29,6 +29,8 @@ This starts:
- API server: `http://localhost:3100` - API server: `http://localhost:3100`
- UI: served by the API server in dev middleware mode (same origin as API) - UI: served by the API server in dev middleware mode (same origin as API)
`pnpm dev` runs the server in watch mode and restarts on changes from workspace packages (including adapter packages). Use `pnpm dev:once` to run without file watching.
Tailscale/private-auth dev mode: Tailscale/private-auth dev mode:
```sh ```sh

View File

@@ -3,8 +3,9 @@
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "node scripts/dev-runner.mjs dev", "dev": "node scripts/dev-runner.mjs watch",
"dev:watch": "PAPERCLIP_MIGRATION_PROMPT=never node scripts/dev-runner.mjs watch", "dev:watch": "PAPERCLIP_MIGRATION_PROMPT=never node scripts/dev-runner.mjs watch",
"dev:once": "node scripts/dev-runner.mjs dev",
"dev:server": "pnpm --filter @paperclipai/server dev", "dev:server": "pnpm --filter @paperclipai/server dev",
"dev:ui": "pnpm --filter @paperclipai/ui dev", "dev:ui": "pnpm --filter @paperclipai/ui dev",
"build": "pnpm -r build", "build": "pnpm -r build",

View File

@@ -0,0 +1,139 @@
# OpenClaw Adapter Modes
This document describes how `@paperclipai/adapter-openclaw` selects request shape and endpoint behavior.
## Transport Modes
The adapter has two transport modes:
- `sse` (default)
- `webhook`
Configured via `adapterConfig.streamTransport` (or legacy `adapterConfig.transport`).
## Mode Matrix
| streamTransport | configured URL path | behavior |
| --- | --- | --- |
| `sse` | `/v1/responses` | Sends OpenResponses request with `stream: true`, expects `text/event-stream` response until terminal event. |
| `sse` | `/hooks/*` | Rejected (`openclaw_sse_incompatible_endpoint`). Hooks are not stream-capable. |
| `sse` | other endpoint | Sends generic streaming payload (`stream: true`, `text`, `paperclip`) and expects SSE response. |
| `webhook` | `/hooks/wake` | Sends wake payload `{ text, mode }`. |
| `webhook` | `/hooks/agent` | Sends agent payload `{ message, ...hook fields }`. |
| `webhook` | `/v1/responses` | Compatibility flow: tries `/hooks/agent` first, then falls back to original `/v1/responses` if hook endpoint returns `404`. |
| `webhook` | other endpoint | Sends legacy generic webhook payload (`stream: false`, `text`, `paperclip`). |
## Webhook Payload Shapes
### 1) Hook Wake (`/hooks/wake`)
Payload:
```json
{
"text": "Paperclip wake event ...",
"mode": "now"
}
```
### 2) Hook Agent (`/hooks/agent`)
Payload:
```json
{
"message": "Paperclip wake event ...",
"name": "Optional hook name",
"agentId": "Optional OpenClaw agent id",
"wakeMode": "now",
"deliver": true,
"channel": "last",
"to": "Optional channel recipient",
"model": "Optional model override",
"thinking": "Optional thinking override",
"timeoutSeconds": 120
}
```
Notes:
- `message` is always used (not `text`) for `/hooks/agent`.
- `sessionKey` is **not** sent by default for `/hooks/agent`.
- To include derived session keys in `/hooks/agent`, set:
- `hookIncludeSessionKey: true`
### 3) OpenResponses (`/v1/responses`)
When used directly (SSE mode or webhook fallback), payload uses OpenResponses shape:
```json
{
"stream": false,
"model": "openclaw",
"input": "...",
"metadata": {
"paperclip_session_key": "paperclip"
}
}
```
## Auth Header Behavior
You can provide auth either explicitly or via token headers:
- Explicit auth header:
- `webhookAuthHeader: "Bearer ..."`
- Token headers (adapter derives `Authorization` automatically when missing):
- `headers["x-openclaw-token"]` (preferred)
- `headers["x-openclaw-auth"]` (legacy compatibility)
## Session Key Behavior
Session keys are resolved from:
- `sessionKeyStrategy`: `fixed` (default), `issue`, `run`
- `sessionKey`: used when strategy is `fixed` (default value `paperclip`)
Where session keys are applied:
- `/v1/responses`: sent via `x-openclaw-session-key` header + metadata.
- `/hooks/wake`: not sent as a dedicated field.
- `/hooks/agent`: only sent if `hookIncludeSessionKey=true`.
- Generic webhook fallback: sent as `sessionKey` field.
## Recommended Config Examples
### SSE (streaming endpoint)
```json
{
"url": "http://127.0.0.1:18789/v1/responses",
"streamTransport": "sse",
"method": "POST",
"headers": {
"x-openclaw-token": "replace-me"
}
}
```
### Webhook (hooks endpoint)
```json
{
"url": "http://127.0.0.1:18789/hooks/agent",
"streamTransport": "webhook",
"method": "POST",
"headers": {
"x-openclaw-token": "replace-me"
}
}
```
### Webhook with legacy URL retained
If URL is still `/v1/responses` and `streamTransport=webhook`, the adapter will:
1. try `.../hooks/agent`
2. fallback to original `.../v1/responses` when hook endpoint returns `404`
This lets older OpenClaw setups continue working while migrating to hooks.

View File

@@ -11,7 +11,7 @@ Use when:
- You run an OpenClaw agent remotely and wake it over HTTP. - You run an OpenClaw agent remotely and wake it over HTTP.
- You want selectable transport: - You want selectable transport:
- \`sse\` for streaming execution in one Paperclip run. - \`sse\` for streaming execution in one Paperclip run.
- \`webhook\` for wake-style callbacks (including /hooks/wake compatibility). - \`webhook\` for wake-style callbacks (\`/hooks/wake\`, \`/hooks/agent\`, or compatibility webhooks).
Don't use when: Don't use when:
- You need local CLI execution inside Paperclip (use claude_local/codex_local/opencode_local/process). - You need local CLI execution inside Paperclip (use claude_local/codex_local/opencode_local/process).
@@ -25,6 +25,7 @@ Core fields:
- webhookAuthHeader (string, optional): Authorization header value if your endpoint requires auth - webhookAuthHeader (string, optional): Authorization header value if your endpoint requires auth
- payloadTemplate (object, optional): additional JSON payload fields merged into each wake payload - payloadTemplate (object, optional): additional JSON payload fields merged into each wake payload
- paperclipApiUrl (string, optional): absolute http(s) Paperclip base URL to advertise to OpenClaw as \`PAPERCLIP_API_URL\` - paperclipApiUrl (string, optional): absolute http(s) Paperclip base URL to advertise to OpenClaw as \`PAPERCLIP_API_URL\`
- hookIncludeSessionKey (boolean, optional): when true, include derived \`sessionKey\` in \`/hooks/agent\` webhook payloads (default false)
Session routing fields: Session routing fields:
- sessionKeyStrategy (string, optional): \`fixed\` (default), \`issue\`, or \`run\` - sessionKeyStrategy (string, optional): \`fixed\` (default), \`issue\`, or \`run\`

View File

@@ -5,6 +5,7 @@ import { parseOpenClawResponse } from "./parse.js";
export type OpenClawTransport = "sse" | "webhook"; export type OpenClawTransport = "sse" | "webhook";
export type SessionKeyStrategy = "fixed" | "issue" | "run"; export type SessionKeyStrategy = "fixed" | "issue" | "run";
export type OpenClawEndpointKind = "open_responses" | "hook_wake" | "hook_agent" | "generic";
export type WakePayload = { export type WakePayload = {
runId: string; runId: string;
@@ -31,7 +32,7 @@ export type OpenClawExecutionState = {
}; };
const SENSITIVE_LOG_KEY_PATTERN = const SENSITIVE_LOG_KEY_PATTERN =
/(^|[_-])(auth|authorization|token|secret|password|api[_-]?key|private[_-]?key)([_-]|$)|^x-openclaw-auth$/i; /(^|[_-])(auth|authorization|token|secret|password|api[_-]?key|private[_-]?key)([_-]|$)|^x-openclaw-(auth|token)$/i;
export function nonEmpty(value: unknown): string | null { export function nonEmpty(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
@@ -73,11 +74,54 @@ export function resolveSessionKey(input: {
return fallback; return fallback;
} }
function normalizeUrlPath(pathname: string): string {
const trimmed = pathname.trim().toLowerCase();
if (!trimmed) return "/";
return trimmed.endsWith("/") && trimmed !== "/" ? trimmed.slice(0, -1) : trimmed;
}
function isWakePath(pathname: string): boolean {
const normalized = normalizeUrlPath(pathname);
return normalized === "/hooks/wake" || normalized.endsWith("/hooks/wake");
}
function isHookAgentPath(pathname: string): boolean {
const normalized = normalizeUrlPath(pathname);
return normalized === "/hooks/agent" || normalized.endsWith("/hooks/agent");
}
function isHookPath(pathname: string): boolean {
const normalized = normalizeUrlPath(pathname);
return (
normalized === "/hooks" ||
normalized.startsWith("/hooks/") ||
normalized.endsWith("/hooks") ||
normalized.includes("/hooks/")
);
}
export function isHookEndpoint(url: string): boolean {
try {
const parsed = new URL(url);
return isHookPath(parsed.pathname);
} catch {
return false;
}
}
export function isWakeCompatibilityEndpoint(url: string): boolean { export function isWakeCompatibilityEndpoint(url: string): boolean {
try { try {
const parsed = new URL(url); const parsed = new URL(url);
const path = parsed.pathname.toLowerCase(); return isWakePath(parsed.pathname);
return path === "/hooks/wake" || path.endsWith("/hooks/wake"); } catch {
return false;
}
}
export function isHookAgentEndpoint(url: string): boolean {
try {
const parsed = new URL(url);
return isHookAgentPath(parsed.pathname);
} catch { } catch {
return false; return false;
} }
@@ -86,13 +130,38 @@ export function isWakeCompatibilityEndpoint(url: string): boolean {
export function isOpenResponsesEndpoint(url: string): boolean { export function isOpenResponsesEndpoint(url: string): boolean {
try { try {
const parsed = new URL(url); const parsed = new URL(url);
const path = parsed.pathname.toLowerCase(); const path = normalizeUrlPath(parsed.pathname);
return path === "/v1/responses" || path.endsWith("/v1/responses"); return path === "/v1/responses" || path.endsWith("/v1/responses");
} catch { } catch {
return false; return false;
} }
} }
export function resolveEndpointKind(url: string): OpenClawEndpointKind {
if (isOpenResponsesEndpoint(url)) return "open_responses";
if (isWakeCompatibilityEndpoint(url)) return "hook_wake";
if (isHookAgentEndpoint(url)) return "hook_agent";
return "generic";
}
export function deriveHookAgentUrlFromResponses(url: string): string | null {
try {
const parsed = new URL(url);
const path = normalizeUrlPath(parsed.pathname);
if (path === "/v1/responses") {
parsed.pathname = "/hooks/agent";
return parsed.toString();
}
if (path.endsWith("/v1/responses")) {
parsed.pathname = `${path.slice(0, -"/v1/responses".length)}/hooks/agent`;
return parsed.toString();
}
return null;
} catch {
return null;
}
}
export function toStringRecord(value: unknown): Record<string, string> { export function toStringRecord(value: unknown): Record<string, string> {
const parsed = parseObject(value); const parsed = parseObject(value);
const out: Record<string, string> = {}; const out: Record<string, string> = {};
@@ -306,6 +375,41 @@ export function isTextRequiredResponse(responseText: string): boolean {
return responseText.toLowerCase().includes("text required"); return responseText.toLowerCase().includes("text required");
} }
function extractResponseErrorMessage(responseText: string): string {
const parsed = parseOpenClawResponse(responseText);
if (!parsed) return responseText;
const directError = parsed.error;
if (typeof directError === "string") return directError;
if (directError && typeof directError === "object") {
const nestedMessage = (directError as Record<string, unknown>).message;
if (typeof nestedMessage === "string") return nestedMessage;
}
const directMessage = parsed.message;
if (typeof directMessage === "string") return directMessage;
return responseText;
}
export function isWakeCompatibilityRetryableResponse(responseText: string): boolean {
if (isTextRequiredResponse(responseText)) return true;
const normalized = extractResponseErrorMessage(responseText).toLowerCase();
const expectsStringInput =
normalized.includes("invalid input") &&
normalized.includes("expected string") &&
normalized.includes("undefined");
if (expectsStringInput) return true;
const missingInputField =
normalized.includes("input") &&
(normalized.includes("required") || normalized.includes("missing"));
if (missingInputField) return true;
return false;
}
export async function sendJsonRequest(params: { export async function sendJsonRequest(params: {
url: string; url: string;
method: string; method: string;
@@ -355,7 +459,12 @@ export function buildExecutionState(ctx: AdapterExecutionContext): OpenClawExecu
} }
} }
const openClawAuthHeader = nonEmpty(headers["x-openclaw-auth"] ?? headers["X-OpenClaw-Auth"]); const openClawAuthHeader = nonEmpty(
headers["x-openclaw-token"] ??
headers["X-OpenClaw-Token"] ??
headers["x-openclaw-auth"] ??
headers["X-OpenClaw-Auth"],
);
if (openClawAuthHeader && !headers.authorization && !headers.Authorization) { if (openClawAuthHeader && !headers.authorization && !headers.Authorization) {
headers.authorization = toAuthorizationHeaderValue(openClawAuthHeader); headers.authorization = toAuthorizationHeaderValue(openClawAuthHeader);
} }

View File

@@ -1,14 +1,19 @@
import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils"; import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils";
import { import {
appendWakeText, appendWakeText,
appendWakeTextToOpenResponsesInput,
buildExecutionState, buildExecutionState,
buildWakeCompatibilityPayload, buildWakeCompatibilityPayload,
deriveHookAgentUrlFromResponses,
isTextRequiredResponse, isTextRequiredResponse,
isWakeCompatibilityEndpoint, isWakeCompatibilityRetryableResponse,
readAndLogResponseText, readAndLogResponseText,
redactForLog, redactForLog,
resolveEndpointKind,
sendJsonRequest, sendJsonRequest,
stringifyForLog, stringifyForLog,
toStringRecord,
type OpenClawEndpointKind,
type OpenClawExecutionState, type OpenClawExecutionState,
} from "./execute-common.js"; } from "./execute-common.js";
import { parseOpenClawResponse } from "./parse.js"; import { parseOpenClawResponse } from "./parse.js";
@@ -17,14 +22,132 @@ function nonEmpty(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
} }
function buildWebhookBody(input: { function asBooleanFlag(value: unknown, fallback = false): boolean {
if (typeof value === "boolean") return value;
if (typeof value === "string") {
const normalized = value.trim().toLowerCase();
if (normalized === "true" || normalized === "1") return true;
if (normalized === "false" || normalized === "0") return false;
}
return fallback;
}
function normalizeWakeMode(value: unknown): "now" | "next-heartbeat" | null {
if (typeof value !== "string") return null;
const normalized = value.trim().toLowerCase();
if (normalized === "now" || normalized === "next-heartbeat") return normalized;
return null;
}
function parseOptionalPositiveInteger(value: unknown): number | null {
if (typeof value === "number" && Number.isFinite(value)) {
const normalized = Math.max(1, Math.floor(value));
return Number.isFinite(normalized) ? normalized : null;
}
if (typeof value === "string" && value.trim().length > 0) {
const parsed = Number.parseInt(value.trim(), 10);
if (Number.isFinite(parsed)) {
const normalized = Math.max(1, Math.floor(parsed));
return Number.isFinite(normalized) ? normalized : null;
}
}
return null;
}
function buildOpenResponsesWebhookBody(input: {
state: OpenClawExecutionState;
configModel: unknown;
}): Record<string, unknown> {
const { state, configModel } = input;
const templateText = nonEmpty(state.payloadTemplate.text);
const payloadText = templateText ? appendWakeText(templateText, state.wakeText) : state.wakeText;
const openResponsesInput = Object.prototype.hasOwnProperty.call(state.payloadTemplate, "input")
? appendWakeTextToOpenResponsesInput(state.payloadTemplate.input, state.wakeText)
: payloadText;
return {
...state.payloadTemplate,
stream: false,
model:
nonEmpty(state.payloadTemplate.model) ??
nonEmpty(configModel) ??
"openclaw",
input: openResponsesInput,
metadata: {
...toStringRecord(state.payloadTemplate.metadata),
...state.paperclipEnv,
paperclip_session_key: state.sessionKey,
paperclip_stream_transport: "webhook",
},
};
}
function buildHookWakeBody(state: OpenClawExecutionState): Record<string, unknown> {
const templateText = nonEmpty(state.payloadTemplate.text) ?? nonEmpty(state.payloadTemplate.message);
const payloadText = templateText ? appendWakeText(templateText, state.wakeText) : state.wakeText;
const wakeMode = normalizeWakeMode(state.payloadTemplate.mode ?? state.payloadTemplate.wakeMode) ?? "now";
return {
text: payloadText,
mode: wakeMode,
};
}
function buildHookAgentBody(input: {
state: OpenClawExecutionState;
includeSessionKey: boolean;
}): Record<string, unknown> {
const { state, includeSessionKey } = input;
const templateMessage = nonEmpty(state.payloadTemplate.message) ?? nonEmpty(state.payloadTemplate.text);
const message = templateMessage ? appendWakeText(templateMessage, state.wakeText) : state.wakeText;
const payload: Record<string, unknown> = {
message,
};
const name = nonEmpty(state.payloadTemplate.name);
if (name) payload.name = name;
const agentId = nonEmpty(state.payloadTemplate.agentId);
if (agentId) payload.agentId = agentId;
const wakeMode = normalizeWakeMode(state.payloadTemplate.wakeMode ?? state.payloadTemplate.mode);
if (wakeMode) payload.wakeMode = wakeMode;
const deliver = state.payloadTemplate.deliver;
if (typeof deliver === "boolean") payload.deliver = deliver;
const channel = nonEmpty(state.payloadTemplate.channel);
if (channel) payload.channel = channel;
const to = nonEmpty(state.payloadTemplate.to);
if (to) payload.to = to;
const model = nonEmpty(state.payloadTemplate.model);
if (model) payload.model = model;
const thinking = nonEmpty(state.payloadTemplate.thinking);
if (thinking) payload.thinking = thinking;
const timeoutSeconds = parseOptionalPositiveInteger(state.payloadTemplate.timeoutSeconds);
if (timeoutSeconds != null) payload.timeoutSeconds = timeoutSeconds;
const explicitSessionKey = nonEmpty(state.payloadTemplate.sessionKey);
if (explicitSessionKey) {
payload.sessionKey = explicitSessionKey;
} else if (includeSessionKey) {
payload.sessionKey = state.sessionKey;
}
return payload;
}
function buildLegacyWebhookBody(input: {
state: OpenClawExecutionState; state: OpenClawExecutionState;
context: AdapterExecutionContext["context"]; context: AdapterExecutionContext["context"];
}): Record<string, unknown> { }): Record<string, unknown> {
const { state, context } = input; const { state, context } = input;
const templateText = nonEmpty(state.payloadTemplate.text); const templateText = nonEmpty(state.payloadTemplate.text);
const payloadText = templateText ? appendWakeText(templateText, state.wakeText) : state.wakeText; const payloadText = templateText ? appendWakeText(templateText, state.wakeText) : state.wakeText;
return { return {
...state.payloadTemplate, ...state.payloadTemplate,
stream: false, stream: false,
@@ -40,6 +163,27 @@ function buildWebhookBody(input: {
}; };
} }
function buildWebhookBody(input: {
endpointKind: OpenClawEndpointKind;
state: OpenClawExecutionState;
context: AdapterExecutionContext["context"];
configModel: unknown;
includeHookSessionKey: boolean;
}): Record<string, unknown> {
const { endpointKind, state, context, configModel, includeHookSessionKey } = input;
if (endpointKind === "open_responses") {
return buildOpenResponsesWebhookBody({ state, configModel });
}
if (endpointKind === "hook_wake") {
return buildHookWakeBody(state);
}
if (endpointKind === "hook_agent") {
return buildHookAgentBody({ state, includeSessionKey: includeHookSessionKey });
}
return buildLegacyWebhookBody({ state, context });
}
async function sendWebhookRequest(params: { async function sendWebhookRequest(params: {
url: string; url: string;
method: string; method: string;
@@ -63,21 +207,50 @@ async function sendWebhookRequest(params: {
export async function executeWebhook(ctx: AdapterExecutionContext, url: string): Promise<AdapterExecutionResult> { export async function executeWebhook(ctx: AdapterExecutionContext, url: string): Promise<AdapterExecutionResult> {
const { onLog, onMeta, context } = ctx; const { onLog, onMeta, context } = ctx;
const state = buildExecutionState(ctx); const state = buildExecutionState(ctx);
const originalUrl = url;
const originalEndpointKind = resolveEndpointKind(originalUrl);
let targetUrl = originalUrl;
let endpointKind = resolveEndpointKind(targetUrl);
const remappedFromResponses = originalEndpointKind === "open_responses";
// In webhook mode, /v1/responses is legacy wiring. Prefer hooks/agent.
if (remappedFromResponses) {
const rewritten = deriveHookAgentUrlFromResponses(targetUrl);
if (rewritten) {
await onLog(
"stdout",
`[openclaw] webhook transport selected; remapping ${targetUrl} -> ${rewritten}\n`,
);
targetUrl = rewritten;
endpointKind = resolveEndpointKind(targetUrl);
}
}
const headers = { ...state.headers };
if (endpointKind === "open_responses" && !headers["x-openclaw-session-key"] && !headers["X-OpenClaw-Session-Key"]) {
headers["x-openclaw-session-key"] = state.sessionKey;
}
if (onMeta) { if (onMeta) {
await onMeta({ await onMeta({
adapterType: "openclaw", adapterType: "openclaw",
command: "webhook", command: "webhook",
commandArgs: [state.method, url], commandArgs: [state.method, targetUrl],
context, context,
}); });
} }
const headers = { ...state.headers }; const includeHookSessionKey = asBooleanFlag(ctx.config.hookIncludeSessionKey, false);
const webhookBody = buildWebhookBody({ state, context }); const webhookBody = buildWebhookBody({
endpointKind,
state,
context,
configModel: ctx.config.model,
includeHookSessionKey,
});
const wakeCompatibilityBody = buildWakeCompatibilityPayload(state.wakeText); const wakeCompatibilityBody = buildWakeCompatibilityPayload(state.wakeText);
const preferWakeCompatibilityBody = isWakeCompatibilityEndpoint(url); const preferWakeCompatibilityBody = endpointKind === "hook_wake";
const initialBody = preferWakeCompatibilityBody ? wakeCompatibilityBody : webhookBody; const initialBody = webhookBody;
const outboundHeaderKeys = Object.keys(headers).sort(); const outboundHeaderKeys = Object.keys(headers).sort();
await onLog( await onLog(
@@ -89,10 +262,10 @@ export async function executeWebhook(ctx: AdapterExecutionContext, url: string):
`[openclaw] outbound payload (redacted): ${stringifyForLog(redactForLog(initialBody), 12_000)}\n`, `[openclaw] outbound payload (redacted): ${stringifyForLog(redactForLog(initialBody), 12_000)}\n`,
); );
await onLog("stdout", `[openclaw] outbound header keys: ${outboundHeaderKeys.join(", ")}\n`); await onLog("stdout", `[openclaw] outbound header keys: ${outboundHeaderKeys.join(", ")}\n`);
await onLog("stdout", `[openclaw] invoking ${state.method} ${url} (transport=webhook)\n`); await onLog("stdout", `[openclaw] invoking ${state.method} ${targetUrl} (transport=webhook kind=${endpointKind})\n`);
if (preferWakeCompatibilityBody) { if (preferWakeCompatibilityBody) {
await onLog("stdout", "[openclaw] using wake text payload for /hooks/wake compatibility\n"); await onLog("stdout", "[openclaw] using webhook wake payload for /hooks/wake\n");
} }
const controller = new AbortController(); const controller = new AbortController();
@@ -100,7 +273,7 @@ export async function executeWebhook(ctx: AdapterExecutionContext, url: string):
try { try {
const initialResponse = await sendWebhookRequest({ const initialResponse = await sendWebhookRequest({
url, url: targetUrl,
method: state.method, method: state.method,
headers, headers,
payload: initialBody, payload: initialBody,
@@ -108,9 +281,70 @@ export async function executeWebhook(ctx: AdapterExecutionContext, url: string):
signal: controller.signal, signal: controller.signal,
}); });
if (!initialResponse.response.ok) { let activeResponse = initialResponse;
let activeEndpointKind = endpointKind;
let activeUrl = targetUrl;
let activeHeaders = headers;
let usedLegacyResponsesFallback = false;
if (
remappedFromResponses &&
targetUrl !== originalUrl &&
initialResponse.response.status === 404
) {
await onLog(
"stdout",
`[openclaw] remapped hook endpoint returned 404; retrying legacy endpoint ${originalUrl}\n`,
);
activeEndpointKind = originalEndpointKind;
activeUrl = originalUrl;
usedLegacyResponsesFallback = true;
const fallbackHeaders = { ...state.headers };
if (
activeEndpointKind === "open_responses" &&
!fallbackHeaders["x-openclaw-session-key"] &&
!fallbackHeaders["X-OpenClaw-Session-Key"]
) {
fallbackHeaders["x-openclaw-session-key"] = state.sessionKey;
}
const fallbackBody = buildWebhookBody({
endpointKind: activeEndpointKind,
state,
context,
configModel: ctx.config.model,
includeHookSessionKey,
});
await onLog(
"stdout",
`[openclaw] fallback headers (redacted): ${stringifyForLog(redactForLog(fallbackHeaders), 4_000)}\n`,
);
await onLog(
"stdout",
`[openclaw] fallback payload (redacted): ${stringifyForLog(redactForLog(fallbackBody), 12_000)}\n`,
);
await onLog(
"stdout",
`[openclaw] invoking fallback ${state.method} ${activeUrl} (transport=webhook kind=${activeEndpointKind})\n`,
);
activeResponse = await sendWebhookRequest({
url: activeUrl,
method: state.method,
headers: fallbackHeaders,
payload: fallbackBody,
onLog,
signal: controller.signal,
});
activeHeaders = fallbackHeaders;
}
if (!activeResponse.response.ok) {
const canRetryWithWakeCompatibility = const canRetryWithWakeCompatibility =
!preferWakeCompatibilityBody && isTextRequiredResponse(initialResponse.responseText); (activeEndpointKind === "open_responses" || activeEndpointKind === "generic") &&
isWakeCompatibilityRetryableResponse(activeResponse.responseText);
if (canRetryWithWakeCompatibility) { if (canRetryWithWakeCompatibility) {
await onLog( await onLog(
@@ -119,9 +353,9 @@ export async function executeWebhook(ctx: AdapterExecutionContext, url: string):
); );
const retryResponse = await sendWebhookRequest({ const retryResponse = await sendWebhookRequest({
url, url: activeUrl,
method: state.method, method: state.method,
headers, headers: activeHeaders,
payload: wakeCompatibilityBody, payload: wakeCompatibilityBody,
onLog, onLog,
signal: controller.signal, signal: controller.signal,
@@ -134,11 +368,12 @@ export async function executeWebhook(ctx: AdapterExecutionContext, url: string):
timedOut: false, timedOut: false,
provider: "openclaw", provider: "openclaw",
model: null, model: null,
summary: `OpenClaw webhook ${state.method} ${url} (wake compatibility)`, summary: `OpenClaw webhook ${state.method} ${activeUrl} (wake compatibility)`,
resultJson: { resultJson: {
status: retryResponse.response.status, status: retryResponse.response.status,
statusText: retryResponse.response.statusText, statusText: retryResponse.response.statusText,
compatibilityMode: "wake_text", compatibilityMode: "wake_text",
usedLegacyResponsesFallback,
response: parseOpenClawResponse(retryResponse.responseText) ?? retryResponse.responseText, response: parseOpenClawResponse(retryResponse.responseText) ?? retryResponse.responseText,
}, },
}; };
@@ -169,16 +404,16 @@ export async function executeWebhook(ctx: AdapterExecutionContext, url: string):
signal: null, signal: null,
timedOut: false, timedOut: false,
errorMessage: errorMessage:
isTextRequiredResponse(initialResponse.responseText) isTextRequiredResponse(activeResponse.responseText)
? "OpenClaw endpoint rejected the payload as text-required." ? "OpenClaw endpoint rejected the payload as text-required."
: `OpenClaw webhook failed with status ${initialResponse.response.status}`, : `OpenClaw webhook failed with status ${activeResponse.response.status}`,
errorCode: isTextRequiredResponse(initialResponse.responseText) errorCode: isTextRequiredResponse(activeResponse.responseText)
? "openclaw_text_required" ? "openclaw_text_required"
: "openclaw_http_error", : "openclaw_http_error",
resultJson: { resultJson: {
status: initialResponse.response.status, status: activeResponse.response.status,
statusText: initialResponse.response.statusText, statusText: activeResponse.response.statusText,
response: parseOpenClawResponse(initialResponse.responseText) ?? initialResponse.responseText, response: parseOpenClawResponse(activeResponse.responseText) ?? activeResponse.responseText,
}, },
}; };
} }
@@ -189,11 +424,12 @@ export async function executeWebhook(ctx: AdapterExecutionContext, url: string):
timedOut: false, timedOut: false,
provider: "openclaw", provider: "openclaw",
model: null, model: null,
summary: `OpenClaw webhook ${state.method} ${url}`, summary: `OpenClaw webhook ${state.method} ${activeUrl}`,
resultJson: { resultJson: {
status: initialResponse.response.status, status: activeResponse.response.status,
statusText: initialResponse.response.statusText, statusText: activeResponse.response.statusText,
response: parseOpenClawResponse(initialResponse.responseText) ?? initialResponse.responseText, usedLegacyResponsesFallback,
response: parseOpenClawResponse(activeResponse.responseText) ?? activeResponse.responseText,
}, },
}; };
} catch (err) { } catch (err) {

View File

@@ -1,6 +1,6 @@
import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils"; import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils";
import { asString } from "@paperclipai/adapter-utils/server-utils"; import { asString } from "@paperclipai/adapter-utils/server-utils";
import { isWakeCompatibilityEndpoint } from "./execute-common.js"; import { isHookEndpoint } from "./execute-common.js";
import { executeSse } from "./execute-sse.js"; import { executeSse } from "./execute-sse.js";
import { executeWebhook } from "./execute-webhook.js"; import { executeWebhook } from "./execute-webhook.js";
@@ -35,12 +35,12 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
}; };
} }
if (transport === "sse" && isWakeCompatibilityEndpoint(url)) { if (transport === "sse" && isHookEndpoint(url)) {
return { return {
exitCode: 1, exitCode: 1,
signal: null, signal: null,
timedOut: false, timedOut: false,
errorMessage: "OpenClaw /hooks/wake is not stream-capable. Use SSE transport with a streaming endpoint.", errorMessage: "OpenClaw /hooks/* endpoints are not stream-capable. Use webhook transport for hooks.",
errorCode: "openclaw_sse_incompatible_endpoint", errorCode: "openclaw_sse_incompatible_endpoint",
}; };
} }

View File

@@ -34,6 +34,16 @@ function isWakePath(pathname: string): boolean {
return value === "/hooks/wake" || value.endsWith("/hooks/wake"); return value === "/hooks/wake" || value.endsWith("/hooks/wake");
} }
function isHooksPath(pathname: string): boolean {
const value = pathname.trim().toLowerCase();
return (
value === "/hooks" ||
value.startsWith("/hooks/") ||
value.endsWith("/hooks") ||
value.includes("/hooks/")
);
}
function normalizeTransport(value: unknown): "sse" | "webhook" | null { function normalizeTransport(value: unknown): "sse" | "webhook" | null {
const normalized = asString(value, "sse").trim().toLowerCase(); const normalized = asString(value, "sse").trim().toLowerCase();
if (!normalized || normalized === "sse") return "sse"; if (!normalized || normalized === "sse") return "sse";
@@ -163,12 +173,12 @@ export async function testEnvironment(
}); });
} }
if (streamTransport === "sse" && isWakePath(url.pathname)) { if (streamTransport === "sse" && (isWakePath(url.pathname) || isHooksPath(url.pathname))) {
checks.push({ checks.push({
code: "openclaw_wake_endpoint_incompatible", code: "openclaw_wake_endpoint_incompatible",
level: "error", level: "error",
message: "Endpoint targets /hooks/wake, which is not stream-capable for SSE transport.", message: "Endpoint targets /hooks/*, which is not stream-capable for SSE transport.",
hint: "Use an endpoint that returns text/event-stream for the full run duration.", hint: "Use webhook transport for /hooks/* endpoints.",
}); });
} }
} }

View File

@@ -28,6 +28,36 @@ set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CLI_DIR="$REPO_ROOT/cli" CLI_DIR="$REPO_ROOT/cli"
# ── Helper: create GitHub Release ────────────────────────────────────────────
create_github_release() {
local version="$1"
local is_dry_run="$2"
local release_notes="$REPO_ROOT/releases/v${version}.md"
if [ "$is_dry_run" = true ]; then
echo " [dry-run] gh release create v$version"
return
fi
if ! command -v gh &>/dev/null; then
echo " ⚠ gh CLI not found — skipping GitHub Release"
return
fi
local gh_args=(gh release create "v$version" --title "v$version")
if [ -f "$release_notes" ]; then
gh_args+=(--notes-file "$release_notes")
else
gh_args+=(--generate-notes)
fi
if "${gh_args[@]}"; then
echo " ✓ Created GitHub Release v$version"
else
echo " ⚠ GitHub Release creation failed (non-fatal)"
fi
}
# ── Parse args ──────────────────────────────────────────────────────────────── # ── Parse args ────────────────────────────────────────────────────────────────
dry_run=false dry_run=false
@@ -141,11 +171,14 @@ console.log(names.join('\n'));
echo " ✓ Committed and tagged v$NEW_VERSION" echo " ✓ Committed and tagged v$NEW_VERSION"
fi fi
create_github_release "$NEW_VERSION" "$dry_run"
echo "" echo ""
if [ "$dry_run" = true ]; then if [ "$dry_run" = true ]; then
echo "Dry run complete for promote v$NEW_VERSION." echo "Dry run complete for promote v$NEW_VERSION."
echo " - Would promote all packages to @latest" echo " - Would promote all packages to @latest"
echo " - Would commit and tag v$NEW_VERSION" echo " - Would commit and tag v$NEW_VERSION"
echo " - Would create GitHub Release"
else else
echo "Promoted all packages to @latest at v$NEW_VERSION" echo "Promoted all packages to @latest at v$NEW_VERSION"
echo "" echo ""
@@ -346,6 +379,10 @@ if [ "$canary" = false ]; then
echo " ✓ Committed and tagged v$NEW_VERSION" echo " ✓ Committed and tagged v$NEW_VERSION"
fi fi
if [ "$canary" = false ]; then
create_github_release "$NEW_VERSION" "$dry_run"
fi
# ── Done ────────────────────────────────────────────────────────────────────── # ── Done ──────────────────────────────────────────────────────────────────────
echo "" echo ""
@@ -371,6 +408,7 @@ elif [ "$dry_run" = true ]; then
echo " - Versions bumped, built, and previewed" echo " - Versions bumped, built, and previewed"
echo " - Dev package.json restored" echo " - Dev package.json restored"
echo " - Commit and tag created (locally)" echo " - Commit and tag created (locally)"
echo " - Would create GitHub Release"
echo "" echo ""
echo "To actually publish, run:" echo "To actually publish, run:"
echo " ./scripts/release.sh $bump_type" echo " ./scripts/release.sh $bump_type"
@@ -379,4 +417,6 @@ else
echo "" echo ""
echo "To push:" echo "To push:"
echo " git push && git push origin v$NEW_VERSION" echo " git push && git push origin v$NEW_VERSION"
echo ""
echo "GitHub Release: https://github.com/cryppadotta/paperclip/releases/tag/v$NEW_VERSION"
fi fi

View File

@@ -90,6 +90,41 @@ describe("buildJoinDefaultsPayloadForAccept", () => {
}); });
}); });
it("accepts auth from agentDefaultsPayload.headers.x-openclaw-token", () => {
const result = buildJoinDefaultsPayloadForAccept({
adapterType: "openclaw",
defaultsPayload: {
url: "http://127.0.0.1:18789/hooks/agent",
method: "POST",
headers: {
"x-openclaw-token": "gateway-token",
},
},
}) as Record<string, unknown>;
expect(result).toMatchObject({
headers: {
"x-openclaw-token": "gateway-token",
},
webhookAuthHeader: "Bearer gateway-token",
});
});
it("accepts inbound x-openclaw-token compatibility header", () => {
const result = buildJoinDefaultsPayloadForAccept({
adapterType: "openclaw",
defaultsPayload: null,
inboundOpenClawTokenHeader: "gateway-token",
}) as Record<string, unknown>;
expect(result).toMatchObject({
headers: {
"x-openclaw-token": "gateway-token",
},
webhookAuthHeader: "Bearer gateway-token",
});
});
it("accepts wrapped auth values in headers for compatibility", () => { it("accepts wrapped auth values in headers for compatibility", () => {
const result = buildJoinDefaultsPayloadForAccept({ const result = buildJoinDefaultsPayloadForAccept({
adapterType: "openclaw", adapterType: "openclaw",

View File

@@ -332,6 +332,31 @@ describe("openclaw adapter execute", () => {
expect(headers.authorization).toBe("Bearer gateway-token"); expect(headers.authorization).toBe("Bearer gateway-token");
}); });
it("derives Authorization header from x-openclaw-token when webhookAuthHeader is unset", async () => {
const fetchMock = vi.fn().mockResolvedValue(
sseResponse([
"event: response.completed\n",
'data: {"type":"response.completed","status":"completed"}\n\n',
]),
);
vi.stubGlobal("fetch", fetchMock);
const result = await execute(
buildContext({
url: "https://agent.example/sse",
method: "POST",
headers: {
"x-openclaw-token": "gateway-token",
},
}),
);
expect(result.exitCode).toBe(0);
const headers = (fetchMock.mock.calls[0]?.[1]?.headers ?? {}) as Record<string, string>;
expect(headers["x-openclaw-token"]).toBe("gateway-token");
expect(headers.authorization).toBe("Bearer gateway-token");
});
it("derives issue session keys when configured", async () => { it("derives issue session keys when configured", async () => {
const fetchMock = vi.fn().mockResolvedValue( const fetchMock = vi.fn().mockResolvedValue(
sseResponse([ sseResponse([
@@ -564,6 +589,93 @@ describe("openclaw adapter execute", () => {
expect((body.paperclip as Record<string, unknown>).streamTransport).toBe("webhook"); expect((body.paperclip as Record<string, unknown>).streamTransport).toBe("webhook");
}); });
it("remaps legacy /v1/responses URLs to /hooks/agent in webhook transport", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ ok: true }), {
status: 200,
statusText: "OK",
headers: {
"content-type": "application/json",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const result = await execute(
buildContext({
url: "https://agent.example/v1/responses",
streamTransport: "webhook",
payloadTemplate: { foo: "bar" },
}),
);
expect(result.exitCode).toBe(0);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(String(fetchMock.mock.calls[0]?.[0] ?? "")).toBe("https://agent.example/hooks/agent");
const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body ?? "{}")) as Record<string, unknown>;
expect(typeof body.message).toBe("string");
expect(String(body.message ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
expect(body.stream).toBeUndefined();
expect(body.input).toBeUndefined();
expect(body.metadata).toBeUndefined();
expect(body.paperclip).toBeUndefined();
const headers = (fetchMock.mock.calls[0]?.[1]?.headers ?? {}) as Record<string, string>;
expect(headers["x-openclaw-session-key"]).toBeUndefined();
});
it("falls back to legacy /v1/responses when remapped /hooks/agent returns 404", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
new Response("Not Found", {
status: 404,
statusText: "Not Found",
headers: {
"content-type": "text/plain",
},
}),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ ok: true }), {
status: 200,
statusText: "OK",
headers: {
"content-type": "application/json",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const result = await execute(
buildContext({
url: "https://agent.example/v1/responses",
streamTransport: "webhook",
}),
);
expect(result.exitCode).toBe(0);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(String(fetchMock.mock.calls[0]?.[0] ?? "")).toBe("https://agent.example/hooks/agent");
expect(String(fetchMock.mock.calls[1]?.[0] ?? "")).toBe("https://agent.example/v1/responses");
const firstBody = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body ?? "{}")) as Record<string, unknown>;
expect(typeof firstBody.message).toBe("string");
expect(String(firstBody.message ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
const secondBody = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body ?? "{}")) as Record<string, unknown>;
expect(secondBody.stream).toBe(false);
expect(typeof secondBody.input).toBe("string");
expect(String(secondBody.input ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
const secondHeaders = (fetchMock.mock.calls[1]?.[1]?.headers ?? {}) as Record<string, string>;
expect(secondHeaders["x-openclaw-session-key"]).toBe("paperclip");
expect(result.resultJson).toEqual(
expect.objectContaining({
usedLegacyResponsesFallback: true,
}),
);
});
it("uses wake compatibility payloads for /hooks/wake when transport=webhook", async () => { it("uses wake compatibility payloads for /hooks/wake when transport=webhook", async () => {
const fetchMock = vi.fn().mockResolvedValue( const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ ok: true }), { new Response(JSON.stringify({ ok: true }), {
@@ -590,6 +702,73 @@ describe("openclaw adapter execute", () => {
expect(body.paperclip).toBeUndefined(); expect(body.paperclip).toBeUndefined();
}); });
it("uses /hooks/agent payloads for webhook transport and omits sessionKey by default", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ ok: true }), {
status: 200,
statusText: "OK",
headers: {
"content-type": "application/json",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const result = await execute(
buildContext({
url: "https://agent.example/hooks/agent",
streamTransport: "webhook",
payloadTemplate: {
name: "Paperclip Hook",
wakeMode: "next-heartbeat",
deliver: true,
channel: "last",
model: "openai/gpt-5.2-mini",
},
}),
);
expect(result.exitCode).toBe(0);
expect(fetchMock).toHaveBeenCalledTimes(1);
const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body ?? "{}")) as Record<string, unknown>;
expect(typeof body.message).toBe("string");
expect(String(body.message)).toContain("PAPERCLIP_RUN_ID=run-123");
expect(body.name).toBe("Paperclip Hook");
expect(body.wakeMode).toBe("next-heartbeat");
expect(body.deliver).toBe(true);
expect(body.channel).toBe("last");
expect(body.model).toBe("openai/gpt-5.2-mini");
expect(body.sessionKey).toBeUndefined();
expect(body.text).toBeUndefined();
expect(body.paperclip).toBeUndefined();
});
it("includes sessionKey for /hooks/agent payloads only when hookIncludeSessionKey=true", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ ok: true }), {
status: 200,
statusText: "OK",
headers: {
"content-type": "application/json",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const result = await execute(
buildContext({
url: "https://agent.example/hooks/agent",
streamTransport: "webhook",
hookIncludeSessionKey: true,
}),
);
expect(result.exitCode).toBe(0);
expect(fetchMock).toHaveBeenCalledTimes(1);
const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body ?? "{}")) as Record<string, unknown>;
expect(body.sessionKey).toBe("paperclip");
});
it("retries webhook payloads with wake compatibility format on text-required errors", async () => { it("retries webhook payloads with wake compatibility format on text-required errors", async () => {
const fetchMock = vi const fetchMock = vi
.fn() .fn()
@@ -615,7 +794,7 @@ describe("openclaw adapter execute", () => {
const result = await execute( const result = await execute(
buildContext({ buildContext({
url: "https://agent.example/v1/responses", url: "https://agent.example/webhook",
streamTransport: "webhook", streamTransport: "webhook",
}), }),
); );
@@ -624,11 +803,57 @@ describe("openclaw adapter execute", () => {
expect(fetchMock).toHaveBeenCalledTimes(2); expect(fetchMock).toHaveBeenCalledTimes(2);
const firstBody = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body ?? "{}")) as Record<string, unknown>; const firstBody = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body ?? "{}")) as Record<string, unknown>;
const secondBody = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body ?? "{}")) as Record<string, unknown>; const secondBody = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body ?? "{}")) as Record<string, unknown>;
expect(String(firstBody.text ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
expect(firstBody.paperclip).toBeTypeOf("object"); expect(firstBody.paperclip).toBeTypeOf("object");
expect(secondBody.mode).toBe("now"); expect(secondBody.mode).toBe("now");
expect(String(secondBody.text ?? "")).toContain("PAPERCLIP_RUN_ID=run-123"); expect(String(secondBody.text ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
}); });
it("retries webhook payloads when /v1/responses reports missing string input", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
new Response(
JSON.stringify({
error: {
message: "model: Invalid input: expected string, received undefined",
type: "invalid_request_error",
},
}),
{
status: 400,
statusText: "Bad Request",
headers: {
"content-type": "application/json",
},
},
),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ ok: true }), {
status: 200,
statusText: "OK",
headers: {
"content-type": "application/json",
},
}),
);
vi.stubGlobal("fetch", fetchMock);
const result = await execute(
buildContext({
url: "https://agent.example/webhook",
streamTransport: "webhook",
}),
);
expect(result.exitCode).toBe(0);
expect(fetchMock).toHaveBeenCalledTimes(2);
const secondBody = JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body ?? "{}")) as Record<string, unknown>;
expect(secondBody.mode).toBe("now");
expect(String(secondBody.text ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
});
it("rejects unsupported transport configuration", async () => { it("rejects unsupported transport configuration", async () => {
const fetchMock = vi.fn(); const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock); vi.stubGlobal("fetch", fetchMock);
@@ -659,6 +884,21 @@ describe("openclaw adapter execute", () => {
expect(result.errorCode).toBe("openclaw_sse_incompatible_endpoint"); expect(result.errorCode).toBe("openclaw_sse_incompatible_endpoint");
expect(fetchMock).not.toHaveBeenCalled(); expect(fetchMock).not.toHaveBeenCalled();
}); });
it("rejects /hooks/agent endpoints in SSE mode", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const result = await execute(
buildContext({
url: "https://agent.example/hooks/agent",
}),
);
expect(result.exitCode).toBe(1);
expect(result.errorCode).toBe("openclaw_sse_incompatible_endpoint");
expect(fetchMock).not.toHaveBeenCalled();
});
}); });
describe("openclaw adapter environment checks", () => { describe("openclaw adapter environment checks", () => {
@@ -686,6 +926,24 @@ describe("openclaw adapter environment checks", () => {
expect(check?.level).toBe("error"); expect(check?.level).toBe("error");
}); });
it("reports /hooks/agent endpoints as incompatible for SSE mode", async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(new Response(null, { status: 405, statusText: "Method Not Allowed" }));
vi.stubGlobal("fetch", fetchMock);
const result = await testEnvironment({
companyId: "company-123",
adapterType: "openclaw",
config: {
url: "https://agent.example/hooks/agent",
},
});
const check = result.checks.find((entry) => entry.code === "openclaw_wake_endpoint_incompatible");
expect(check?.level).toBe("error");
});
it("reports unsupported streamTransport settings", async () => { it("reports unsupported streamTransport settings", async () => {
const fetchMock = vi const fetchMock = vi
.fn() .fn()

View File

@@ -320,6 +320,7 @@ export function buildJoinDefaultsPayloadForAccept(input: {
paperclipApiUrl?: unknown; paperclipApiUrl?: unknown;
webhookAuthHeader?: unknown; webhookAuthHeader?: unknown;
inboundOpenClawAuthHeader?: string | null; inboundOpenClawAuthHeader?: string | null;
inboundOpenClawTokenHeader?: string | null;
}): unknown { }): unknown {
if (input.adapterType !== "openclaw") { if (input.adapterType !== "openclaw") {
return input.defaultsPayload; return input.defaultsPayload;
@@ -367,6 +368,15 @@ export function buildJoinDefaultsPayloadForAccept(input: {
const inboundOpenClawAuthHeader = nonEmptyTrimmedString( const inboundOpenClawAuthHeader = nonEmptyTrimmedString(
input.inboundOpenClawAuthHeader input.inboundOpenClawAuthHeader
); );
const inboundOpenClawTokenHeader = nonEmptyTrimmedString(
input.inboundOpenClawTokenHeader
);
if (
inboundOpenClawTokenHeader &&
!headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-token")
) {
mergedHeaders["x-openclaw-token"] = inboundOpenClawTokenHeader;
}
if ( if (
inboundOpenClawAuthHeader && inboundOpenClawAuthHeader &&
!headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-auth") !headerMapHasKeyIgnoreCase(mergedHeaders, "x-openclaw-auth")
@@ -388,7 +398,9 @@ export function buildJoinDefaultsPayloadForAccept(input: {
nonEmptyTrimmedString(merged.webhookAuthHeader) nonEmptyTrimmedString(merged.webhookAuthHeader)
); );
if (!hasAuthorizationHeader && !hasWebhookAuthHeader) { if (!hasAuthorizationHeader && !hasWebhookAuthHeader) {
const openClawAuthToken = headerMapGetIgnoreCase( const openClawAuthToken =
headerMapGetIgnoreCase(mergedHeaders, "x-openclaw-token") ??
headerMapGetIgnoreCase(
mergedHeaders, mergedHeaders,
"x-openclaw-auth" "x-openclaw-auth"
); );
@@ -484,9 +496,8 @@ function summarizeOpenClawDefaultsForLog(defaultsPayload: unknown) {
: null; : null;
const headers = defaults ? normalizeHeaderMap(defaults.headers) : undefined; const headers = defaults ? normalizeHeaderMap(defaults.headers) : undefined;
const openClawAuthHeaderValue = headers const openClawAuthHeaderValue = headers
? Object.entries(headers).find( ? headerMapGetIgnoreCase(headers, "x-openclaw-token") ??
([key]) => key.trim().toLowerCase() === "x-openclaw-auth" headerMapGetIgnoreCase(headers, "x-openclaw-auth")
)?.[1] ?? null
: null; : null;
return { return {
@@ -703,20 +714,23 @@ function normalizeAgentDefaultsForJoin(input: {
} }
const openClawAuthHeader = headers const openClawAuthHeader = headers
? headerMapGetIgnoreCase(headers, "x-openclaw-auth") ? headerMapGetIgnoreCase(headers, "x-openclaw-token") ??
headerMapGetIgnoreCase(headers, "x-openclaw-auth")
: null; : null;
if (openClawAuthHeader) { if (openClawAuthHeader) {
diagnostics.push({ diagnostics.push({
code: "openclaw_auth_header_configured", code: "openclaw_auth_header_configured",
level: "info", level: "info",
message: "Gateway auth token received via headers.x-openclaw-auth." message:
"Gateway auth token received via headers.x-openclaw-token (or legacy x-openclaw-auth)."
}); });
} else { } else {
diagnostics.push({ diagnostics.push({
code: "openclaw_auth_header_missing", code: "openclaw_auth_header_missing",
level: "warn", level: "warn",
message: "Gateway auth token is missing from agent defaults.", message: "Gateway auth token is missing from agent defaults.",
hint: "Set agentDefaultsPayload.headers.x-openclaw-auth to the token your OpenClaw endpoint requires." hint:
"Set agentDefaultsPayload.headers.x-openclaw-token (or legacy x-openclaw-auth) to the token your OpenClaw endpoint requires."
}); });
} }
@@ -1894,7 +1908,8 @@ export function accessRoutes(
responsesWebhookHeaders: req.body.responsesWebhookHeaders ?? null, responsesWebhookHeaders: req.body.responsesWebhookHeaders ?? null,
paperclipApiUrl: req.body.paperclipApiUrl ?? null, paperclipApiUrl: req.body.paperclipApiUrl ?? null,
webhookAuthHeader: req.body.webhookAuthHeader ?? null, webhookAuthHeader: req.body.webhookAuthHeader ?? null,
inboundOpenClawAuthHeader: req.header("x-openclaw-auth") ?? null inboundOpenClawAuthHeader: req.header("x-openclaw-auth") ?? null,
inboundOpenClawTokenHeader: req.header("x-openclaw-token") ?? null
}) })
: null; : null;
@@ -1917,6 +1932,9 @@ export function accessRoutes(
inboundOpenClawAuthHeader: summarizeSecretForLog( inboundOpenClawAuthHeader: summarizeSecretForLog(
req.header("x-openclaw-auth") ?? null req.header("x-openclaw-auth") ?? null
), ),
inboundOpenClawTokenHeader: summarizeSecretForLog(
req.header("x-openclaw-token") ?? null
),
rawAgentDefaults: summarizeOpenClawDefaultsForLog( rawAgentDefaults: summarizeOpenClawDefaultsForLog(
req.body.agentDefaultsPayload ?? null req.body.agentDefaultsPayload ?? null
), ),
@@ -2107,7 +2125,9 @@ export function accessRoutes(
expectedDefaults.openClawAuthHeader && expectedDefaults.openClawAuthHeader &&
!persistedDefaults.openClawAuthHeader !persistedDefaults.openClawAuthHeader
) { ) {
missingPersistedFields.push("headers.x-openclaw-auth"); missingPersistedFields.push(
"headers.x-openclaw-token|headers.x-openclaw-auth"
);
} }
if ( if (
expectedDefaults.headerKeys.length > 0 && expectedDefaults.headerKeys.length > 0 &&

View File

@@ -432,7 +432,7 @@ export function issueRoutes(db: Db, storage: StorageService) {
details: { title: issue.title, identifier: issue.identifier }, details: { title: issue.title, identifier: issue.identifier },
}); });
if (issue.assigneeAgentId) { if (issue.assigneeAgentId && issue.status !== "backlog") {
void heartbeat void heartbeat
.wakeup(issue.assigneeAgentId, { .wakeup(issue.assigneeAgentId, {
source: "assignment", source: "assignment",
@@ -566,7 +566,7 @@ export function issueRoutes(db: Db, storage: StorageService) {
void (async () => { void (async () => {
const wakeups = new Map<string, Parameters<typeof heartbeat.wakeup>[1]>(); const wakeups = new Map<string, Parameters<typeof heartbeat.wakeup>[1]>();
if (assigneeChanged && issue.assigneeAgentId) { if (assigneeChanged && issue.assigneeAgentId && issue.status !== "backlog") {
wakeups.set(issue.assigneeAgentId, { wakeups.set(issue.assigneeAgentId, {
source: "assignment", source: "assignment",
triggerDetail: "system", triggerDetail: "system",