Merge origin/main into upstream-main (openclaw v2026.3.13-1)
Resolve conflicts: take upstream ci.yml changes, keep pazi 4-section versioning in package.json.feature/PAZ-358-fe-credit-error-display
commit
4e52705b75
@ -0,0 +1,159 @@
|
||||
name: Deploy Pazi Agent
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, staging]
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
environment:
|
||||
description: 'Environment to deploy to'
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- staging
|
||||
- production
|
||||
default: staging
|
||||
branch:
|
||||
description: 'Branch to deploy'
|
||||
required: true
|
||||
type: string
|
||||
default: staging
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
env:
|
||||
AWS_REGION: us-east-1
|
||||
GHCR_IMAGE: ghcr.io/pythagora-io/pazi-agent
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
outputs:
|
||||
image_tag: ${{ steps.build-image.outputs.image_tag }}
|
||||
version: ${{ steps.get_version.outputs.VERSION }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.branch || github.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Read version from package.json
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
echo "Version: v${VERSION}"
|
||||
echo "VERSION=v${VERSION}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GHCR_TOKEN }}
|
||||
|
||||
- name: Determine environment
|
||||
id: env
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
ENVIRONMENT="${{ github.event.inputs.environment }}"
|
||||
elif [[ "${{ github.ref_name }}" == "main" ]]; then
|
||||
ENVIRONMENT="production"
|
||||
else
|
||||
ENVIRONMENT="staging"
|
||||
fi
|
||||
|
||||
if [ "$ENVIRONMENT" = "production" ]; then
|
||||
echo "environment=production" >> $GITHUB_OUTPUT
|
||||
echo "suffix=" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "environment=staging" >> $GITHUB_OUTPUT
|
||||
echo "suffix=-staging" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Build, tag, and push image to GHCR
|
||||
id: build-image
|
||||
env:
|
||||
IMAGE_TAG: ${{ steps.get_version.outputs.VERSION }}${{ steps.env.outputs.suffix }}
|
||||
LATEST_TAG: latest${{ steps.env.outputs.suffix }}
|
||||
run: |
|
||||
docker build -f Dockerfile.pazi -t $GHCR_IMAGE:$IMAGE_TAG .
|
||||
docker tag $GHCR_IMAGE:$IMAGE_TAG $GHCR_IMAGE:$LATEST_TAG
|
||||
|
||||
docker push $GHCR_IMAGE:$IMAGE_TAG
|
||||
docker push $GHCR_IMAGE:$LATEST_TAG
|
||||
|
||||
echo "image=$GHCR_IMAGE:$IMAGE_TAG" >> $GITHUB_OUTPUT
|
||||
echo "image_tag=$IMAGE_TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Configure AWS credentials
|
||||
uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
aws-region: ${{ env.AWS_REGION }}
|
||||
|
||||
- name: Upload latest version to S3
|
||||
env:
|
||||
IMAGE_TAG: ${{ steps.build-image.outputs.image_tag }}
|
||||
run: |
|
||||
if [ "${{ steps.env.outputs.environment }}" = "production" ]; then
|
||||
S3_KEY="latest.txt"
|
||||
else
|
||||
S3_KEY="latest-staging.txt"
|
||||
fi
|
||||
echo "$IMAGE_TAG" > "$S3_KEY"
|
||||
aws s3 cp "$S3_KEY" "s3://assets.pazi.ai/cloud/$S3_KEY"
|
||||
|
||||
- name: Deployment Summary
|
||||
if: success()
|
||||
run: |
|
||||
echo "### Build and Push Successful! :rocket:" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Image:** ${{ steps.build-image.outputs.image }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Registry:** GHCR (${{ env.GHCR_IMAGE }})" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Version:** ${{ steps.get_version.outputs.VERSION }}" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
push-version-tag:
|
||||
if: github.ref_name == 'main'
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Tag and bump version
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
RELEASE_TAG="${{ needs.build-and-push.outputs.version }}"
|
||||
if git ls-remote --exit-code --tags origin "refs/tags/${RELEASE_TAG}" >/dev/null; then
|
||||
echo "Tag ${RELEASE_TAG} already exists on origin; skipping tag creation."
|
||||
else
|
||||
git tag "${RELEASE_TAG}"
|
||||
git push origin "${RELEASE_TAG}"
|
||||
fi
|
||||
|
||||
CURRENT=$(node -p "require('./package.json').version")
|
||||
# Version format: UPSTREAM.PAZI_PATCH (e.g. 2026.3.11.9)
|
||||
# Bump only the 4th segment (pazi patch number)
|
||||
IFS='.' read -r MAJOR MINOR UPSTREAM_PATCH PAZI_PATCH <<< "$CURRENT"
|
||||
NEXT="${MAJOR}.${MINOR}.${UPSTREAM_PATCH}.$((PAZI_PATCH + 1))"
|
||||
node -e "const pkg=require('./package.json'); pkg.version='${NEXT}'; require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, '\t') + '\n')"
|
||||
|
||||
# Sync pazi extension version to match root (upstream extensions keep their own versions)
|
||||
node -e "const fs=require('fs'),p='extensions/pazi/package.json',pkg=JSON.parse(fs.readFileSync(p,'utf8'));pkg.version='${NEXT}';fs.writeFileSync(p,JSON.stringify(pkg,null,2)+'\n')"
|
||||
|
||||
git add package.json extensions/pazi/package.json
|
||||
git commit -m "chore: release ${NEXT} [skip ci]"
|
||||
git push origin HEAD:${{ github.ref_name }}
|
||||
@ -0,0 +1,119 @@
|
||||
# Dockerfile.pazi - Pazi production wrapper
|
||||
# Builds the OpenClaw agent, then layers desktop services on top.
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stage 1: Build OpenClaw (reuses the standard build steps from Dockerfile)
|
||||
# ---------------------------------------------------------------------------
|
||||
FROM node:22-bookworm@sha256:cd7bcd2e7a1e6f72052feb023c7f6b722205d3fcab7bbcbd2d1bfdab10b1e935 AS builder
|
||||
|
||||
RUN curl -fsSL https://bun.sh/install | bash
|
||||
ENV PATH="/root/.bun/bin:${PATH}"
|
||||
|
||||
RUN corepack enable
|
||||
|
||||
WORKDIR /app
|
||||
RUN chown node:node /app
|
||||
|
||||
COPY --chown=node:node package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
|
||||
COPY --chown=node:node ui/package.json ./ui/package.json
|
||||
COPY --chown=node:node patches ./patches
|
||||
COPY --chown=node:node scripts ./scripts
|
||||
|
||||
USER node
|
||||
RUN NODE_OPTIONS=--max-old-space-size=2048 pnpm install --frozen-lockfile
|
||||
|
||||
USER node
|
||||
COPY --chown=node:node . .
|
||||
RUN pnpm build
|
||||
ENV OPENCLAW_PREFER_PNPM=1
|
||||
RUN pnpm ui:build
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Stage 2: Production image with desktop environment
|
||||
# ---------------------------------------------------------------------------
|
||||
FROM node:22-bookworm-slim
|
||||
|
||||
# Playwright: use system Chromium
|
||||
ENV CHROME_PATH=/usr/bin/chromium \
|
||||
PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium \
|
||||
PLAYWRIGHT_MCP_EXECUTABLE_PATH=/usr/bin/chromium \
|
||||
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
||||
|
||||
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
# Chromium browser
|
||||
chromium \
|
||||
# Playwright / Chromium runtime deps
|
||||
libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 \
|
||||
libdbus-1-3 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 \
|
||||
libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2 libatspi2.0-0 \
|
||||
# Fonts
|
||||
fonts-liberation fonts-noto-color-emoji \
|
||||
# Desktop environment (Xvfb + XFCE4)
|
||||
xvfb xfce4 xfce4-terminal dbus-x11 \
|
||||
# GUI viewers for common local files in Selkies sessions
|
||||
mousepad ristretto evince parole \
|
||||
# MIME + desktop integration for file open actions
|
||||
xdg-utils shared-mime-info gvfs gvfs-backends \
|
||||
# Media codecs for MP4/MP3 playback in Parole
|
||||
gstreamer1.0-libav gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly \
|
||||
# Selkies-GStreamer dependencies
|
||||
python3 python3-gi python3-setuptools python3-pip python3-dev \
|
||||
libpulse0 libwayland-dev libwayland-egl1 \
|
||||
x11-utils x11-xkb-utils x11-xserver-utils \
|
||||
libx11-xcb1 libxcb-dri3-0 libxkbcommon0 libxdamage1 libxfixes3 \
|
||||
libxv1 libxtst6 libxext6 libgcrypt20 glib-networking \
|
||||
jq \
|
||||
# Screenshot capture for desktop preview
|
||||
scrot \
|
||||
# Utilities + baseline CLI tools for workspace terminals
|
||||
git curl wget nano less file unzip zip ca-certificates procps sudo \
|
||||
# Process manager
|
||||
supervisor \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Selkies-GStreamer (WebRTC remote desktop, replaces noVNC)
|
||||
RUN SELKIES_VERSION="$(curl -fsSL \
|
||||
"https://api.github.com/repos/selkies-project/selkies/releases/latest" | \
|
||||
jq -r '.tag_name' | sed 's/[^0-9\.\-]*//g')" && \
|
||||
mkdir -p /opt/selkies && cd /opt/selkies && \
|
||||
curl -fsSL \
|
||||
"https://github.com/selkies-project/selkies/releases/download/v${SELKIES_VERSION}/selkies-gstreamer-portable-v${SELKIES_VERSION}_amd64.tar.gz" | \
|
||||
tar -xzf - && \
|
||||
echo "Selkies-GStreamer v${SELKIES_VERSION} installed"
|
||||
|
||||
# Create pazi user (UID 1001 — matches host /home/pazi volume mounts)
|
||||
RUN groupadd -g 1001 pazi && useradd -u 1001 -g 1001 -m -d /home/pazi pazi && \
|
||||
echo "pazi ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/pazi && chmod 440 /etc/sudoers.d/pazi
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy built app from builder stage
|
||||
COPY --from=builder --chown=pazi:pazi /app /app
|
||||
|
||||
# Download desktop wallpaper from S3
|
||||
RUN mkdir -p /usr/share/backgrounds && \
|
||||
curl -fsSL "https://s3.us-east-1.amazonaws.com/assets.pazi.ai/cloud/pazi-desktop-bg.jpg" \
|
||||
-o /usr/share/backgrounds/pazi-desktop.jpg
|
||||
|
||||
# Runtime directories
|
||||
RUN mkdir -p /home/pazi/generations /home/pazi/.config /home/pazi/.local/share && \
|
||||
chown -R pazi:pazi /home/pazi
|
||||
|
||||
# Supervisord config
|
||||
COPY supervisord.pazi.conf /etc/supervisor/conf.d/supervisord.conf
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
OPENCLAW_GATEWAY_PORT=12420 \
|
||||
GENERATIONS_DIR=/home/pazi/generations
|
||||
|
||||
# 12420 — OpenClaw gateway (HTTP + WS)
|
||||
# 8080 — Selkies-GStreamer WebRTC desktop
|
||||
EXPOSE 12420 8080
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
||||
CMD curl -f http://127.0.0.1:12420/health || exit 1
|
||||
|
||||
# supervisord runs as root to manage child processes with different users
|
||||
USER root
|
||||
|
||||
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
|
||||
@ -0,0 +1,257 @@
|
||||
import type { Server as HttpServer } from "node:http";
|
||||
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
|
||||
import { resolveAgentWorkspaceDir, resolveDefaultAgentId } from "../../src/agents/agent-scope.js";
|
||||
import { notifyPairingApproved } from "../../src/channels/plugins/pairing.js";
|
||||
import {
|
||||
approveChannelPairingCode,
|
||||
listChannelPairingRequests,
|
||||
} from "../../src/pairing/pairing-store.js";
|
||||
import { normalizeAgentId } from "../../src/routing/session-key.js";
|
||||
import { resolveBrowserUseConfig } from "./src/browser-use/config.js";
|
||||
import { createBrowserUseTools } from "./src/browser-use/tools.js";
|
||||
import { createPaziChannelsConfigureHandler } from "./src/channels-configure.js";
|
||||
import {
|
||||
createPaziChannelsPairingApproveHandler,
|
||||
createPaziChannelsPairingListHandler,
|
||||
} from "./src/channels-pairing.js";
|
||||
import { resolvePaziBillingConfig } from "./src/config.js";
|
||||
import { getProxyLastActivityAt, isProxyBusyForStatus } from "./src/context.js";
|
||||
import {
|
||||
createPaziFilesGet,
|
||||
createPaziFilesList,
|
||||
createPaziFilesSet,
|
||||
} from "./src/gateway/pazi-files.js";
|
||||
import { createPipedreamTools } from "./src/pipedream/tools.js";
|
||||
import { createPaziContextHandler } from "./src/proxy/pazi-context.js";
|
||||
import { startPaziProxy } from "./src/proxy/pazi-proxy.js";
|
||||
import { createPaziUploadHandler } from "./src/proxy/pazi-upload.js";
|
||||
|
||||
function normalizePluginConfig(
|
||||
value: OpenClawPluginApi["pluginConfig"],
|
||||
): Record<string, unknown> | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
async function stopServer(server: HttpServer, logger: OpenClawPluginApi["logger"]) {
|
||||
await new Promise<void>((resolve) => {
|
||||
server.close((err) => {
|
||||
if (err) {
|
||||
logger.warn(`pazi proxy shutdown failed: ${String(err)}`);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export default {
|
||||
id: "pazi",
|
||||
name: "Pazi Proxy",
|
||||
description: "Routes Anthropic calls through the Pazi API.",
|
||||
register(api: OpenClawPluginApi) {
|
||||
const defaultAgentId = resolveDefaultAgentId(api.config);
|
||||
const resolveWorkspace = (requestedAgentId: unknown) => {
|
||||
const requested =
|
||||
typeof requestedAgentId === "number" ? String(requestedAgentId) : requestedAgentId;
|
||||
const normalized =
|
||||
typeof requested === "string" && requested.trim()
|
||||
? normalizeAgentId(requested)
|
||||
: defaultAgentId;
|
||||
return {
|
||||
agentId: normalized,
|
||||
workspaceDir: resolveAgentWorkspaceDir(api.config, normalized),
|
||||
};
|
||||
};
|
||||
|
||||
const pluginConfig = normalizePluginConfig(api.pluginConfig);
|
||||
const gatewayAuthToken =
|
||||
typeof api.config.gateway?.auth?.token === "string"
|
||||
? api.config.gateway.auth.token
|
||||
: undefined;
|
||||
const contextHandler = createPaziContextHandler({
|
||||
configToken: gatewayAuthToken,
|
||||
env: process.env,
|
||||
logger: api.logger,
|
||||
});
|
||||
|
||||
const uploadHandler = createPaziUploadHandler({
|
||||
configToken: gatewayAuthToken,
|
||||
env: process.env,
|
||||
logger: api.logger,
|
||||
});
|
||||
|
||||
api.registerGatewayMethod("pazi.integration.emit", ({ params, respond, context }) => {
|
||||
context.broadcast("integration", params);
|
||||
respond(true, { emitted: true });
|
||||
});
|
||||
api.registerGatewayMethod("pazi.files.list", createPaziFilesList(resolveWorkspace));
|
||||
api.registerGatewayMethod("pazi.files.get", createPaziFilesGet(resolveWorkspace));
|
||||
api.registerGatewayMethod("pazi.files.set", createPaziFilesSet(resolveWorkspace));
|
||||
|
||||
api.registerGatewayMethod(
|
||||
"pazi.channels.configure",
|
||||
createPaziChannelsConfigureHandler({
|
||||
loadConfig: () => api.runtime.config.loadConfig(),
|
||||
writeConfigFile: (cfg) => api.runtime.config.writeConfigFile(cfg),
|
||||
probeSlack: (token, timeoutMs) => api.runtime.channel.slack.probeSlack(token, timeoutMs),
|
||||
probeTelegram: (token, timeoutMs, proxyUrl) =>
|
||||
api.runtime.channel.telegram.probeTelegram(token, timeoutMs, proxyUrl),
|
||||
}),
|
||||
);
|
||||
const gatewayEnv = process.env;
|
||||
const pairingGatewayDeps = {
|
||||
loadConfig: () => api.runtime.config.loadConfig(),
|
||||
env: gatewayEnv,
|
||||
logWarn: (message: string) => {
|
||||
api.logger.warn(message);
|
||||
},
|
||||
listRequests: ({
|
||||
channel,
|
||||
accountId,
|
||||
env,
|
||||
}: {
|
||||
channel: "telegram";
|
||||
accountId: string;
|
||||
env: NodeJS.ProcessEnv;
|
||||
}) => listChannelPairingRequests(channel, env, accountId),
|
||||
approveCode: ({
|
||||
channel,
|
||||
accountId,
|
||||
code,
|
||||
env,
|
||||
}: {
|
||||
channel: "telegram";
|
||||
accountId: string;
|
||||
code: string;
|
||||
env: NodeJS.ProcessEnv;
|
||||
}) => approveChannelPairingCode({ channel, accountId, code, env }),
|
||||
notifyApproved: ({
|
||||
channelId,
|
||||
id,
|
||||
cfg,
|
||||
}: {
|
||||
channelId: "telegram";
|
||||
id: string;
|
||||
cfg: Record<string, unknown>;
|
||||
}) =>
|
||||
notifyPairingApproved({
|
||||
channelId,
|
||||
id,
|
||||
cfg,
|
||||
}),
|
||||
};
|
||||
api.registerGatewayMethod(
|
||||
"pazi.channels.pairing.list",
|
||||
createPaziChannelsPairingListHandler(pairingGatewayDeps),
|
||||
);
|
||||
api.registerGatewayMethod(
|
||||
"pazi.channels.pairing.approve",
|
||||
createPaziChannelsPairingApproveHandler(pairingGatewayDeps),
|
||||
);
|
||||
|
||||
const tools = createPipedreamTools({
|
||||
pluginConfig,
|
||||
config: api.config,
|
||||
});
|
||||
for (const tool of tools) {
|
||||
api.registerTool(tool);
|
||||
}
|
||||
|
||||
const browserUseConfig = resolveBrowserUseConfig({
|
||||
pluginConfig,
|
||||
env: process.env,
|
||||
});
|
||||
if (browserUseConfig.browserUseEnabled) {
|
||||
const browserUseTools = createBrowserUseTools({ pluginConfig });
|
||||
for (const tool of browserUseTools) {
|
||||
api.registerTool(tool);
|
||||
}
|
||||
}
|
||||
|
||||
api.registerHttpRoute({
|
||||
path: "/pazi/context",
|
||||
auth: "gateway",
|
||||
handler: async (req, res) => {
|
||||
if (req.method !== "POST") {
|
||||
res.statusCode = 404;
|
||||
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
||||
res.end("Not Found");
|
||||
return;
|
||||
}
|
||||
await contextHandler(req, res);
|
||||
},
|
||||
});
|
||||
|
||||
api.registerHttpRoute({
|
||||
path: "/health",
|
||||
auth: "gateway",
|
||||
handler: (_req, res) => {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
});
|
||||
res.end(JSON.stringify({ status: "ok", timestamp: new Date().toISOString() }));
|
||||
},
|
||||
});
|
||||
|
||||
api.registerHttpRoute({
|
||||
path: "/status",
|
||||
auth: "gateway",
|
||||
handler: (_req, res) => {
|
||||
const lastActivityAtMs = getProxyLastActivityAt();
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
});
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
status: "running",
|
||||
busy: isProxyBusyForStatus(),
|
||||
lastActivityAt:
|
||||
lastActivityAtMs === null ? null : new Date(lastActivityAtMs).toISOString(),
|
||||
version: process.env.AGENT_VERSION ?? "unknown",
|
||||
environment: process.env.NODE_ENV ?? "development",
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
api.registerHttpRoute({
|
||||
path: "/pazi/upload",
|
||||
auth: "gateway",
|
||||
handler: async (req, res) => {
|
||||
if (req.method !== "POST") {
|
||||
res.statusCode = 404;
|
||||
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
||||
res.end("Not Found");
|
||||
return;
|
||||
}
|
||||
await uploadHandler(req, res);
|
||||
},
|
||||
});
|
||||
|
||||
let proxyServer: HttpServer | null = null;
|
||||
|
||||
api.registerService({
|
||||
id: "pazi-proxy",
|
||||
start: async () => {
|
||||
const resolved = resolvePaziBillingConfig({
|
||||
pluginConfig,
|
||||
env: process.env,
|
||||
});
|
||||
proxyServer = await startPaziProxy({
|
||||
apiUrl: resolved.apiUrl,
|
||||
port: resolved.proxyPort,
|
||||
logger: api.logger,
|
||||
});
|
||||
},
|
||||
stop: async () => {
|
||||
if (!proxyServer) {
|
||||
return;
|
||||
}
|
||||
await stopServer(proxyServer, api.logger);
|
||||
proxyServer = null;
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,13 @@
|
||||
{
|
||||
"id": "pazi",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"apiUrl": { "type": "string" },
|
||||
"proxyPort": { "type": "number" },
|
||||
"browserUseEnabled": { "type": "boolean" },
|
||||
"browserUseTimeoutMs": { "type": "number" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "@openclaw/pazi",
|
||||
"version": "2026.3.12.5",
|
||||
"private": true,
|
||||
"description": "OpenClaw Pazi proxy",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "0.34.48"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"openclaw": ">=2026.1.26"
|
||||
},
|
||||
"openclaw": {
|
||||
"extensions": [
|
||||
"./index.ts"
|
||||
]
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,347 @@
|
||||
import { getProxyContext } from "../context.js";
|
||||
import { resolveBrowserUseConfig } from "./config.js";
|
||||
|
||||
type ApiParams = {
|
||||
apiUrl: string;
|
||||
proxyToken: string;
|
||||
timeoutMs: number;
|
||||
};
|
||||
|
||||
export type BrowserUseApiResult<T> = { ok: true; data: T } | { ok: false; error: string };
|
||||
|
||||
export type BrowserUseCreateSessionResponse = {
|
||||
sessionId: string;
|
||||
liveUrl?: string;
|
||||
status?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type BrowserUseSessionStatusResponse = {
|
||||
sessionId: string;
|
||||
liveUrl?: string;
|
||||
status?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type BrowserUseSnapshotResponse = {
|
||||
text: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type BrowserUseScreenshotResponse = {
|
||||
url: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type BrowserUseRunTaskResponse = {
|
||||
taskId: string;
|
||||
liveUrl?: string;
|
||||
status?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type BrowserUseTaskStatusResponse = {
|
||||
taskId: string;
|
||||
status: string;
|
||||
liveUrl?: string;
|
||||
result?: unknown;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type BrowserUseStopSessionResponse = {
|
||||
ok?: boolean;
|
||||
status?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
function resolveApiParams(pluginConfig: Record<string, unknown> | null): ApiParams {
|
||||
const context = getProxyContext();
|
||||
if (!context) {
|
||||
throw new Error("No billing context set — workspace may not be initialized yet");
|
||||
}
|
||||
|
||||
const resolved = resolveBrowserUseConfig({
|
||||
pluginConfig,
|
||||
env: process.env,
|
||||
});
|
||||
const apiUrl = resolved.browserUseApiUrl?.trim();
|
||||
if (!apiUrl) {
|
||||
throw new Error("Browser Use API URL not configured");
|
||||
}
|
||||
|
||||
let baseUrl: URL;
|
||||
try {
|
||||
baseUrl = new URL(apiUrl);
|
||||
} catch {
|
||||
throw new Error(`Invalid Browser Use API URL: ${apiUrl}`);
|
||||
}
|
||||
|
||||
return {
|
||||
apiUrl: baseUrl.toString(),
|
||||
proxyToken: context.proxyToken,
|
||||
timeoutMs: resolved.browserUseTimeoutMs,
|
||||
};
|
||||
}
|
||||
|
||||
function buildEndpointUrl(baseApiUrl: string, endpointPath: string): URL {
|
||||
const url = new URL(baseApiUrl);
|
||||
const prefix = url.pathname.endsWith("/") ? url.pathname : `${url.pathname}/`;
|
||||
url.pathname = `${prefix}${endpointPath.replace(/^\/+/, "")}`;
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
return url;
|
||||
}
|
||||
|
||||
function readErrorMessage(payload: unknown): string | undefined {
|
||||
if (!payload) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof payload === "string") {
|
||||
return payload;
|
||||
}
|
||||
if (typeof payload === "object") {
|
||||
const record = payload as { error?: unknown; message?: unknown };
|
||||
if (typeof record.error === "string") {
|
||||
return record.error;
|
||||
}
|
||||
if (typeof record.message === "string") {
|
||||
return record.message;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function readJsonBody(res: Response): Promise<unknown> {
|
||||
const text = await res.text();
|
||||
if (!text.trim()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
async function parseResponse<T>(res: Response): Promise<BrowserUseApiResult<T>> {
|
||||
const payload = await readJsonBody(res);
|
||||
if (res.ok) {
|
||||
return { ok: true, data: payload as T };
|
||||
}
|
||||
const message = readErrorMessage(payload) ?? res.statusText ?? "Request failed";
|
||||
const status = res.status ? ` (${res.status})` : "";
|
||||
return { ok: false, error: `Pazi Browser Use API error${status}: ${message}` };
|
||||
}
|
||||
|
||||
function withTimeoutSignal(
|
||||
timeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): {
|
||||
signal: AbortSignal;
|
||||
cleanup: () => void;
|
||||
} {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => {
|
||||
controller.abort();
|
||||
}, timeoutMs);
|
||||
|
||||
const onAbort = () => {
|
||||
controller.abort();
|
||||
};
|
||||
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
controller.abort();
|
||||
} else {
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
signal: controller.signal,
|
||||
cleanup: () => {
|
||||
clearTimeout(timer);
|
||||
if (signal) {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function requestJson<T>(params: {
|
||||
apiParams: ApiParams;
|
||||
endpointPath: string;
|
||||
init?: RequestInit;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<BrowserUseApiResult<T>> {
|
||||
const url = buildEndpointUrl(params.apiParams.apiUrl, params.endpointPath);
|
||||
const headers = new Headers(params.init?.headers);
|
||||
headers.set("x-proxy-token", params.apiParams.proxyToken);
|
||||
const timeout = withTimeoutSignal(params.apiParams.timeoutMs, params.signal);
|
||||
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
...params.init,
|
||||
headers,
|
||||
signal: timeout.signal,
|
||||
});
|
||||
return await parseResponse<T>(res);
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === "AbortError") {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Pazi Browser Use API request timed out after ${String(params.apiParams.timeoutMs)}ms`,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
} finally {
|
||||
timeout.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
export async function createSession(
|
||||
params: {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
body?: Record<string, unknown>;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<BrowserUseApiResult<BrowserUseCreateSessionResponse>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
return await requestJson({
|
||||
apiParams,
|
||||
endpointPath: "session",
|
||||
init: {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(params.body ?? {}),
|
||||
},
|
||||
signal,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSessionStatus(
|
||||
params: {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
sessionId: string;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<BrowserUseApiResult<BrowserUseSessionStatusResponse>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
return await requestJson({
|
||||
apiParams,
|
||||
endpointPath: `session/${encodeURIComponent(params.sessionId)}`,
|
||||
signal,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSnapshot(
|
||||
params: {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
sessionId: string;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<BrowserUseApiResult<BrowserUseSnapshotResponse>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
return await requestJson({
|
||||
apiParams,
|
||||
endpointPath: `session/${encodeURIComponent(params.sessionId)}/snapshot`,
|
||||
signal,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getScreenshot(
|
||||
params: {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
sessionId: string;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<BrowserUseApiResult<BrowserUseScreenshotResponse>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
return await requestJson({
|
||||
apiParams,
|
||||
endpointPath: `session/${encodeURIComponent(params.sessionId)}/screenshot`,
|
||||
signal,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function runTask(
|
||||
params: {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
body: {
|
||||
task: string;
|
||||
sessionId?: string;
|
||||
};
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<BrowserUseApiResult<BrowserUseRunTaskResponse>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
return await requestJson({
|
||||
apiParams,
|
||||
endpointPath: "task",
|
||||
init: {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(params.body),
|
||||
},
|
||||
signal,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getTaskStatus(
|
||||
params: {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
taskId: string;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<BrowserUseApiResult<BrowserUseTaskStatusResponse>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
return await requestJson({
|
||||
apiParams,
|
||||
endpointPath: `task/${encodeURIComponent(params.taskId)}`,
|
||||
signal,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function stopSession(
|
||||
params: {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
sessionId: string;
|
||||
},
|
||||
signal?: AbortSignal,
|
||||
): Promise<BrowserUseApiResult<BrowserUseStopSessionResponse>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
return await requestJson({
|
||||
apiParams,
|
||||
endpointPath: `session/${encodeURIComponent(params.sessionId)}`,
|
||||
init: { method: "DELETE" },
|
||||
signal,
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,93 @@
|
||||
import { resolvePaziBillingConfig } from "../config.js";
|
||||
|
||||
export type BrowserUseConfig = {
|
||||
browserUseEnabled: boolean;
|
||||
browserUseApiUrl?: string;
|
||||
browserUseTimeoutMs: number;
|
||||
};
|
||||
|
||||
const DEFAULT_BROWSER_USE_TIMEOUT_MS = 120_000;
|
||||
|
||||
function normalizeString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeNumber(value: unknown): number | undefined {
|
||||
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
|
||||
return Math.floor(value);
|
||||
}
|
||||
if (typeof value === "string" && value.trim().length > 0) {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
if (Number.isFinite(parsed) && parsed > 0) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function normalizeBoolean(value: unknown): boolean | undefined {
|
||||
if (typeof value === "boolean") {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["1", "true", "yes", "on"].includes(normalized)) {
|
||||
return true;
|
||||
}
|
||||
if (["0", "false", "no", "off"].includes(normalized)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function withBrowserUsePath(baseUrl: string): string {
|
||||
try {
|
||||
const url = new URL(baseUrl);
|
||||
const normalizedPath = url.pathname.replace(/\/+$/, "");
|
||||
if (normalizedPath.endsWith("/browser-use")) {
|
||||
url.pathname = normalizedPath;
|
||||
} else if (normalizedPath.length === 0 || normalizedPath === "/") {
|
||||
url.pathname = "/browser-use";
|
||||
} else {
|
||||
url.pathname = `${normalizedPath}/browser-use`;
|
||||
}
|
||||
return url.toString();
|
||||
} catch {
|
||||
return baseUrl;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveBrowserUseConfig(params: {
|
||||
pluginConfig?: Record<string, unknown> | null;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
}): BrowserUseConfig {
|
||||
const env = params.env ?? process.env;
|
||||
const raw = params.pluginConfig ?? {};
|
||||
|
||||
const browserUseEnabled =
|
||||
normalizeBoolean(raw.browserUseEnabled) ?? normalizeBoolean(env.BROWSER_USE_ENABLED) ?? false;
|
||||
|
||||
const browserUseTimeoutMs =
|
||||
normalizeNumber(raw.browserUseTimeoutMs) ??
|
||||
normalizeNumber(env.BROWSER_USE_TIMEOUT_MS) ??
|
||||
DEFAULT_BROWSER_USE_TIMEOUT_MS;
|
||||
|
||||
const billingConfig = resolvePaziBillingConfig({
|
||||
pluginConfig: params.pluginConfig,
|
||||
env,
|
||||
});
|
||||
|
||||
const browserUseApiBase =
|
||||
normalizeString(env.BROWSER_USE_API_URL) ?? normalizeString(billingConfig.apiUrl);
|
||||
|
||||
return {
|
||||
browserUseEnabled,
|
||||
browserUseApiUrl: browserUseApiBase ? withBrowserUsePath(browserUseApiBase) : undefined,
|
||||
browserUseTimeoutMs,
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,411 @@
|
||||
import { mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { extname, join } from "node:path";
|
||||
import { Type } from "@sinclair/typebox";
|
||||
import type { AnyAgentTool } from "openclaw/plugin-sdk";
|
||||
import {
|
||||
createSession,
|
||||
getSessionStatus,
|
||||
getSnapshot,
|
||||
getScreenshot,
|
||||
getTaskStatus,
|
||||
runTask,
|
||||
stopSession,
|
||||
} from "./api.js";
|
||||
import { resolveBrowserUseConfig } from "./config.js";
|
||||
|
||||
const BROWSER_USE_ACTIONS = [
|
||||
"run",
|
||||
"session_create",
|
||||
"session_stop",
|
||||
"snapshot",
|
||||
"screenshot",
|
||||
"status",
|
||||
] as const;
|
||||
|
||||
type BrowserUseAction = (typeof BROWSER_USE_ACTIONS)[number];
|
||||
|
||||
type AgentToolResult = {
|
||||
content: Array<{ type: "text"; text: string }>;
|
||||
details?: unknown;
|
||||
};
|
||||
|
||||
export type BrowserUseToolsDeps = {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
function stringEnum<T extends readonly string[]>(
|
||||
values: T,
|
||||
options: { description?: string } = {},
|
||||
) {
|
||||
return Type.Unsafe<T[number]>({
|
||||
type: "string",
|
||||
enum: [...values],
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
function json(payload: unknown, summary?: string): AgentToolResult {
|
||||
const details = payload as Record<string, unknown>;
|
||||
const text = summary
|
||||
? `${summary}\n\n${JSON.stringify(payload, null, 2)}`
|
||||
: JSON.stringify(payload, null, 2);
|
||||
return {
|
||||
content: [{ type: "text", text }],
|
||||
details,
|
||||
};
|
||||
}
|
||||
|
||||
function readRequiredString(params: Record<string, unknown>, key: string): string {
|
||||
const value = params[key];
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(`${key} required`);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error(`${key} required`);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function readOptionalString(params: Record<string, unknown>, key: string): string | undefined {
|
||||
const value = params[key];
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function fileExtensionFromContentType(contentType: string | null): string | undefined {
|
||||
if (!contentType) {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = contentType.toLowerCase();
|
||||
if (normalized.includes("image/png")) {
|
||||
return ".png";
|
||||
}
|
||||
if (normalized.includes("image/jpeg") || normalized.includes("image/jpg")) {
|
||||
return ".jpg";
|
||||
}
|
||||
if (normalized.includes("image/webp")) {
|
||||
return ".webp";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function extensionFromUrl(rawUrl: string): string | undefined {
|
||||
try {
|
||||
const parsed = new URL(rawUrl);
|
||||
const extension = extname(parsed.pathname).trim().toLowerCase();
|
||||
if (!extension) {
|
||||
return undefined;
|
||||
}
|
||||
if (extension.length > 10) {
|
||||
return undefined;
|
||||
}
|
||||
return extension;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function withTimeoutSignal(
|
||||
timeoutMs: number,
|
||||
signal?: AbortSignal,
|
||||
): {
|
||||
signal: AbortSignal;
|
||||
cleanup: () => void;
|
||||
} {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => {
|
||||
controller.abort();
|
||||
}, timeoutMs);
|
||||
|
||||
const onAbort = () => {
|
||||
controller.abort();
|
||||
};
|
||||
|
||||
if (signal) {
|
||||
if (signal.aborted) {
|
||||
controller.abort();
|
||||
} else {
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
signal: controller.signal,
|
||||
cleanup: () => {
|
||||
clearTimeout(timer);
|
||||
if (signal) {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function downloadScreenshot(params: {
|
||||
url: string;
|
||||
timeoutMs: number;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<{ path: string; bytes: number; mimeType?: string }> {
|
||||
const timeout = withTimeoutSignal(params.timeoutMs, params.signal);
|
||||
|
||||
try {
|
||||
const res = await fetch(params.url, {
|
||||
method: "GET",
|
||||
signal: timeout.signal,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const statusText = res.statusText || "request_failed";
|
||||
throw new Error(`Screenshot download failed (${String(res.status)}): ${statusText}`);
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(await res.arrayBuffer());
|
||||
const extension =
|
||||
fileExtensionFromContentType(res.headers.get("content-type")) ??
|
||||
extensionFromUrl(params.url) ??
|
||||
".png";
|
||||
|
||||
const dir = await mkdtemp(join(tmpdir(), "openclaw-browser-use-"));
|
||||
const path = join(dir, `screenshot${extension}`);
|
||||
await writeFile(path, bytes);
|
||||
|
||||
return {
|
||||
path,
|
||||
bytes: bytes.byteLength,
|
||||
mimeType: res.headers.get("content-type") ?? undefined,
|
||||
};
|
||||
} finally {
|
||||
timeout.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
function buildStatusHint(action: BrowserUseAction): string {
|
||||
if (action === "run") {
|
||||
return "Task started. Poll with action=status and taskId until status is completed or failed.";
|
||||
}
|
||||
if (action === "session_create") {
|
||||
return "Session created. Use snapshot/screenshot/status/session_stop with this sessionId.";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function createBrowserUseTools(deps: BrowserUseToolsDeps): AnyAgentTool[] {
|
||||
return [
|
||||
{
|
||||
name: "browser_use",
|
||||
label: "Browser Use",
|
||||
description:
|
||||
"Stealth cloud browser automation via Pazi Browser Use API. Supports async run tasks and direct session controls.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
action: stringEnum(BROWSER_USE_ACTIONS, {
|
||||
description: `Action to perform: ${BROWSER_USE_ACTIONS.join(", ")}`,
|
||||
}),
|
||||
task: Type.Optional(
|
||||
Type.String({
|
||||
description: "Natural language browsing task for action=run.",
|
||||
}),
|
||||
),
|
||||
taskId: Type.Optional(Type.String({ description: "Task ID for action=status." })),
|
||||
sessionId: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
"Session ID for session_stop, snapshot, screenshot, or session status checks.",
|
||||
}),
|
||||
),
|
||||
url: Type.Optional(
|
||||
Type.String({
|
||||
description: "Optional starting URL used when creating a new session.",
|
||||
}),
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>, signal?: AbortSignal) {
|
||||
try {
|
||||
const actionRaw = params.action;
|
||||
const action =
|
||||
typeof actionRaw === "string" ? (actionRaw.trim() as BrowserUseAction) : undefined;
|
||||
if (!action) {
|
||||
throw new Error("action required");
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "run": {
|
||||
const task = readRequiredString(params, "task");
|
||||
const sessionId = readOptionalString(params, "sessionId");
|
||||
const result = await runTask(
|
||||
{
|
||||
pluginConfig: deps.pluginConfig,
|
||||
body: {
|
||||
task,
|
||||
...(sessionId ? { sessionId } : {}),
|
||||
},
|
||||
},
|
||||
signal,
|
||||
);
|
||||
if (!result.ok) {
|
||||
return json({ error: result.error });
|
||||
}
|
||||
|
||||
return json(
|
||||
{
|
||||
status: typeof result.data.status === "string" ? result.data.status : "running",
|
||||
taskId: result.data.taskId,
|
||||
liveUrl: result.data.liveUrl,
|
||||
hint: buildStatusHint(action),
|
||||
},
|
||||
"Browser Use task started.",
|
||||
);
|
||||
}
|
||||
|
||||
case "session_create": {
|
||||
const startUrl = readOptionalString(params, "url");
|
||||
const result = await createSession(
|
||||
{
|
||||
pluginConfig: deps.pluginConfig,
|
||||
body: startUrl ? { url: startUrl } : undefined,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
if (!result.ok) {
|
||||
return json({ error: result.error });
|
||||
}
|
||||
|
||||
return json(
|
||||
{
|
||||
sessionId: result.data.sessionId,
|
||||
liveUrl: result.data.liveUrl,
|
||||
status: result.data.status,
|
||||
hint: buildStatusHint(action),
|
||||
},
|
||||
"Browser Use session created.",
|
||||
);
|
||||
}
|
||||
|
||||
case "session_stop": {
|
||||
const sessionId = readRequiredString(params, "sessionId");
|
||||
const result = await stopSession(
|
||||
{ pluginConfig: deps.pluginConfig, sessionId },
|
||||
signal,
|
||||
);
|
||||
if (!result.ok) {
|
||||
return json({ error: result.error });
|
||||
}
|
||||
return json({ sessionId, ...result.data }, "Browser Use session stopped.");
|
||||
}
|
||||
|
||||
case "snapshot": {
|
||||
const sessionId = readRequiredString(params, "sessionId");
|
||||
const result = await getSnapshot(
|
||||
{ pluginConfig: deps.pluginConfig, sessionId },
|
||||
signal,
|
||||
);
|
||||
if (!result.ok) {
|
||||
return json({ error: result.error });
|
||||
}
|
||||
if (typeof result.data.text !== "string") {
|
||||
return json({ error: "Snapshot response missing text" });
|
||||
}
|
||||
return {
|
||||
content: [{ type: "text", text: result.data.text }],
|
||||
details: {
|
||||
sessionId,
|
||||
text: result.data.text,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "screenshot": {
|
||||
const sessionId = readRequiredString(params, "sessionId");
|
||||
const screenshot = await getScreenshot(
|
||||
{ pluginConfig: deps.pluginConfig, sessionId },
|
||||
signal,
|
||||
);
|
||||
if (!screenshot.ok) {
|
||||
return json({ error: screenshot.error });
|
||||
}
|
||||
|
||||
const screenshotUrl =
|
||||
typeof screenshot.data.url === "string" ? screenshot.data.url.trim() : "";
|
||||
if (!screenshotUrl) {
|
||||
return json({ error: "Screenshot response missing URL" });
|
||||
}
|
||||
|
||||
const resolvedCfg = resolveBrowserUseConfig({
|
||||
pluginConfig: deps.pluginConfig,
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
const downloaded = await downloadScreenshot({
|
||||
url: screenshotUrl,
|
||||
timeoutMs: resolvedCfg.browserUseTimeoutMs,
|
||||
signal,
|
||||
});
|
||||
|
||||
return {
|
||||
content: [{ type: "text", text: `FILE:${downloaded.path}` }],
|
||||
details: {
|
||||
sessionId,
|
||||
url: screenshotUrl,
|
||||
path: downloaded.path,
|
||||
bytes: downloaded.bytes,
|
||||
mimeType: downloaded.mimeType,
|
||||
imagePaths: [downloaded.path],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "status": {
|
||||
const taskId = readOptionalString(params, "taskId");
|
||||
const sessionId = readOptionalString(params, "sessionId");
|
||||
|
||||
if (!taskId && !sessionId) {
|
||||
throw new Error("taskId or sessionId required");
|
||||
}
|
||||
if (taskId && sessionId) {
|
||||
throw new Error("Provide either taskId or sessionId, not both");
|
||||
}
|
||||
|
||||
if (taskId) {
|
||||
const result = await getTaskStatus(
|
||||
{ pluginConfig: deps.pluginConfig, taskId },
|
||||
signal,
|
||||
);
|
||||
if (!result.ok) {
|
||||
return json({ error: result.error });
|
||||
}
|
||||
|
||||
return json({ taskId, ...result.data }, "Browser Use task status.");
|
||||
}
|
||||
|
||||
const sessionResult = await getSessionStatus(
|
||||
{
|
||||
pluginConfig: deps.pluginConfig,
|
||||
sessionId: sessionId as string,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
if (!sessionResult.ok) {
|
||||
return json({ error: sessionResult.error });
|
||||
}
|
||||
|
||||
return json({ sessionId, ...sessionResult.data }, "Browser Use session status.");
|
||||
}
|
||||
|
||||
default: {
|
||||
action satisfies never;
|
||||
return json({ error: `Unsupported action: ${String(action)}` });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,462 @@
|
||||
type ChannelType = "slack" | "telegram";
|
||||
|
||||
interface ChannelConfigureParams {
|
||||
channel: ChannelType;
|
||||
accountId?: string;
|
||||
timeoutMs?: number;
|
||||
config: {
|
||||
name?: string;
|
||||
botToken?: string;
|
||||
appToken?: string;
|
||||
appId?: string;
|
||||
accessMode?: "open" | "closed";
|
||||
groupAccessMode?: "open" | "closed";
|
||||
allowFrom?: string[];
|
||||
token?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ProbeResult {
|
||||
ok: boolean;
|
||||
status?: number | null;
|
||||
error?: string | null;
|
||||
bot?: {
|
||||
id?: string | number | null;
|
||||
name?: string | null;
|
||||
username?: string | null;
|
||||
};
|
||||
team?: { id?: string | null; name?: string | null };
|
||||
elapsedMs?: number | null;
|
||||
}
|
||||
|
||||
interface TelegramOnboardingResult {
|
||||
mode: "pairing";
|
||||
dmPolicy: "pairing";
|
||||
command: string;
|
||||
botUsername?: string | null;
|
||||
deepLink?: string;
|
||||
pollingIntervalMs?: number;
|
||||
}
|
||||
|
||||
interface ChannelConfigureResult {
|
||||
ok: true;
|
||||
channel: ChannelType;
|
||||
accountId: string;
|
||||
probe?: ProbeResult;
|
||||
appId?: string;
|
||||
teamId?: string;
|
||||
dmPolicy?: "open" | "allowlist";
|
||||
groupPolicy?: "open" | "allowlist";
|
||||
allowFrom?: string[];
|
||||
onboarding?: TelegramOnboardingResult;
|
||||
}
|
||||
|
||||
type GatewayErrorShape = {
|
||||
code: string;
|
||||
message: string;
|
||||
};
|
||||
|
||||
interface GatewayMethodContext {
|
||||
params: unknown;
|
||||
respond: (ok: boolean, data?: unknown, error?: GatewayErrorShape) => void;
|
||||
context: {
|
||||
stopChannel: (channel: string, accountId?: string) => Promise<void>;
|
||||
startChannel: (channel: string, accountId?: string) => Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type OpenClawConfig = Record<string, any>;
|
||||
|
||||
interface ChannelConfigureDeps {
|
||||
loadConfig: () => OpenClawConfig;
|
||||
writeConfigFile: (cfg: OpenClawConfig) => void | Promise<void>;
|
||||
probeSlack: (token: string, timeoutMs: number) => Promise<ProbeResult>;
|
||||
probeTelegram: (
|
||||
token: string,
|
||||
timeoutMs: number,
|
||||
proxyUrl: string | undefined,
|
||||
) => Promise<ProbeResult>;
|
||||
}
|
||||
|
||||
const VALID_CHANNELS: ReadonlySet<string> = new Set(["slack", "telegram"]);
|
||||
const ERROR_INVALID_REQUEST = "INVALID_REQUEST";
|
||||
const ERROR_UNAVAILABLE = "UNAVAILABLE";
|
||||
const TELEGRAM_PAIRING_POLL_INTERVAL_MS = 3000;
|
||||
|
||||
function respondError(
|
||||
respond: GatewayMethodContext["respond"],
|
||||
code: string,
|
||||
message: string,
|
||||
payload?: unknown,
|
||||
): void {
|
||||
respond(false, payload, { code, message });
|
||||
}
|
||||
|
||||
function isChannelType(value: unknown): value is ChannelType {
|
||||
return typeof value === "string" && VALID_CHANNELS.has(value);
|
||||
}
|
||||
|
||||
function validateParams(raw: unknown): {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
params?: ChannelConfigureParams;
|
||||
} {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
return { ok: false, error: "params must be an object" };
|
||||
}
|
||||
const p = raw as Record<string, unknown>;
|
||||
|
||||
if (!isChannelType(p.channel)) {
|
||||
return { ok: false, error: "channel must be 'slack' or 'telegram'" };
|
||||
}
|
||||
|
||||
const config = p.config;
|
||||
if (!config || typeof config !== "object") {
|
||||
return { ok: false, error: "config must be an object" };
|
||||
}
|
||||
const cfg = config as Record<string, unknown>;
|
||||
|
||||
if (p.channel === "slack") {
|
||||
const botToken = typeof cfg.botToken === "string" ? cfg.botToken.trim() : "";
|
||||
const appToken = typeof cfg.appToken === "string" ? cfg.appToken.trim() : "";
|
||||
const accessMode = cfg.accessMode === "closed" ? "closed" : "open";
|
||||
const allowFrom = Array.isArray(cfg.allowFrom)
|
||||
? cfg.allowFrom.filter(
|
||||
(entry): entry is string => typeof entry === "string" && entry.trim().length > 0,
|
||||
)
|
||||
: [];
|
||||
if (!botToken || !appToken) {
|
||||
return { ok: false, error: "Slack requires botToken and appToken" };
|
||||
}
|
||||
if (accessMode === "closed" && allowFrom.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "Closed Slack access requires at least one allowed Slack user ID",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (p.channel === "telegram") {
|
||||
const token =
|
||||
typeof cfg.token === "string"
|
||||
? cfg.token.trim()
|
||||
: typeof cfg.botToken === "string"
|
||||
? cfg.botToken.trim()
|
||||
: "";
|
||||
if (!token) {
|
||||
return { ok: false, error: "Telegram requires token or botToken" };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
params: {
|
||||
channel: p.channel,
|
||||
accountId: typeof p.accountId === "string" ? p.accountId : undefined,
|
||||
timeoutMs: typeof p.timeoutMs === "number" ? p.timeoutMs : undefined,
|
||||
config: {
|
||||
name: typeof cfg.name === "string" ? cfg.name : undefined,
|
||||
botToken: typeof cfg.botToken === "string" ? cfg.botToken : undefined,
|
||||
appToken: typeof cfg.appToken === "string" ? cfg.appToken : undefined,
|
||||
appId: typeof cfg.appId === "string" ? cfg.appId : undefined,
|
||||
accessMode: cfg.accessMode === "closed" ? "closed" : "open",
|
||||
groupAccessMode: cfg.groupAccessMode === "closed" ? "closed" : "open",
|
||||
allowFrom: Array.isArray(cfg.allowFrom)
|
||||
? cfg.allowFrom.filter((entry): entry is string => typeof entry === "string")
|
||||
: undefined,
|
||||
token: typeof cfg.token === "string" ? cfg.token : undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSlackAllowFrom(input: string[] | undefined): string[] {
|
||||
return (input ?? [])
|
||||
.map((entry) => entry.trim().toUpperCase())
|
||||
.filter((entry) => entry.length > 0);
|
||||
}
|
||||
|
||||
function normalizeBindingChannel(channel: string): string {
|
||||
return channel.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function upsertChannelAgentBinding(
|
||||
cfg: OpenClawConfig,
|
||||
params: { channel: ChannelType; accountId: string; agentId: string },
|
||||
): OpenClawConfig {
|
||||
const channel = normalizeBindingChannel(params.channel);
|
||||
const accountId = params.accountId.trim();
|
||||
const agentId = params.agentId.trim();
|
||||
if (!channel || !accountId || !agentId || accountId === "default") {
|
||||
return cfg;
|
||||
}
|
||||
|
||||
const existing = Array.isArray(cfg.bindings) ? cfg.bindings : [];
|
||||
const filtered = existing.filter((binding) => {
|
||||
const match = binding?.match;
|
||||
return !(
|
||||
binding?.agentId &&
|
||||
typeof match?.channel === "string" &&
|
||||
typeof match?.accountId === "string" &&
|
||||
normalizeBindingChannel(match.channel) === channel &&
|
||||
match.accountId.trim() === accountId
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
...cfg,
|
||||
bindings: [
|
||||
...filtered,
|
||||
{
|
||||
agentId,
|
||||
match: { channel, accountId },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function applySlackConfig(
|
||||
cfg: OpenClawConfig,
|
||||
accountId: string,
|
||||
input: ChannelConfigureParams["config"],
|
||||
probe: ProbeResult,
|
||||
): OpenClawConfig {
|
||||
const botToken = input.botToken?.trim() ?? "";
|
||||
const appToken = input.appToken?.trim() ?? "";
|
||||
const accessMode = input.accessMode === "closed" ? "closed" : "open";
|
||||
const groupAccessMode = input.groupAccessMode === "closed" ? "closed" : "open";
|
||||
const allowFrom = accessMode === "open" ? ["*"] : normalizeSlackAllowFrom(input.allowFrom);
|
||||
const dmPolicy = accessMode === "open" ? "open" : "allowlist";
|
||||
const groupPolicy = groupAccessMode === "open" ? "open" : "allowlist";
|
||||
const dm = { policy: dmPolicy, allowFrom };
|
||||
|
||||
if (accountId === "default") {
|
||||
return {
|
||||
...cfg,
|
||||
channels: {
|
||||
...cfg.channels,
|
||||
slack: {
|
||||
...cfg.channels?.slack,
|
||||
enabled: true,
|
||||
botToken,
|
||||
appToken,
|
||||
dmPolicy,
|
||||
groupPolicy,
|
||||
allowFrom,
|
||||
dm,
|
||||
// Disable block streaming so tool execution traces and intermediate
|
||||
// steps are not posted to Slack — only the final response is sent.
|
||||
blockStreaming: false,
|
||||
...(input.name ? { name: input.name } : {}),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return upsertChannelAgentBinding(
|
||||
{
|
||||
...cfg,
|
||||
channels: {
|
||||
...cfg.channels,
|
||||
slack: {
|
||||
...cfg.channels?.slack,
|
||||
enabled: true,
|
||||
accounts: {
|
||||
...cfg.channels?.slack?.accounts,
|
||||
[accountId]: {
|
||||
...cfg.channels?.slack?.accounts?.[accountId],
|
||||
enabled: true,
|
||||
botToken,
|
||||
appToken,
|
||||
dmPolicy,
|
||||
groupPolicy,
|
||||
allowFrom,
|
||||
dm,
|
||||
// Disable block streaming so tool execution traces and intermediate
|
||||
// steps are not posted to Slack — only the final response is sent.
|
||||
blockStreaming: false,
|
||||
...(input.name ? { name: input.name } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ channel: "slack", accountId, agentId: accountId },
|
||||
);
|
||||
}
|
||||
|
||||
function applyTelegramConfig(
|
||||
cfg: OpenClawConfig,
|
||||
accountId: string,
|
||||
input: ChannelConfigureParams["config"],
|
||||
): OpenClawConfig {
|
||||
const token = (input.token ?? input.botToken ?? "").trim();
|
||||
|
||||
if (accountId === "default") {
|
||||
return {
|
||||
...cfg,
|
||||
channels: {
|
||||
...cfg.channels,
|
||||
telegram: {
|
||||
...cfg.channels?.telegram,
|
||||
enabled: true,
|
||||
botToken: token,
|
||||
dmPolicy: "pairing",
|
||||
...(input.name ? { name: input.name } : {}),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return upsertChannelAgentBinding(
|
||||
{
|
||||
...cfg,
|
||||
channels: {
|
||||
...cfg.channels,
|
||||
telegram: {
|
||||
...cfg.channels?.telegram,
|
||||
enabled: true,
|
||||
accounts: {
|
||||
...cfg.channels?.telegram?.accounts,
|
||||
[accountId]: {
|
||||
...cfg.channels?.telegram?.accounts?.[accountId],
|
||||
enabled: true,
|
||||
botToken: token,
|
||||
dmPolicy: "pairing",
|
||||
...(input.name ? { name: input.name } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ channel: "telegram", accountId, agentId: accountId },
|
||||
);
|
||||
}
|
||||
|
||||
export function createPaziChannelsConfigureHandler(
|
||||
deps: ChannelConfigureDeps,
|
||||
): (ctx: GatewayMethodContext) => Promise<void> {
|
||||
return async ({ params, respond, context }: GatewayMethodContext) => {
|
||||
const validation = validateParams(params);
|
||||
if (!validation.ok || !validation.params) {
|
||||
respondError(respond, ERROR_INVALID_REQUEST, validation.error ?? "invalid params");
|
||||
return;
|
||||
}
|
||||
|
||||
const { channel, config: inputConfig } = validation.params;
|
||||
const rawAccountId = validation.params.accountId?.trim();
|
||||
const accountId = rawAccountId || "default";
|
||||
const timeoutMs = validation.params.timeoutMs ?? 5000;
|
||||
|
||||
let probe: ProbeResult;
|
||||
try {
|
||||
if (channel === "slack") {
|
||||
const token = inputConfig.botToken?.trim() ?? "";
|
||||
// probeSlack validates botToken. appToken validity is verified on channel restart.
|
||||
probe = await deps.probeSlack(token, timeoutMs);
|
||||
} else {
|
||||
const token = (inputConfig.token ?? inputConfig.botToken ?? "").trim();
|
||||
probe = await deps.probeTelegram(token, timeoutMs, undefined);
|
||||
}
|
||||
} catch (err) {
|
||||
respondError(
|
||||
respond,
|
||||
ERROR_UNAVAILABLE,
|
||||
`probe failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!probe.ok) {
|
||||
respondError(respond, ERROR_UNAVAILABLE, probe.error ?? "token probe failed", { probe });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await context.stopChannel(channel, accountId);
|
||||
} catch (err) {
|
||||
respondError(
|
||||
respond,
|
||||
ERROR_UNAVAILABLE,
|
||||
`failed to stop channel: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let cfg = deps.loadConfig();
|
||||
if (channel === "slack") {
|
||||
cfg = applySlackConfig(cfg, accountId, inputConfig, probe);
|
||||
} else {
|
||||
cfg = applyTelegramConfig(cfg, accountId, inputConfig);
|
||||
}
|
||||
await deps.writeConfigFile(cfg);
|
||||
} catch (err) {
|
||||
try {
|
||||
await context.startChannel(channel, accountId);
|
||||
} catch (restartErr) {
|
||||
respondError(
|
||||
respond,
|
||||
ERROR_UNAVAILABLE,
|
||||
`config write failed and restart failed: ${restartErr instanceof Error ? restartErr.message : String(restartErr)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
respondError(
|
||||
respond,
|
||||
ERROR_UNAVAILABLE,
|
||||
`config write failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await context.startChannel(channel, accountId);
|
||||
} catch (err) {
|
||||
respondError(
|
||||
respond,
|
||||
ERROR_UNAVAILABLE,
|
||||
`channel restart failed after config update: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const result: ChannelConfigureResult = {
|
||||
ok: true,
|
||||
channel,
|
||||
accountId,
|
||||
probe,
|
||||
...(channel === "slack" && inputConfig.appId?.trim()
|
||||
? { appId: inputConfig.appId.trim().toUpperCase() }
|
||||
: {}),
|
||||
...(channel === "slack" && probe.team?.id?.trim() ? { teamId: probe.team.id.trim() } : {}),
|
||||
...(channel === "slack"
|
||||
? {
|
||||
dmPolicy: inputConfig.accessMode === "closed" ? "allowlist" : "open",
|
||||
groupPolicy: inputConfig.groupAccessMode === "closed" ? "allowlist" : "open",
|
||||
allowFrom:
|
||||
inputConfig.accessMode === "closed"
|
||||
? normalizeSlackAllowFrom(inputConfig.allowFrom)
|
||||
: ["*"],
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
if (channel === "telegram") {
|
||||
const botUsername = probe.bot?.username?.trim() ?? "";
|
||||
result.onboarding = {
|
||||
mode: "pairing",
|
||||
dmPolicy: "pairing",
|
||||
command: "/start",
|
||||
botUsername: botUsername || undefined,
|
||||
pollingIntervalMs: TELEGRAM_PAIRING_POLL_INTERVAL_MS,
|
||||
...(botUsername
|
||||
? {
|
||||
deepLink: `https://t.me/${encodeURIComponent(botUsername)}`,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
respond(true, result);
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,262 @@
|
||||
import type { PairingRequest } from "../../../src/pairing/pairing-store.js";
|
||||
|
||||
type ChannelType = "telegram";
|
||||
type OpenClawConfig = Record<string, unknown>;
|
||||
|
||||
interface PairingListParams {
|
||||
channel: ChannelType;
|
||||
accountId?: string;
|
||||
}
|
||||
|
||||
interface PairingApproveParams extends PairingListParams {
|
||||
code: string;
|
||||
}
|
||||
|
||||
interface PairingListResult {
|
||||
ok: true;
|
||||
channel: ChannelType;
|
||||
accountId: string;
|
||||
pending: PairingRequestSummary[];
|
||||
}
|
||||
|
||||
interface PairingApproveResult {
|
||||
ok: true;
|
||||
channel: ChannelType;
|
||||
accountId: string;
|
||||
approved: boolean;
|
||||
id?: string;
|
||||
}
|
||||
|
||||
interface PairingRequestSummary {
|
||||
id: string;
|
||||
code: string;
|
||||
createdAt: string;
|
||||
lastSeenAt: string;
|
||||
meta?: {
|
||||
accountId?: string;
|
||||
username?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
senderUserId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
type GatewayErrorShape = {
|
||||
code: string;
|
||||
message: string;
|
||||
};
|
||||
|
||||
interface GatewayMethodContext {
|
||||
params: unknown;
|
||||
respond: (ok: boolean, data?: unknown, error?: GatewayErrorShape) => void;
|
||||
}
|
||||
|
||||
interface PairingHandlersDeps {
|
||||
loadConfig: () => OpenClawConfig;
|
||||
env: NodeJS.ProcessEnv;
|
||||
logWarn: (message: string) => void;
|
||||
listRequests: (params: {
|
||||
channel: ChannelType;
|
||||
accountId: string;
|
||||
env: NodeJS.ProcessEnv;
|
||||
}) => Promise<PairingRequest[]>;
|
||||
approveCode: (params: {
|
||||
channel: ChannelType;
|
||||
accountId: string;
|
||||
code: string;
|
||||
env: NodeJS.ProcessEnv;
|
||||
}) => Promise<{ id: string; entry?: PairingRequest } | null>;
|
||||
notifyApproved: (params: {
|
||||
channelId: ChannelType;
|
||||
id: string;
|
||||
cfg: OpenClawConfig;
|
||||
}) => Promise<void>;
|
||||
}
|
||||
|
||||
const DEFAULT_ACCOUNT_ID = "default";
|
||||
const VALID_CHANNELS: ReadonlySet<string> = new Set(["telegram"]);
|
||||
const ERROR_INVALID_REQUEST = "INVALID_REQUEST";
|
||||
const ERROR_UNAVAILABLE = "UNAVAILABLE";
|
||||
|
||||
function respondError(
|
||||
respond: GatewayMethodContext["respond"],
|
||||
code: string,
|
||||
message: string,
|
||||
payload?: unknown,
|
||||
): void {
|
||||
respond(false, payload, { code, message });
|
||||
}
|
||||
|
||||
function resolveAccountId(raw: unknown): string {
|
||||
// These gateway methods are intentionally account-scoped. Missing/blank account IDs default
|
||||
// to "default" instead of unscoped pairing-store reads.
|
||||
if (typeof raw !== "string") {
|
||||
return DEFAULT_ACCOUNT_ID;
|
||||
}
|
||||
const trimmed = raw.trim();
|
||||
return trimmed || DEFAULT_ACCOUNT_ID;
|
||||
}
|
||||
|
||||
function parseListParams(
|
||||
raw: unknown,
|
||||
): { ok: true; value: PairingListParams } | { ok: false; error: string } {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
return { ok: false, error: "params must be an object" };
|
||||
}
|
||||
const params = raw as Record<string, unknown>;
|
||||
const channel = params.channel === "telegram" ? "telegram" : null;
|
||||
if (!channel || !VALID_CHANNELS.has(channel)) {
|
||||
return { ok: false, error: "channel must be 'telegram'" };
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
channel,
|
||||
accountId: typeof params.accountId === "string" ? params.accountId : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parseApproveParams(
|
||||
raw: unknown,
|
||||
): { ok: true; value: PairingApproveParams } | { ok: false; error: string } {
|
||||
const parsed = parseListParams(raw);
|
||||
if (!parsed.ok) {
|
||||
return parsed;
|
||||
}
|
||||
const params = raw as Record<string, unknown>;
|
||||
const code = typeof params.code === "string" ? params.code.trim() : "";
|
||||
if (!code) {
|
||||
return { ok: false, error: "code is required" };
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
...parsed.value,
|
||||
code,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function summarizePairingRequest(request: PairingRequest): PairingRequestSummary {
|
||||
const meta = request.meta ?? {};
|
||||
return {
|
||||
id: request.id,
|
||||
code: request.code,
|
||||
createdAt: request.createdAt,
|
||||
lastSeenAt: request.lastSeenAt,
|
||||
meta: {
|
||||
accountId: typeof meta.accountId === "string" ? meta.accountId : undefined,
|
||||
username: typeof meta.username === "string" ? meta.username : undefined,
|
||||
firstName: typeof meta.firstName === "string" ? meta.firstName : undefined,
|
||||
lastName: typeof meta.lastName === "string" ? meta.lastName : undefined,
|
||||
senderUserId: typeof meta.senderUserId === "string" ? meta.senderUserId : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createPaziChannelsPairingListHandler(
|
||||
deps: PairingHandlersDeps,
|
||||
): (ctx: GatewayMethodContext) => Promise<void> {
|
||||
return async ({ params, respond }: GatewayMethodContext) => {
|
||||
const parsed = parseListParams(params);
|
||||
if (!parsed.ok) {
|
||||
respondError(respond, ERROR_INVALID_REQUEST, parsed.error);
|
||||
return;
|
||||
}
|
||||
|
||||
const accountId = resolveAccountId(parsed.value.accountId);
|
||||
try {
|
||||
const pending = await deps.listRequests({
|
||||
channel: parsed.value.channel,
|
||||
accountId,
|
||||
env: deps.env,
|
||||
});
|
||||
const result: PairingListResult = {
|
||||
ok: true,
|
||||
channel: parsed.value.channel,
|
||||
accountId,
|
||||
pending: pending.map((entry) => summarizePairingRequest(entry)),
|
||||
};
|
||||
respond(true, result);
|
||||
} catch (err) {
|
||||
respondError(
|
||||
respond,
|
||||
ERROR_UNAVAILABLE,
|
||||
`failed to load pairing requests: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createPaziChannelsPairingApproveHandler(
|
||||
deps: PairingHandlersDeps,
|
||||
): (ctx: GatewayMethodContext) => Promise<void> {
|
||||
return async ({ params, respond }: GatewayMethodContext) => {
|
||||
const parsed = parseApproveParams(params);
|
||||
if (!parsed.ok) {
|
||||
respondError(respond, ERROR_INVALID_REQUEST, parsed.error);
|
||||
return;
|
||||
}
|
||||
|
||||
const accountId = resolveAccountId(parsed.value.accountId);
|
||||
let cfgSnapshot: OpenClawConfig | null = null;
|
||||
try {
|
||||
cfgSnapshot = deps.loadConfig();
|
||||
} catch (err) {
|
||||
deps.logWarn(
|
||||
`pazi.channels.pairing.approve failed to load config snapshot before approval: ${String(err)}`,
|
||||
);
|
||||
}
|
||||
try {
|
||||
const approved = await deps.approveCode({
|
||||
channel: parsed.value.channel,
|
||||
accountId,
|
||||
code: parsed.value.code,
|
||||
env: deps.env,
|
||||
});
|
||||
if (!approved) {
|
||||
const result: PairingApproveResult = {
|
||||
ok: true,
|
||||
channel: parsed.value.channel,
|
||||
accountId,
|
||||
approved: false,
|
||||
};
|
||||
respond(true, result);
|
||||
return;
|
||||
}
|
||||
if (cfgSnapshot) {
|
||||
try {
|
||||
await deps.notifyApproved({
|
||||
channelId: parsed.value.channel,
|
||||
id: approved.id,
|
||||
cfg: cfgSnapshot,
|
||||
});
|
||||
} catch (err) {
|
||||
deps.logWarn(
|
||||
`pazi.channels.pairing.approve notification failed for telegram id=${approved.id}: ${String(err)}`,
|
||||
);
|
||||
// Approval is persisted even when notification back to Telegram fails.
|
||||
}
|
||||
} else {
|
||||
deps.logWarn(
|
||||
`pazi.channels.pairing.approve notification skipped for telegram id=${approved.id} because config snapshot was unavailable`,
|
||||
);
|
||||
}
|
||||
const result: PairingApproveResult = {
|
||||
ok: true,
|
||||
channel: parsed.value.channel,
|
||||
accountId,
|
||||
approved: true,
|
||||
id: approved.id,
|
||||
};
|
||||
respond(true, result);
|
||||
} catch (err) {
|
||||
respondError(
|
||||
respond,
|
||||
ERROR_UNAVAILABLE,
|
||||
`failed to approve pairing request: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,57 @@
|
||||
export type PaziBillingConfig = {
|
||||
apiUrl?: string;
|
||||
proxyPort: number;
|
||||
};
|
||||
|
||||
const DEFAULT_PROXY_PORT = 8765;
|
||||
|
||||
function normalizeString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown): number | undefined {
|
||||
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
|
||||
return Math.floor(value);
|
||||
}
|
||||
if (typeof value === "string" && value.trim().length > 0) {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
if (Number.isFinite(parsed) && parsed > 0) {
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function resolvePaziBillingConfig(params: {
|
||||
pluginConfig?: Record<string, unknown> | null;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
}): PaziBillingConfig {
|
||||
const env = params.env ?? process.env;
|
||||
const raw = params.pluginConfig ?? {};
|
||||
|
||||
const apiUrl = normalizeString(raw.apiUrl) ?? normalizeString(env.PAZI_API_URL);
|
||||
|
||||
const proxyPort =
|
||||
normalizePort(raw.proxyPort) ?? normalizePort(env.PAZI_PROXY_PORT) ?? DEFAULT_PROXY_PORT;
|
||||
|
||||
return {
|
||||
apiUrl,
|
||||
proxyPort,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveGatewayToken(params: {
|
||||
configToken?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
}): string | undefined {
|
||||
const configToken = normalizeString(params.configToken);
|
||||
if (configToken) {
|
||||
return configToken;
|
||||
}
|
||||
const env = params.env ?? process.env;
|
||||
return normalizeString(env.OPENCLAW_GATEWAY_TOKEN);
|
||||
}
|
||||
@ -0,0 +1,50 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
clearProxyContext,
|
||||
getProxyLastActivityAt,
|
||||
isProxyBusyForStatus,
|
||||
markProxyActivity,
|
||||
setProxyContext,
|
||||
} from "./context.js";
|
||||
|
||||
describe("pazi context busy status", () => {
|
||||
beforeEach(() => {
|
||||
clearProxyContext();
|
||||
});
|
||||
|
||||
it("returns not busy when no context has been set", () => {
|
||||
expect(isProxyBusyForStatus(1_000_000)).toBe(false);
|
||||
expect(getProxyLastActivityAt()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns not busy when context exists but there is no activity yet", () => {
|
||||
setProxyContext({
|
||||
userId: "u1",
|
||||
agentId: "a1",
|
||||
proxyToken: "p1",
|
||||
});
|
||||
expect(isProxyBusyForStatus(1_000_000)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns busy when activity is within the 30-minute window", () => {
|
||||
const nowMs = 1_000_000;
|
||||
setProxyContext({
|
||||
userId: "u1",
|
||||
agentId: "a1",
|
||||
proxyToken: "p1",
|
||||
});
|
||||
markProxyActivity(nowMs - 29 * 60 * 1000);
|
||||
expect(isProxyBusyForStatus(nowMs)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns not busy when activity is older than 30 minutes", () => {
|
||||
const nowMs = 1_000_000;
|
||||
setProxyContext({
|
||||
userId: "u1",
|
||||
agentId: "a1",
|
||||
proxyToken: "p1",
|
||||
});
|
||||
markProxyActivity(nowMs - 31 * 60 * 1000);
|
||||
expect(isProxyBusyForStatus(nowMs)).toBe(false);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,38 @@
|
||||
type ProxyContext = {
|
||||
userId: string;
|
||||
agentId: string;
|
||||
proxyToken: string;
|
||||
};
|
||||
|
||||
const STALE_BUSY_AFTER_MS = 30 * 60 * 1000;
|
||||
|
||||
let currentContext: ProxyContext | null = null;
|
||||
let lastProxyActivityAtMs: number | null = null;
|
||||
|
||||
export function getProxyContext(): ProxyContext | null {
|
||||
return currentContext;
|
||||
}
|
||||
|
||||
export function setProxyContext(ctx: ProxyContext): void {
|
||||
currentContext = ctx;
|
||||
}
|
||||
|
||||
export function markProxyActivity(atMs = Date.now()): void {
|
||||
lastProxyActivityAtMs = atMs;
|
||||
}
|
||||
|
||||
export function getProxyLastActivityAt(): number | null {
|
||||
return lastProxyActivityAtMs;
|
||||
}
|
||||
|
||||
export function isProxyBusyForStatus(nowMs = Date.now()): boolean {
|
||||
if (!currentContext || lastProxyActivityAtMs === null) {
|
||||
return false;
|
||||
}
|
||||
return nowMs - lastProxyActivityAtMs <= STALE_BUSY_AFTER_MS;
|
||||
}
|
||||
|
||||
export function clearProxyContext(): void {
|
||||
currentContext = null;
|
||||
lastProxyActivityAtMs = null;
|
||||
}
|
||||
@ -0,0 +1,231 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { ErrorCodes, errorShape } from "../../../../src/gateway/protocol/index.js";
|
||||
import type { GatewayRequestHandler } from "../../../../src/gateway/server-methods/types.js";
|
||||
import {
|
||||
readFileWithinRoot,
|
||||
writeFileWithinRoot,
|
||||
SafeOpenError,
|
||||
} from "../../../../src/infra/fs-safe.js";
|
||||
|
||||
const SCAN_SKIP_DIRS = new Set([".git", "node_modules", ".DS_Store", "__pycache__", ".cache"]);
|
||||
const SCAN_MAX_FILES = 10_000;
|
||||
const SCAN_MAX_DEPTH = 10;
|
||||
|
||||
type ResolvedWorkspace = {
|
||||
agentId: string;
|
||||
workspaceDir: string;
|
||||
};
|
||||
|
||||
type ResolveWorkspace = (agentId: unknown) => ResolvedWorkspace | null;
|
||||
|
||||
async function listFiles(workspaceDir: string) {
|
||||
const files: Array<{
|
||||
name: string;
|
||||
path: string;
|
||||
missing: boolean;
|
||||
size?: number;
|
||||
updatedAtMs?: number;
|
||||
}> = [];
|
||||
|
||||
const resolvedWorkspace = path.resolve(workspaceDir);
|
||||
|
||||
try {
|
||||
await fs.access(resolvedWorkspace);
|
||||
} catch {
|
||||
return files;
|
||||
}
|
||||
|
||||
const queue: Array<{ dir: string; depth: number }> = [{ dir: resolvedWorkspace, depth: 0 }];
|
||||
|
||||
while (queue.length > 0 && files.length < SCAN_MAX_FILES) {
|
||||
const current = queue.shift()!;
|
||||
if (current.depth > SCAN_MAX_DEPTH) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let dirEntries: string[];
|
||||
try {
|
||||
dirEntries = await fs.readdir(current.dir);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const entryName of dirEntries) {
|
||||
if (files.length >= SCAN_MAX_FILES) {
|
||||
break;
|
||||
}
|
||||
if (SCAN_SKIP_DIRS.has(entryName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fullPath = path.join(current.dir, entryName);
|
||||
|
||||
let entryStat: Awaited<ReturnType<typeof fs.lstat>>;
|
||||
try {
|
||||
entryStat = await fs.lstat(fullPath);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entryStat.isDirectory()) {
|
||||
queue.push({ dir: fullPath, depth: current.depth + 1 });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!entryStat.isFile() || entryStat.isSymbolicLink()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
files.push({
|
||||
name: path.relative(resolvedWorkspace, fullPath),
|
||||
path: fullPath,
|
||||
missing: false,
|
||||
size: entryStat.size,
|
||||
updatedAtMs: Math.floor(entryStat.mtimeMs),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
function resolveRequestWorkspace(
|
||||
params: unknown,
|
||||
resolveWorkspace: ResolveWorkspace,
|
||||
): ResolvedWorkspace | null {
|
||||
const agentId =
|
||||
params && typeof params === "object" ? (params as { agentId?: unknown }).agentId : undefined;
|
||||
return resolveWorkspace(agentId);
|
||||
}
|
||||
|
||||
export function createPaziFilesList(resolveWorkspace: ResolveWorkspace): GatewayRequestHandler {
|
||||
return async ({ params, respond }) => {
|
||||
const resolved = resolveRequestWorkspace(params, resolveWorkspace);
|
||||
if (!resolved) {
|
||||
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "unknown agent id"));
|
||||
return;
|
||||
}
|
||||
const files = await listFiles(resolved.workspaceDir);
|
||||
respond(true, {
|
||||
agentId: resolved.agentId,
|
||||
workspace: resolved.workspaceDir,
|
||||
files,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export function createPaziFilesGet(resolveWorkspace: ResolveWorkspace): GatewayRequestHandler {
|
||||
return async ({ params, respond }) => {
|
||||
const resolved = resolveRequestWorkspace(params, resolveWorkspace);
|
||||
if (!resolved) {
|
||||
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "unknown agent id"));
|
||||
return;
|
||||
}
|
||||
const { agentId, workspaceDir } = resolved;
|
||||
const name = typeof params.name === "string" ? params.name.trim() : "";
|
||||
if (!name || name.includes("\0")) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(ErrorCodes.INVALID_REQUEST, `invalid file name "${name}"`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await readFileWithinRoot({
|
||||
rootDir: workspaceDir,
|
||||
relativePath: name,
|
||||
});
|
||||
const filePath = path.join(workspaceDir, name);
|
||||
respond(true, {
|
||||
agentId,
|
||||
workspace: workspaceDir,
|
||||
file: {
|
||||
name,
|
||||
path: filePath,
|
||||
missing: false,
|
||||
size: result.stat.size,
|
||||
updatedAtMs: Math.floor(result.stat.mtimeMs),
|
||||
content: result.buffer.toString("utf-8"),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof SafeOpenError) {
|
||||
if (err.code === "not-found") {
|
||||
respond(true, {
|
||||
agentId,
|
||||
workspace: workspaceDir,
|
||||
file: { name, path: path.join(workspaceDir, name), missing: true },
|
||||
});
|
||||
return;
|
||||
}
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(ErrorCodes.INVALID_REQUEST, `invalid file: ${err.message}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
respond(false, undefined, errorShape(ErrorCodes.UNAVAILABLE, "read_failed"));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createPaziFilesSet(resolveWorkspace: ResolveWorkspace): GatewayRequestHandler {
|
||||
return async ({ params, respond }) => {
|
||||
const resolved = resolveRequestWorkspace(params, resolveWorkspace);
|
||||
if (!resolved) {
|
||||
respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, "unknown agent id"));
|
||||
return;
|
||||
}
|
||||
const { agentId, workspaceDir } = resolved;
|
||||
const name = typeof params.name === "string" ? params.name.trim() : "";
|
||||
if (!name || name.includes("\0")) {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(ErrorCodes.INVALID_REQUEST, `invalid file name "${name}"`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const content = String(params.content ?? "");
|
||||
|
||||
try {
|
||||
await writeFileWithinRoot({
|
||||
rootDir: workspaceDir,
|
||||
relativePath: name,
|
||||
data: content,
|
||||
encoding: "utf8",
|
||||
mkdir: true,
|
||||
});
|
||||
} catch {
|
||||
respond(
|
||||
false,
|
||||
undefined,
|
||||
errorShape(ErrorCodes.INVALID_REQUEST, `unsafe workspace file "${name}"`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.join(workspaceDir, name);
|
||||
let size: number | undefined;
|
||||
let updatedAtMs: number | undefined;
|
||||
try {
|
||||
const stat = await fs.stat(filePath);
|
||||
size = stat.size;
|
||||
updatedAtMs = Math.floor(stat.mtimeMs);
|
||||
} catch {
|
||||
// best effort
|
||||
}
|
||||
|
||||
respond(true, {
|
||||
ok: true,
|
||||
agentId,
|
||||
workspace: workspaceDir,
|
||||
file: { name, path: filePath, missing: false, size, updatedAtMs, content },
|
||||
});
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,233 @@
|
||||
import { resolvePaziBillingConfig } from "../config.js";
|
||||
import { getProxyContext } from "../context.js";
|
||||
|
||||
type ApiParams = {
|
||||
apiUrl: string;
|
||||
proxyToken: string;
|
||||
};
|
||||
|
||||
export type PipedreamApiResult<T> = { ok: true; data: T } | { ok: false; error: string };
|
||||
|
||||
function resolveApiParams(pluginConfig: Record<string, unknown> | null): ApiParams {
|
||||
const context = getProxyContext();
|
||||
if (!context) {
|
||||
throw new Error("No billing context set — workspace may not be initialized yet");
|
||||
}
|
||||
|
||||
const resolved = resolvePaziBillingConfig({ pluginConfig, env: process.env });
|
||||
const apiUrl = resolved.apiUrl?.trim();
|
||||
if (!apiUrl) {
|
||||
throw new Error("PAZI_API_URL not configured");
|
||||
}
|
||||
|
||||
let baseUrl: URL;
|
||||
try {
|
||||
baseUrl = new URL(apiUrl);
|
||||
} catch {
|
||||
throw new Error(`Invalid PAZI_API_URL: ${apiUrl}`);
|
||||
}
|
||||
|
||||
return { apiUrl: baseUrl.toString(), proxyToken: context.proxyToken };
|
||||
}
|
||||
|
||||
function readErrorMessage(payload: unknown): string | undefined {
|
||||
if (!payload) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof payload === "string") {
|
||||
return payload;
|
||||
}
|
||||
if (typeof payload === "object") {
|
||||
const record = payload as { error?: unknown; message?: unknown };
|
||||
if (typeof record.error === "string") {
|
||||
return record.error;
|
||||
}
|
||||
if (typeof record.message === "string") {
|
||||
return record.message;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function readJsonBody(res: Response): Promise<unknown> {
|
||||
const text = await res.text();
|
||||
if (!text.trim()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
async function parseResponse<T>(res: Response): Promise<PipedreamApiResult<T>> {
|
||||
const payload = await readJsonBody(res);
|
||||
if (res.ok) {
|
||||
return { ok: true, data: payload as T };
|
||||
}
|
||||
const message = readErrorMessage(payload) ?? res.statusText ?? "Request failed";
|
||||
const status = res.status ? ` (${res.status})` : "";
|
||||
return { ok: false, error: `Pazi API error${status}: ${message}` };
|
||||
}
|
||||
|
||||
async function fetchWithToken(params: ApiParams, url: URL, init?: RequestInit): Promise<Response> {
|
||||
const headers = new Headers(init?.headers);
|
||||
headers.set("x-proxy-token", params.proxyToken);
|
||||
return await fetch(url, { ...init, headers });
|
||||
}
|
||||
|
||||
async function requestJson<T>(
|
||||
params: ApiParams,
|
||||
url: URL,
|
||||
init?: RequestInit,
|
||||
): Promise<PipedreamApiResult<T>> {
|
||||
const res = await fetchWithToken(params, url, init);
|
||||
return await parseResponse<T>(res);
|
||||
}
|
||||
|
||||
function coerceLimit(limit?: number): number | undefined {
|
||||
if (typeof limit !== "number" || !Number.isFinite(limit) || limit <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
return Math.floor(limit);
|
||||
}
|
||||
|
||||
export async function searchApps(
|
||||
params: { pluginConfig: Record<string, unknown> | null },
|
||||
query: string,
|
||||
limit?: number,
|
||||
): Promise<PipedreamApiResult<unknown>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
const url = new URL("/integrations/apps", apiParams.apiUrl);
|
||||
url.searchParams.set("q", query);
|
||||
const resolvedLimit = coerceLimit(limit);
|
||||
if (resolvedLimit) {
|
||||
url.searchParams.set("limit", String(resolvedLimit));
|
||||
}
|
||||
return await requestJson(apiParams, url);
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function listActions(
|
||||
params: { pluginConfig: Record<string, unknown> | null },
|
||||
app: string,
|
||||
limit?: number,
|
||||
): Promise<PipedreamApiResult<unknown>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
const url = new URL(`/integrations/${encodeURIComponent(app)}/actions`, apiParams.apiUrl);
|
||||
const resolvedLimit = coerceLimit(limit);
|
||||
if (resolvedLimit) {
|
||||
url.searchParams.set("limit", String(resolvedLimit));
|
||||
}
|
||||
return await requestJson(apiParams, url);
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAction(
|
||||
params: { pluginConfig: Record<string, unknown> | null },
|
||||
actionId: string,
|
||||
): Promise<PipedreamApiResult<unknown>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
const url = new URL(`/integrations/actions/${encodeURIComponent(actionId)}`, apiParams.apiUrl);
|
||||
return await requestJson(apiParams, url);
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function configureActionProp(
|
||||
params: { pluginConfig: Record<string, unknown> | null },
|
||||
actionId: string,
|
||||
body: {
|
||||
propName: string;
|
||||
configuredProps?: Record<string, unknown>;
|
||||
query?: string;
|
||||
page?: number;
|
||||
prevContext?: Record<string, unknown>;
|
||||
dynamicPropsId?: string;
|
||||
},
|
||||
): Promise<PipedreamApiResult<unknown>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
const url = new URL(
|
||||
`/integrations/actions/${encodeURIComponent(actionId)}/configure-prop`,
|
||||
apiParams.apiUrl,
|
||||
);
|
||||
return await requestJson(apiParams, url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function reloadActionProps(
|
||||
params: { pluginConfig: Record<string, unknown> | null },
|
||||
actionId: string,
|
||||
body: { configuredProps?: Record<string, unknown>; dynamicPropsId?: string },
|
||||
): Promise<PipedreamApiResult<unknown>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
const url = new URL(
|
||||
`/integrations/actions/${encodeURIComponent(actionId)}/reload-props`,
|
||||
apiParams.apiUrl,
|
||||
);
|
||||
return await requestJson(apiParams, url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkIntegration(
|
||||
params: { pluginConfig: Record<string, unknown> | null },
|
||||
app: string,
|
||||
): Promise<PipedreamApiResult<unknown>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
const url = new URL(`/integrations/accounts/${encodeURIComponent(app)}`, apiParams.apiUrl);
|
||||
const res = await fetchWithToken(apiParams, url, { method: "GET" });
|
||||
if (res.status === 404) {
|
||||
return { ok: true, data: { connected: false } };
|
||||
}
|
||||
return await parseResponse(res);
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function runAction(
|
||||
params: { pluginConfig: Record<string, unknown> | null },
|
||||
app: string,
|
||||
actionId: string,
|
||||
configuredProps?: Record<string, unknown>,
|
||||
): Promise<PipedreamApiResult<unknown>> {
|
||||
try {
|
||||
const apiParams = resolveApiParams(params.pluginConfig);
|
||||
const url = new URL(`/integrations/${encodeURIComponent(app)}/action`, apiParams.apiUrl);
|
||||
const body: { actionId: string; configuredProps?: Record<string, unknown> } = { actionId };
|
||||
if (configuredProps) {
|
||||
body.configuredProps = configuredProps;
|
||||
}
|
||||
return await requestJson(apiParams, url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,806 @@
|
||||
import { Type } from "@sinclair/typebox";
|
||||
import type { AnyAgentTool, OpenClawConfig } from "openclaw/plugin-sdk";
|
||||
import { callGateway } from "../../../../src/gateway/call.js";
|
||||
import {
|
||||
checkIntegration,
|
||||
listActions,
|
||||
getAction,
|
||||
configureActionProp,
|
||||
reloadActionProps,
|
||||
runAction,
|
||||
searchApps,
|
||||
type PipedreamApiResult,
|
||||
} from "./api.js";
|
||||
|
||||
export type PipedreamToolsDeps = {
|
||||
pluginConfig: Record<string, unknown> | null;
|
||||
config: OpenClawConfig;
|
||||
};
|
||||
|
||||
type AgentToolResult = {
|
||||
content: Array<{ type: "text"; text: string }>;
|
||||
details?: unknown;
|
||||
};
|
||||
|
||||
function json(payload: unknown): AgentToolResult {
|
||||
return {
|
||||
content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
|
||||
details: payload,
|
||||
};
|
||||
}
|
||||
|
||||
function readRequiredString(params: Record<string, unknown>, key: string): string {
|
||||
const value = params[key];
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(`${key} required`);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error(`${key} required`);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function readOptionalString(params: Record<string, unknown>, key: string): string | undefined {
|
||||
const value = params[key];
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function readOptionalNumber(params: Record<string, unknown>, key: string): number | undefined {
|
||||
const value = params[key];
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
return undefined;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function coerceLimit(value: number | undefined): number | undefined {
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
return Math.floor(value);
|
||||
}
|
||||
|
||||
function unwrapResult(result: PipedreamApiResult<unknown>): AgentToolResult {
|
||||
if (result.ok) {
|
||||
return json(result.data);
|
||||
}
|
||||
return json({ error: result.error });
|
||||
}
|
||||
|
||||
type ConfigurableProp = {
|
||||
name?: string;
|
||||
type?: string;
|
||||
label?: string;
|
||||
description?: string;
|
||||
optional?: boolean;
|
||||
hidden?: boolean;
|
||||
disabled?: boolean;
|
||||
withLabel?: boolean;
|
||||
remoteOptions?: boolean;
|
||||
useQuery?: boolean;
|
||||
reloadProps?: boolean;
|
||||
};
|
||||
|
||||
type ActionSchemaPayload = {
|
||||
action?: {
|
||||
configurableProps?: ConfigurableProp[];
|
||||
};
|
||||
};
|
||||
|
||||
type LabelValueOption = { label: string; value: unknown };
|
||||
|
||||
function extractActionProps(payload: unknown): ConfigurableProp[] {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
return [];
|
||||
}
|
||||
const data = payload as ActionSchemaPayload;
|
||||
const props = data.action?.configurableProps;
|
||||
return Array.isArray(props) ? props : [];
|
||||
}
|
||||
|
||||
function isLabelValue(value: unknown): value is { label: string; value: unknown } {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
const record = value as { label?: unknown; value?: unknown };
|
||||
return typeof record.label === "string" && "value" in record;
|
||||
}
|
||||
|
||||
function normalizeOptions(payload: unknown): LabelValueOption[] {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
return [];
|
||||
}
|
||||
const record = payload as {
|
||||
options?: Array<
|
||||
{ label?: string; value?: unknown } | { lv?: { label?: string; value?: unknown } }
|
||||
>;
|
||||
stringOptions?: string[];
|
||||
};
|
||||
const options: LabelValueOption[] = [];
|
||||
if (Array.isArray(record.options)) {
|
||||
for (const raw of record.options) {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
continue;
|
||||
}
|
||||
if ("lv" in raw && raw.lv && typeof raw.lv === "object") {
|
||||
const lv = raw.lv as { label?: string; value?: unknown };
|
||||
if (typeof lv.label === "string") {
|
||||
options.push({ label: lv.label, value: lv.value });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const direct = raw as { label?: string; value?: unknown };
|
||||
if (typeof direct.label === "string") {
|
||||
options.push({ label: direct.label, value: direct.value });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(record.stringOptions)) {
|
||||
for (const value of record.stringOptions) {
|
||||
options.push({ label: value, value });
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function matchesType(value: unknown, propType: string): boolean {
|
||||
if (propType === "any" || propType === "object" || propType === "sql") {
|
||||
return true;
|
||||
}
|
||||
if (propType === "string") {
|
||||
return typeof value === "string";
|
||||
}
|
||||
if (propType === "integer") {
|
||||
return typeof value === "number" && Number.isInteger(value);
|
||||
}
|
||||
if (propType === "boolean") {
|
||||
return typeof value === "boolean";
|
||||
}
|
||||
if (propType === "string[]") {
|
||||
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
||||
}
|
||||
if (propType === "integer[]") {
|
||||
return Array.isArray(value) && value.every((item) => typeof item === "number");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function sleep(ms: number, signal?: AbortSignal): Promise<"ok" | "aborted"> {
|
||||
if (signal?.aborted) {
|
||||
return "aborted";
|
||||
}
|
||||
return await new Promise<"ok" | "aborted">((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
resolve("ok");
|
||||
}, ms);
|
||||
if (!signal) {
|
||||
return;
|
||||
}
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
resolve("aborted");
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
export function createPipedreamTools(deps: PipedreamToolsDeps): AnyAgentTool[] {
|
||||
return [
|
||||
{
|
||||
name: "pipedream_find_integrations",
|
||||
label: "Pipedream: Find Integrations",
|
||||
description:
|
||||
"ALWAYS call this FIRST to discover the correct Pipedream app slug. App slugs are often different from expected (e.g. Slack is 'slack_v2', Gmail is 'gmail', etc.). Returns matching apps with their exact slug to use in subsequent calls.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
query: Type.String({ description: "Search query." }),
|
||||
limit: Type.Optional(Type.Number({ description: "Maximum results to return." })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>) {
|
||||
try {
|
||||
const query = readRequiredString(params, "query");
|
||||
const limit = coerceLimit(readOptionalNumber(params, "limit"));
|
||||
const result = await searchApps({ pluginConfig: deps.pluginConfig }, query, limit);
|
||||
return unwrapResult(result);
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pipedream_list_actions",
|
||||
label: "Pipedream: List Actions",
|
||||
description:
|
||||
"List available actions for a Pipedream app. Returns each action's key (use as actionId), name, description, and a basic configuredProps schema (exact property names and types). For full configurableProps metadata (remote options, withLabel, etc.), call pipedream_get_action.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
app: Type.String({ description: "Pipedream app slug." }),
|
||||
limit: Type.Optional(Type.Number({ description: "Maximum results to return." })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>) {
|
||||
try {
|
||||
const app = readRequiredString(params, "app");
|
||||
const limit = coerceLimit(readOptionalNumber(params, "limit"));
|
||||
const result = await listActions({ pluginConfig: deps.pluginConfig }, app, limit);
|
||||
return unwrapResult(result);
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pipedream_get_action",
|
||||
label: "Pipedream: Get Action Schema",
|
||||
description:
|
||||
"Fetch the full configurableProps schema for a specific action. Use this to see required props, remoteOptions, withLabel, and other metadata before calling pipedream_use_integration.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
actionId: Type.String({
|
||||
description: "Action key from pipedream_list_actions (e.g. 'slack_v2-send-message').",
|
||||
}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>) {
|
||||
try {
|
||||
const actionId = readRequiredString(params, "actionId");
|
||||
const result = await getAction({ pluginConfig: deps.pluginConfig }, actionId);
|
||||
return unwrapResult(result);
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pipedream_configure_prop",
|
||||
label: "Pipedream: Configure Prop",
|
||||
description:
|
||||
"Fetch remote options (label/value) for a configurable prop, or validate dynamic props. Use this for props marked remoteOptions/withLabel or when you need to map a human name to an ID.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
actionId: Type.String({
|
||||
description: "Action key from pipedream_list_actions.",
|
||||
}),
|
||||
propName: Type.String({
|
||||
description: "Configurable prop name from pipedream_get_action.",
|
||||
}),
|
||||
configuredProps: Type.Optional(
|
||||
Type.Record(Type.String(), Type.Unknown(), {
|
||||
description:
|
||||
"Current configuredProps values (excluding auth). Used to resolve dependent props.",
|
||||
}),
|
||||
),
|
||||
query: Type.Optional(
|
||||
Type.String({
|
||||
description: "Optional search query for filtering options (if supported).",
|
||||
}),
|
||||
),
|
||||
page: Type.Optional(Type.Number({ description: "Optional page for pagination." })),
|
||||
prevContext: Type.Optional(
|
||||
Type.Record(Type.String(), Type.Unknown(), {
|
||||
description: "Optional context from a previous configureProp call.",
|
||||
}),
|
||||
),
|
||||
dynamicPropsId: Type.Optional(
|
||||
Type.String({
|
||||
description: "Optional dynamicPropsId when props are generated dynamically.",
|
||||
}),
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>) {
|
||||
try {
|
||||
const actionId = readRequiredString(params, "actionId");
|
||||
const propName = readRequiredString(params, "propName");
|
||||
const configuredProps = params.configuredProps;
|
||||
if (
|
||||
configuredProps !== undefined &&
|
||||
(typeof configuredProps !== "object" ||
|
||||
configuredProps === null ||
|
||||
Array.isArray(configuredProps))
|
||||
) {
|
||||
throw new Error("configuredProps must be an object");
|
||||
}
|
||||
const query = readOptionalString(params, "query");
|
||||
const page = readOptionalNumber(params, "page");
|
||||
const prevContext = params.prevContext;
|
||||
if (
|
||||
prevContext !== undefined &&
|
||||
(typeof prevContext !== "object" || prevContext === null || Array.isArray(prevContext))
|
||||
) {
|
||||
throw new Error("prevContext must be an object");
|
||||
}
|
||||
const dynamicPropsId = readOptionalString(params, "dynamicPropsId");
|
||||
|
||||
const result = await configureActionProp({ pluginConfig: deps.pluginConfig }, actionId, {
|
||||
propName,
|
||||
configuredProps: configuredProps as Record<string, unknown> | undefined,
|
||||
query: query ?? undefined,
|
||||
page: page ?? undefined,
|
||||
prevContext: prevContext as Record<string, unknown> | undefined,
|
||||
dynamicPropsId,
|
||||
});
|
||||
return unwrapResult(result);
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pipedream_reload_props",
|
||||
label: "Pipedream: Reload Props",
|
||||
description:
|
||||
"Reload dynamic props after setting dependent values (when a prop has reloadProps=true).",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
actionId: Type.String({ description: "Action key from pipedream_list_actions." }),
|
||||
configuredProps: Type.Optional(
|
||||
Type.Record(Type.String(), Type.Unknown(), {
|
||||
description: "Current configuredProps values (excluding auth).",
|
||||
}),
|
||||
),
|
||||
dynamicPropsId: Type.Optional(Type.String({ description: "Dynamic props ID." })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>) {
|
||||
try {
|
||||
const actionId = readRequiredString(params, "actionId");
|
||||
const configuredProps = params.configuredProps;
|
||||
if (
|
||||
configuredProps !== undefined &&
|
||||
(typeof configuredProps !== "object" ||
|
||||
configuredProps === null ||
|
||||
Array.isArray(configuredProps))
|
||||
) {
|
||||
throw new Error("configuredProps must be an object");
|
||||
}
|
||||
const dynamicPropsId = readOptionalString(params, "dynamicPropsId");
|
||||
|
||||
const result = await reloadActionProps({ pluginConfig: deps.pluginConfig }, actionId, {
|
||||
configuredProps: configuredProps as Record<string, unknown> | undefined,
|
||||
dynamicPropsId: dynamicPropsId ?? undefined,
|
||||
});
|
||||
return unwrapResult(result);
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pipedream_check_integration",
|
||||
label: "Pipedream: Check Integration",
|
||||
description:
|
||||
"Check whether a Pipedream app is connected. Use the exact app slug from pipedream_find_integrations. Returns {connected: true, accountId} if connected.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
app: Type.String({
|
||||
description:
|
||||
"Pipedream app slug from pipedream_find_integrations (e.g. 'slack_v2', not 'slack').",
|
||||
}),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>) {
|
||||
try {
|
||||
const app = readRequiredString(params, "app");
|
||||
const result = await checkIntegration({ pluginConfig: deps.pluginConfig }, app);
|
||||
if (result.ok) {
|
||||
const data =
|
||||
result.data && typeof result.data === "object"
|
||||
? (result.data as { connected?: unknown })
|
||||
: undefined;
|
||||
if (data?.connected !== true) {
|
||||
return json({
|
||||
...data,
|
||||
hint: `App "${app}" is not connected. Did you use the correct slug? Call pipedream_find_integrations to discover the exact Pipedream slug (e.g. Slack is "slack_v2", not "slack").`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return unwrapResult(result);
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pipedream_use_integration",
|
||||
label: "Pipedream: Use Integration",
|
||||
description:
|
||||
"Run a Pipedream action. IMPORTANT: Use pipedream_list_actions to discover actionId and pipedream_get_action to fetch the full configurableProps schema. This tool validates your configuredProps and will reject calls with missing/unknown props. Do NOT guess property names — use the schema. Do NOT include auth/app props — authentication is automatic. For props with remoteOptions/withLabel, use pipedream_configure_prop to fetch options.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
app: Type.String({ description: "Pipedream app slug." }),
|
||||
actionId: Type.String({
|
||||
description: "Action key from pipedream_list_actions (e.g. 'slack_v2-send-message').",
|
||||
}),
|
||||
configuredProps: Type.Optional(
|
||||
Type.Record(Type.String(), Type.Unknown(), {
|
||||
description:
|
||||
"Action properties. Keys and types MUST match the configurableProps schema returned by pipedream_get_action.",
|
||||
}),
|
||||
),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>) {
|
||||
try {
|
||||
const app = readRequiredString(params, "app");
|
||||
const actionId = readRequiredString(params, "actionId");
|
||||
const configuredProps = params.configuredProps;
|
||||
if (
|
||||
configuredProps !== undefined &&
|
||||
(typeof configuredProps !== "object" ||
|
||||
configuredProps === null ||
|
||||
Array.isArray(configuredProps))
|
||||
) {
|
||||
throw new Error("configuredProps must be an object");
|
||||
}
|
||||
const props = (configuredProps as Record<string, unknown> | undefined) ?? {};
|
||||
const resolvedProps: Record<string, unknown> = { ...props };
|
||||
|
||||
// Validate configuredProps against full action schema
|
||||
const actionResult = await getAction({ pluginConfig: deps.pluginConfig }, actionId);
|
||||
if (!actionResult.ok) {
|
||||
return json({
|
||||
error: actionResult.error,
|
||||
hint: "Failed to fetch action schema. Try pipedream_get_action again before calling pipedream_use_integration.",
|
||||
});
|
||||
}
|
||||
|
||||
const actionProps = extractActionProps(actionResult.data);
|
||||
const authPropNames = actionProps
|
||||
.filter((p) => p.type === "app" && typeof p.name === "string")
|
||||
.map((p) => p.name as string);
|
||||
|
||||
const expectedProps = actionProps.filter((p) => {
|
||||
if (!p.name || typeof p.name !== "string") {
|
||||
return false;
|
||||
}
|
||||
if (p.type === "app") {
|
||||
return false;
|
||||
}
|
||||
if (p.hidden === true || p.disabled === true) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const tryResolveValue = async (
|
||||
prop: ConfigurableProp,
|
||||
value: unknown,
|
||||
): Promise<
|
||||
{ ok: true; value: unknown } | { ok: false; error: string; options?: string[] }
|
||||
> => {
|
||||
if (!prop.name || typeof prop.name !== "string") {
|
||||
return { ok: true, value };
|
||||
}
|
||||
if (isLabelValue(value)) {
|
||||
return { ok: true, value };
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
const resolvedValues: unknown[] = [];
|
||||
for (const item of value) {
|
||||
if (isLabelValue(item)) {
|
||||
resolvedValues.push(item);
|
||||
continue;
|
||||
}
|
||||
if (typeof item !== "string") {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Prop "${prop.name}" expects label/value objects; got non-string array item.`,
|
||||
};
|
||||
}
|
||||
const lookup = await configureActionProp(
|
||||
{ pluginConfig: deps.pluginConfig },
|
||||
actionId,
|
||||
{
|
||||
propName: prop.name,
|
||||
configuredProps: resolvedProps,
|
||||
query: prop.useQuery ? item : undefined,
|
||||
},
|
||||
);
|
||||
if (!lookup.ok) {
|
||||
return { ok: false, error: lookup.error };
|
||||
}
|
||||
const options = normalizeOptions(lookup.data);
|
||||
const match = options.filter(
|
||||
(opt) =>
|
||||
opt.label.toLowerCase() === item.toLowerCase() ||
|
||||
String(opt.value ?? "").toLowerCase() === item.toLowerCase(),
|
||||
);
|
||||
if (match.length !== 1) {
|
||||
return {
|
||||
ok: false,
|
||||
error:
|
||||
match.length === 0
|
||||
? `No option found for "${item}" in prop "${prop.name}".`
|
||||
: `Multiple options found for "${item}" in prop "${prop.name}".`,
|
||||
options: options.slice(0, 5).map((opt) => opt.label),
|
||||
};
|
||||
}
|
||||
const selected = match[0];
|
||||
const selectedValue = selected.value ?? selected.label;
|
||||
const resolved = prop.withLabel
|
||||
? { label: selected.label, value: selectedValue }
|
||||
: selectedValue;
|
||||
resolvedValues.push(resolved);
|
||||
}
|
||||
return { ok: true, value: resolvedValues };
|
||||
}
|
||||
if (typeof value !== "string") {
|
||||
return { ok: true, value };
|
||||
}
|
||||
|
||||
const lookup = await configureActionProp(
|
||||
{ pluginConfig: deps.pluginConfig },
|
||||
actionId,
|
||||
{
|
||||
propName: prop.name,
|
||||
configuredProps: resolvedProps,
|
||||
query: prop.useQuery ? value : undefined,
|
||||
},
|
||||
);
|
||||
if (!lookup.ok) {
|
||||
return { ok: false, error: lookup.error };
|
||||
}
|
||||
const options = normalizeOptions(lookup.data);
|
||||
const match = options.filter(
|
||||
(opt) =>
|
||||
opt.label.toLowerCase() === value.toLowerCase() ||
|
||||
String(opt.value ?? "").toLowerCase() === value.toLowerCase(),
|
||||
);
|
||||
if (match.length !== 1) {
|
||||
return {
|
||||
ok: false,
|
||||
error:
|
||||
match.length === 0
|
||||
? `No option found for "${value}" in prop "${prop.name}".`
|
||||
: `Multiple options found for "${value}" in prop "${prop.name}".`,
|
||||
options: options.slice(0, 5).map((opt) => opt.label),
|
||||
};
|
||||
}
|
||||
const selected = match[0];
|
||||
const selectedValue = selected.value ?? selected.label;
|
||||
const resolved = prop.withLabel
|
||||
? { label: selected.label, value: selectedValue }
|
||||
: selectedValue;
|
||||
return { ok: true, value: resolved };
|
||||
};
|
||||
|
||||
// Auto-resolve remote options when needed
|
||||
const resolutionErrors: Array<{ prop: string; error: string; options?: string[] }> = [];
|
||||
for (const prop of expectedProps) {
|
||||
if (!prop.name || typeof prop.name !== "string") {
|
||||
continue;
|
||||
}
|
||||
if (!(prop.name in resolvedProps)) {
|
||||
continue;
|
||||
}
|
||||
const value = resolvedProps[prop.name];
|
||||
if (value === undefined || value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const needsRemote =
|
||||
prop.remoteOptions === true || prop.useQuery === true || prop.withLabel === true;
|
||||
const needsLabel =
|
||||
prop.withLabel === true &&
|
||||
!(isLabelValue(value) || (Array.isArray(value) && value.every(isLabelValue)));
|
||||
|
||||
if (needsRemote || needsLabel) {
|
||||
const resolved = await tryResolveValue(prop, value);
|
||||
if (!resolved.ok) {
|
||||
resolutionErrors.push({
|
||||
prop: prop.name,
|
||||
error: resolved.error,
|
||||
options: resolved.options,
|
||||
});
|
||||
} else {
|
||||
resolvedProps[prop.name] = resolved.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (resolutionErrors.length > 0) {
|
||||
return json({
|
||||
error: "Unable to resolve remote options for one or more props.",
|
||||
details: resolutionErrors,
|
||||
hint: "Call pipedream_configure_prop to fetch options and pass { label, value } for withLabel props.",
|
||||
});
|
||||
}
|
||||
|
||||
const expectedNames = new Set(
|
||||
expectedProps.map((p) => (typeof p.name === "string" ? p.name : "")).filter(Boolean),
|
||||
);
|
||||
const requiredProps = expectedProps.filter((p) => p.optional !== true);
|
||||
const providedNames = new Set(
|
||||
Object.entries(resolvedProps)
|
||||
.filter(([_, value]) => value !== undefined && value !== null)
|
||||
.map(([name]) => name),
|
||||
);
|
||||
for (const authName of authPropNames) {
|
||||
providedNames.delete(authName);
|
||||
}
|
||||
|
||||
const missingRequired = requiredProps
|
||||
.filter((p) => p.name && !providedNames.has(p.name))
|
||||
.map((p) => p.name);
|
||||
const unrecognized = [...providedNames].filter((n) => !expectedNames.has(n));
|
||||
|
||||
const typeErrors = expectedProps
|
||||
.filter((p) => p.name && providedNames.has(p.name))
|
||||
.map((p) => {
|
||||
const value = resolvedProps[p.name as string];
|
||||
if (
|
||||
p.withLabel &&
|
||||
(isLabelValue(value) || (Array.isArray(value) && value.every(isLabelValue)))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (!p.type) {
|
||||
return null;
|
||||
}
|
||||
if (!matchesType(value, p.type)) {
|
||||
return { name: p.name, expectedType: p.type };
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
if (missingRequired.length > 0 || unrecognized.length > 0 || typeErrors.length > 0) {
|
||||
return json({
|
||||
error: "Invalid configuredProps.",
|
||||
missingRequired: missingRequired.length > 0 ? missingRequired : undefined,
|
||||
unrecognized: unrecognized.length > 0 ? unrecognized : undefined,
|
||||
typeErrors: typeErrors.length > 0 ? typeErrors : undefined,
|
||||
expectedProps: expectedProps.map((p) => ({
|
||||
name: p.name,
|
||||
type: p.type,
|
||||
description: p.description ?? p.label,
|
||||
required: p.optional !== true,
|
||||
remoteOptions: p.remoteOptions === true ? true : undefined,
|
||||
withLabel: p.withLabel === true ? true : undefined,
|
||||
useQuery: p.useQuery === true ? true : undefined,
|
||||
})),
|
||||
hint: "Use the exact property names and types from the expectedProps list above. For remote options, call pipedream_configure_prop to get label/value entries.",
|
||||
});
|
||||
}
|
||||
|
||||
const authPropProvided = authPropNames.filter((name) =>
|
||||
Object.prototype.hasOwnProperty.call(resolvedProps, name),
|
||||
);
|
||||
if (authPropProvided.length > 0) {
|
||||
return json({
|
||||
error: "Do not include auth/app props in configuredProps.",
|
||||
authProps: authPropProvided,
|
||||
hint: "Remove auth props; authentication is added automatically.",
|
||||
});
|
||||
}
|
||||
|
||||
const result = await runAction(
|
||||
{ pluginConfig: deps.pluginConfig },
|
||||
app,
|
||||
actionId,
|
||||
Object.keys(resolvedProps).length > 0 ? resolvedProps : undefined,
|
||||
);
|
||||
if (result.ok) {
|
||||
return json({
|
||||
...(result.data as Record<string, unknown>),
|
||||
_request: { app, actionId, configuredProps: resolvedProps },
|
||||
note:
|
||||
(result.data as { result?: unknown })?.result === null
|
||||
? "Action returned null result. This can be normal, but verify the message was delivered."
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
return json({
|
||||
error: result.error,
|
||||
_request: { app, actionId, configuredProps: resolvedProps },
|
||||
});
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pipedream_request_integration",
|
||||
label: "Pipedream: Request Integration",
|
||||
description:
|
||||
"Prompt the user's UI to connect a Pipedream integration. Only use this AFTER check_integration returns connected=false. This opens an OAuth dialog in the frontend.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
app: Type.String({ description: "Pipedream app slug." }),
|
||||
message: Type.Optional(Type.String({ description: "Optional message to display." })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>) {
|
||||
try {
|
||||
const app = readRequiredString(params, "app");
|
||||
const message = readOptionalString(params, "message");
|
||||
const result = await callGateway({
|
||||
method: "pazi.integration.emit",
|
||||
params: { action: "required", app, message },
|
||||
config: deps.config,
|
||||
});
|
||||
return json(result);
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pipedream_wait_for_connection",
|
||||
label: "Pipedream: Wait For Connection",
|
||||
description:
|
||||
"Poll until a Pipedream integration is connected. Use after request_integration to wait for the user to complete the OAuth flow.",
|
||||
parameters: Type.Object(
|
||||
{
|
||||
app: Type.String({ description: "Pipedream app slug." }),
|
||||
timeoutMs: Type.Optional(
|
||||
Type.Number({ description: "Total time to wait before timing out." }),
|
||||
),
|
||||
pollIntervalMs: Type.Optional(Type.Number({ description: "Delay between polls." })),
|
||||
},
|
||||
{ additionalProperties: false },
|
||||
),
|
||||
async execute(_toolCallId: string, params: Record<string, unknown>, signal?: AbortSignal) {
|
||||
try {
|
||||
const app = readRequiredString(params, "app");
|
||||
const timeoutMs = readOptionalNumber(params, "timeoutMs");
|
||||
const pollIntervalMs = readOptionalNumber(params, "pollIntervalMs");
|
||||
const resolvedTimeoutMs =
|
||||
typeof timeoutMs === "number" && timeoutMs > 0 ? timeoutMs : 120_000;
|
||||
const resolvedPollMs =
|
||||
typeof pollIntervalMs === "number" && pollIntervalMs > 0 ? pollIntervalMs : 3_000;
|
||||
const deadline = Date.now() + resolvedTimeoutMs;
|
||||
|
||||
while (true) {
|
||||
if (signal?.aborted) {
|
||||
return json({ status: "aborted" });
|
||||
}
|
||||
|
||||
const result = await checkIntegration({ pluginConfig: deps.pluginConfig }, app);
|
||||
if (!result.ok) {
|
||||
return json({ error: result.error });
|
||||
}
|
||||
|
||||
const payload =
|
||||
result.data && typeof result.data === "object"
|
||||
? (result.data as { connected?: unknown; accountId?: unknown })
|
||||
: undefined;
|
||||
if (payload?.connected === true) {
|
||||
const accountId =
|
||||
typeof payload.accountId === "string" ? payload.accountId : undefined;
|
||||
return json({ status: "connected", accountId });
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
if (now >= deadline) {
|
||||
return json({ status: "timeout" });
|
||||
}
|
||||
|
||||
const waitMs = Math.min(resolvedPollMs, deadline - now);
|
||||
const slept = await sleep(waitMs, signal);
|
||||
if (slept === "aborted") {
|
||||
return json({ status: "aborted" });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@ -0,0 +1,76 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
|
||||
import { resolveGatewayToken } from "../config.js";
|
||||
import { setProxyContext } from "../context.js";
|
||||
|
||||
type JsonBody = {
|
||||
userId?: string;
|
||||
agentId?: string;
|
||||
proxyToken?: string;
|
||||
};
|
||||
|
||||
type ContextHandlerDeps = {
|
||||
configToken?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
logger: OpenClawPluginApi["logger"];
|
||||
};
|
||||
|
||||
function writeJson(res: ServerResponse, status: number, body: unknown) {
|
||||
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
async function readJsonBody(req: IncomingMessage): Promise<JsonBody | null> {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) {
|
||||
if (typeof chunk === "string") {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
} else {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(Buffer.concat(chunks).toString());
|
||||
if (parsed && typeof parsed === "object") {
|
||||
return parsed as JsonBody;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function createPaziContextHandler(deps: ContextHandlerDeps) {
|
||||
return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
||||
const gatewayToken = resolveGatewayToken({
|
||||
configToken: deps.configToken,
|
||||
env: deps.env,
|
||||
});
|
||||
if (!gatewayToken) {
|
||||
deps.logger.warn("pazi context request rejected: gateway token missing");
|
||||
writeJson(res, 500, { error: "gateway_token_missing" });
|
||||
return;
|
||||
}
|
||||
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader !== `Bearer ${gatewayToken}`) {
|
||||
writeJson(res, 401, { error: "unauthorized" });
|
||||
return;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(req);
|
||||
if (!body) {
|
||||
writeJson(res, 400, { error: "invalid JSON" });
|
||||
return;
|
||||
}
|
||||
|
||||
const { userId, agentId, proxyToken } = body;
|
||||
if (!userId || !agentId || !proxyToken) {
|
||||
writeJson(res, 400, { error: "missing userId, agentId, or proxyToken" });
|
||||
return;
|
||||
}
|
||||
|
||||
setProxyContext({ userId, agentId, proxyToken });
|
||||
writeJson(res, 200, { ok: true });
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,128 @@
|
||||
import http from "node:http";
|
||||
import type { IncomingHttpHeaders } from "node:http";
|
||||
import https from "node:https";
|
||||
import { getProxyContext, markProxyActivity } from "../context.js";
|
||||
|
||||
type ProxyLogger = {
|
||||
info: (message: string) => void;
|
||||
warn: (message: string) => void;
|
||||
};
|
||||
|
||||
type ProxyServer = http.Server;
|
||||
|
||||
type HttpRequest = typeof http.request;
|
||||
|
||||
type ProxyError = { error: string; message?: string };
|
||||
|
||||
type StartProxyParams = {
|
||||
apiUrl?: string;
|
||||
port: number;
|
||||
logger: ProxyLogger;
|
||||
};
|
||||
|
||||
function requestForUrl(url: URL): HttpRequest {
|
||||
return url.protocol === "https:" ? https.request : http.request;
|
||||
}
|
||||
|
||||
function pickAnthropicHeaders(incoming: IncomingHttpHeaders): Record<string, string> {
|
||||
const forward: Record<string, string> = {};
|
||||
const passthrough = ["anthropic-version", "anthropic-beta", "accept", "content-type"] as const;
|
||||
for (const key of passthrough) {
|
||||
const value = incoming[key];
|
||||
if (typeof value === "string") {
|
||||
forward[key] = value;
|
||||
}
|
||||
}
|
||||
return forward;
|
||||
}
|
||||
|
||||
function writeJson(res: http.ServerResponse, status: number, body: ProxyError) {
|
||||
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
export async function startPaziProxy(params: StartProxyParams): Promise<ProxyServer | null> {
|
||||
const apiUrl = params.apiUrl?.trim();
|
||||
if (!apiUrl) {
|
||||
params.logger.info("pazi proxy disabled (PAZI_API_URL not set)");
|
||||
return null;
|
||||
}
|
||||
|
||||
let baseUrl: URL;
|
||||
try {
|
||||
baseUrl = new URL(apiUrl);
|
||||
} catch {
|
||||
params.logger.warn(`pazi proxy disabled (invalid PAZI_API_URL: ${apiUrl})`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (req.method !== "POST" || !req.url?.startsWith("/v1/messages")) {
|
||||
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
||||
res.end("Not Found");
|
||||
return;
|
||||
}
|
||||
|
||||
const context = getProxyContext();
|
||||
if (!context) {
|
||||
writeJson(res, 503, { error: "no billing context set" });
|
||||
return;
|
||||
}
|
||||
markProxyActivity();
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) {
|
||||
if (typeof chunk === "string") {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
} else {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
}
|
||||
const body = Buffer.concat(chunks);
|
||||
|
||||
const target = new URL("/anthropic/v1/messages", baseUrl);
|
||||
const doRequest = requestForUrl(target);
|
||||
|
||||
const proxyReq = doRequest(
|
||||
target,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
...pickAnthropicHeaders(req.headers),
|
||||
"X-Proxy-Token": context.proxyToken,
|
||||
"X-User-Id": context.userId,
|
||||
},
|
||||
},
|
||||
(proxyRes) => {
|
||||
res.writeHead(proxyRes.statusCode || 500, proxyRes.headers);
|
||||
proxyRes.pipe(res);
|
||||
},
|
||||
);
|
||||
|
||||
proxyReq.on("error", (err: Error) => {
|
||||
params.logger.warn(`pazi proxy error: ${String(err)}`);
|
||||
if (!res.headersSent) {
|
||||
writeJson(res, 502, { error: "proxy_error", message: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
proxyReq.write(body);
|
||||
proxyReq.end();
|
||||
});
|
||||
|
||||
server.on("clientError", (err, socket) => {
|
||||
params.logger.warn(`pazi proxy client error: ${String(err)}`);
|
||||
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(params.port, "127.0.0.1", () => {
|
||||
server.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
params.logger.info(`pazi proxy listening on 127.0.0.1:${params.port}`);
|
||||
return server;
|
||||
}
|
||||
@ -0,0 +1,109 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { homedir } from "node:os";
|
||||
import { join, extname, basename } from "node:path";
|
||||
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
|
||||
import { resolveGatewayToken } from "../config.js";
|
||||
|
||||
type UploadFile = {
|
||||
name: string;
|
||||
content: string; // base64
|
||||
mimeType: string;
|
||||
};
|
||||
|
||||
type UploadBody = {
|
||||
files?: UploadFile[];
|
||||
};
|
||||
|
||||
type UploadHandlerDeps = {
|
||||
configToken?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
logger: OpenClawPluginApi["logger"];
|
||||
};
|
||||
|
||||
function writeJson(res: ServerResponse, status: number, body: unknown) {
|
||||
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
async function readJsonBody(req: IncomingMessage): Promise<UploadBody | null> {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) {
|
||||
if (typeof chunk === "string") {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
} else {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(Buffer.concat(chunks).toString());
|
||||
if (parsed && typeof parsed === "object") {
|
||||
return parsed as UploadBody;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Resolve a unique path, appending -1, -2, etc. on collision. */
|
||||
function uniquePath(dir: string, name: string): string {
|
||||
const ext = extname(name);
|
||||
const base = basename(name, ext);
|
||||
let candidate = join(dir, name);
|
||||
let counter = 0;
|
||||
while (existsSync(candidate)) {
|
||||
counter++;
|
||||
candidate = join(dir, `${base}-${String(counter)}${ext}`);
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
export function createPaziUploadHandler(deps: UploadHandlerDeps) {
|
||||
return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
||||
const gatewayToken = resolveGatewayToken({
|
||||
configToken: deps.configToken,
|
||||
env: deps.env,
|
||||
});
|
||||
if (!gatewayToken) {
|
||||
deps.logger.warn("pazi upload request rejected: gateway token missing");
|
||||
writeJson(res, 500, { error: "gateway_token_missing" });
|
||||
return;
|
||||
}
|
||||
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader !== `Bearer ${gatewayToken}`) {
|
||||
writeJson(res, 401, { error: "unauthorized" });
|
||||
return;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(req);
|
||||
if (!body) {
|
||||
writeJson(res, 400, { error: "invalid JSON" });
|
||||
return;
|
||||
}
|
||||
|
||||
const { files } = body;
|
||||
if (!Array.isArray(files) || files.length === 0) {
|
||||
writeJson(res, 400, { error: "no files provided" });
|
||||
return;
|
||||
}
|
||||
|
||||
const uploadDir = join(homedir(), "Desktop", "agent");
|
||||
await mkdir(uploadDir, { recursive: true });
|
||||
|
||||
const paths: string[] = [];
|
||||
for (const file of files) {
|
||||
if (!file.name || !file.content) {
|
||||
continue;
|
||||
}
|
||||
const filePath = uniquePath(uploadDir, file.name);
|
||||
await writeFile(filePath, Buffer.from(file.content, "base64"));
|
||||
paths.push(filePath);
|
||||
}
|
||||
|
||||
deps.logger.info(`pazi upload: wrote ${String(paths.length)} file(s) to ${uploadDir}`);
|
||||
writeJson(res, 200, { paths });
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
---
|
||||
name: slack-setup
|
||||
description: Use when the user wants to set up, connect, or integrate Slack with their agent. This skill triggers the interactive Slack setup form in the dashboard chat.
|
||||
metadata: { "openclaw": { "emoji": "🔧" } }
|
||||
---
|
||||
|
||||
# Slack Integration Setup
|
||||
|
||||
## When to use
|
||||
|
||||
Use this skill when the user asks to:
|
||||
|
||||
- Set up Slack integration
|
||||
- Connect their agent to Slack
|
||||
- Configure a Slack bot for their agent
|
||||
- Integrate Slack with Pazi
|
||||
|
||||
## How it works
|
||||
|
||||
The Pazi dashboard supports inline interactive commands. When you output a special command marker in your response, the dashboard renders the corresponding interactive UI component directly in the chat.
|
||||
|
||||
## Command
|
||||
|
||||
### Show the Slack setup form
|
||||
|
||||
Output the following command marker on its own line to trigger the interactive Slack setup form in the chat:
|
||||
|
||||
```
|
||||
PAZI_COMMAND:SLACK_SETUP
|
||||
```
|
||||
|
||||
The dashboard will replace this marker with a full interactive Slack setup form that guides the user through:
|
||||
|
||||
1. Creating a Slack app at api.slack.com/apps
|
||||
2. Copying the pre-generated app manifest
|
||||
3. Entering the App ID, App Token, and Bot Token
|
||||
4. Configuring access controls (open/closed DM policy, group access)
|
||||
5. Connecting the bot
|
||||
|
||||
After the user submits the form, the gateway automatically restarts to apply the channel changes.
|
||||
|
||||
If the user sends a new message instead of filling the form, the form is automatically dismissed and normal conversation continues.
|
||||
|
||||
## Default Slack behavior
|
||||
|
||||
Once connected, the agent behaves as follows by default. Communicate these defaults to the user so they know what to expect:
|
||||
|
||||
- **Thread replies**: The agent always responds in a Slack thread. When someone messages the bot (DM or channel mention), the reply appears as a threaded reply to the original message, keeping conversations organized.
|
||||
- **Channel access**: The agent can read and respond in any channel it has been added to. Users can invite the bot to channels and mention it with `@BotName` to interact.
|
||||
- **Group access (default: open)**: The bot can respond in channels and group DMs when mentioned. This is configurable via the setup form.
|
||||
- **DM access (default: open)**: Any Slack user in the workspace can DM the bot. This can be restricted to specific Slack user IDs via the setup form.
|
||||
|
||||
## Example conversation
|
||||
|
||||
**User:** I want to connect my agent to Slack
|
||||
|
||||
**Agent response:**
|
||||
|
||||
```
|
||||
I'll help you set up Slack integration! I'm opening the setup form for you now. Follow the step-by-step instructions to create your Slack app and connect it.
|
||||
|
||||
Once connected, your agent will:
|
||||
- Reply in Slack threads to keep conversations organized
|
||||
- Respond in any channel it's added to when mentioned
|
||||
|
||||
PAZI_COMMAND:SLACK_SETUP
|
||||
```
|
||||
|
||||
## Important notes
|
||||
|
||||
- Always provide a brief explanation before outputting the command marker
|
||||
- The command marker must appear exactly as shown: `PAZI_COMMAND:SLACK_SETUP`
|
||||
- Only output ONE command per message
|
||||
- After `PAZI_COMMAND:SLACK_SETUP`, do not add further text — the form will appear where the marker is
|
||||
@ -0,0 +1,47 @@
|
||||
[supervisord]
|
||||
nodaemon=true
|
||||
user=root
|
||||
logfile=/var/log/supervisord.log
|
||||
pidfile=/var/run/supervisord.pid
|
||||
|
||||
[program:xvfb]
|
||||
command=Xvfb :1 -screen 0 1920x1080x24
|
||||
autorestart=true
|
||||
priority=10
|
||||
|
||||
[program:xfce4]
|
||||
command=bash -c "sleep 2 && DISPLAY=:1 dbus-launch --exit-with-session startxfce4"
|
||||
user=pazi
|
||||
environment=HOME="/home/pazi",DISPLAY=":1"
|
||||
autorestart=true
|
||||
priority=20
|
||||
|
||||
[program:chromium]
|
||||
command=bash -c "sleep 5 && chromium --no-sandbox --no-first-run --no-default-browser-check --disable-infobars --display=:1"
|
||||
user=pazi
|
||||
environment=HOME="/home/pazi",DISPLAY=":1"
|
||||
autorestart=false
|
||||
priority=25
|
||||
|
||||
[program:selkies]
|
||||
command=bash -c "sleep 3 && /opt/selkies/selkies-gstreamer/selkies-gstreamer-run --addr=0.0.0.0 --port=8080 --web_root=/opt/selkies/selkies-gstreamer/share/selkies-web --enable_https=false --encoder=x264enc --enable_resize=false --enable_basic_auth=false"
|
||||
environment=DISPLAY=":1",XDG_RUNTIME_DIR="/tmp",PIPEWIRE_LATENCY="128/48000",PULSE_RUNTIME_PATH="/tmp/pulse",PULSE_SERVER="unix:/tmp/pulse/native"
|
||||
autorestart=true
|
||||
priority=30
|
||||
|
||||
[program:desktop-preview]
|
||||
command=bash -c "sleep 10 && while true; do scrot -q 40 /tmp/preview-new.jpg && mv -f /tmp/preview-new.jpg /opt/selkies/selkies-gstreamer/share/selkies-web/preview.jpg; sleep 60; done"
|
||||
environment=DISPLAY=":1"
|
||||
autorestart=true
|
||||
priority=35
|
||||
|
||||
[program:agent]
|
||||
command=bash -c "sleep 8 && exec node /app/openclaw.mjs gateway --allow-unconfigured --bind lan --port 12420"
|
||||
user=pazi
|
||||
environment=HOME="/home/pazi",DISPLAY=":1",NODE_ENV="production"
|
||||
autorestart=true
|
||||
priority=50
|
||||
stdout_logfile=/dev/stdout
|
||||
stdout_logfile_maxbytes=0
|
||||
stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
Loading…
Reference in New Issue