feat(openclaw): support /hooks/agent endpoint and multi-endpoint detection
Add OpenClawEndpointKind type to distinguish between /hooks/wake, /hooks/agent, open_responses, and generic endpoints. Build appropriate payloads per endpoint kind with optional sessionKey inclusion. Refactor webhook execution to use endpoint-aware payload construction. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
139
packages/adapters/openclaw/README.md
Normal file
139
packages/adapters/openclaw/README.md
Normal 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.
|
||||||
@@ -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\`
|
||||||
|
|||||||
@@ -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> = {};
|
||||||
@@ -390,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);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,15 +4,16 @@ import {
|
|||||||
appendWakeTextToOpenResponsesInput,
|
appendWakeTextToOpenResponsesInput,
|
||||||
buildExecutionState,
|
buildExecutionState,
|
||||||
buildWakeCompatibilityPayload,
|
buildWakeCompatibilityPayload,
|
||||||
isOpenResponsesEndpoint,
|
deriveHookAgentUrlFromResponses,
|
||||||
isTextRequiredResponse,
|
isTextRequiredResponse,
|
||||||
isWakeCompatibilityRetryableResponse,
|
isWakeCompatibilityRetryableResponse,
|
||||||
isWakeCompatibilityEndpoint,
|
|
||||||
readAndLogResponseText,
|
readAndLogResponseText,
|
||||||
redactForLog,
|
redactForLog,
|
||||||
|
resolveEndpointKind,
|
||||||
sendJsonRequest,
|
sendJsonRequest,
|
||||||
stringifyForLog,
|
stringifyForLog,
|
||||||
toStringRecord,
|
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";
|
||||||
@@ -21,18 +22,45 @@ 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 {
|
||||||
url: string;
|
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;
|
state: OpenClawExecutionState;
|
||||||
context: AdapterExecutionContext["context"];
|
|
||||||
configModel: unknown;
|
configModel: unknown;
|
||||||
}): Record<string, unknown> {
|
}): Record<string, unknown> {
|
||||||
const { url, state, context, configModel } = input;
|
const { state, configModel } = 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;
|
||||||
const isOpenResponses = isOpenResponsesEndpoint(url);
|
|
||||||
|
|
||||||
if (isOpenResponses) {
|
|
||||||
const openResponsesInput = Object.prototype.hasOwnProperty.call(state.payloadTemplate, "input")
|
const openResponsesInput = Object.prototype.hasOwnProperty.call(state.payloadTemplate, "input")
|
||||||
? appendWakeTextToOpenResponsesInput(state.payloadTemplate.input, state.wakeText)
|
? appendWakeTextToOpenResponsesInput(state.payloadTemplate.input, state.wakeText)
|
||||||
: payloadText;
|
: payloadText;
|
||||||
@@ -52,8 +80,74 @@ function buildWebhookBody(input: {
|
|||||||
paperclip_stream_transport: "webhook",
|
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;
|
||||||
|
context: AdapterExecutionContext["context"];
|
||||||
|
}): Record<string, unknown> {
|
||||||
|
const { state, context } = input;
|
||||||
|
const templateText = nonEmpty(state.payloadTemplate.text);
|
||||||
|
const payloadText = templateText ? appendWakeText(templateText, state.wakeText) : state.wakeText;
|
||||||
return {
|
return {
|
||||||
...state.payloadTemplate,
|
...state.payloadTemplate,
|
||||||
stream: false,
|
stream: false,
|
||||||
@@ -69,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;
|
||||||
@@ -92,30 +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);
|
||||||
if (isOpenResponsesEndpoint(url) && !headers["x-openclaw-session-key"] && !headers["X-OpenClaw-Session-Key"]) {
|
|
||||||
headers["x-openclaw-session-key"] = state.sessionKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
const webhookBody = buildWebhookBody({
|
const webhookBody = buildWebhookBody({
|
||||||
url,
|
endpointKind,
|
||||||
state,
|
state,
|
||||||
context,
|
context,
|
||||||
configModel: ctx.config.model,
|
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(
|
||||||
@@ -127,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();
|
||||||
@@ -138,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,
|
||||||
@@ -146,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 && isWakeCompatibilityRetryableResponse(initialResponse.responseText);
|
(activeEndpointKind === "open_responses" || activeEndpointKind === "generic") &&
|
||||||
|
isWakeCompatibilityRetryableResponse(activeResponse.responseText);
|
||||||
|
|
||||||
if (canRetryWithWakeCompatibility) {
|
if (canRetryWithWakeCompatibility) {
|
||||||
await onLog(
|
await onLog(
|
||||||
@@ -157,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,
|
||||||
@@ -172,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,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -207,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,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -227,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) {
|
||||||
|
|||||||
@@ -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",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,7 +589,7 @@ 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("uses OpenResponses payload shape for webhook transport against /v1/responses", async () => {
|
it("remaps legacy /v1/responses URLs to /hooks/agent in webhook transport", async () => {
|
||||||
const fetchMock = vi.fn().mockResolvedValue(
|
const fetchMock = vi.fn().mockResolvedValue(
|
||||||
new Response(JSON.stringify({ ok: true }), {
|
new Response(JSON.stringify({ ok: true }), {
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -586,16 +611,69 @@ describe("openclaw adapter execute", () => {
|
|||||||
|
|
||||||
expect(result.exitCode).toBe(0);
|
expect(result.exitCode).toBe(0);
|
||||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
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>;
|
const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body ?? "{}")) as Record<string, unknown>;
|
||||||
expect(body.foo).toBe("bar");
|
expect(typeof body.message).toBe("string");
|
||||||
expect(body.stream).toBe(false);
|
expect(String(body.message ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
|
||||||
expect(body.model).toBe("openclaw");
|
expect(body.stream).toBeUndefined();
|
||||||
expect(String(body.input ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
|
expect(body.input).toBeUndefined();
|
||||||
const metadata = body.metadata as Record<string, unknown>;
|
expect(body.metadata).toBeUndefined();
|
||||||
expect(metadata.PAPERCLIP_RUN_ID).toBe("run-123");
|
|
||||||
expect(metadata.paperclip_session_key).toBe("paperclip");
|
|
||||||
expect(metadata.paperclip_stream_transport).toBe("webhook");
|
|
||||||
expect(body.paperclip).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 () => {
|
||||||
@@ -624,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()
|
||||||
@@ -649,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",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -658,8 +803,8 @@ 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(firstBody.model).toBe("openclaw");
|
expect(String(firstBody.text ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
|
||||||
expect(String(firstBody.input ?? "")).toContain("PAPERCLIP_RUN_ID=run-123");
|
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");
|
||||||
});
|
});
|
||||||
@@ -697,7 +842,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",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -739,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", () => {
|
||||||
@@ -766,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()
|
||||||
|
|||||||
Reference in New Issue
Block a user