Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(openclaw): support connecting to existing OpenClaw gateway (#3260) [MUL-3158] (#3664)

YOMXXX34d4cd3a28b5
diff --git a/packages/core/agents/index.ts b/packages/core/agents/index.ts
index 486db14902..dccc9520a9 100644
--- a/packages/core/agents/index.ts
+++ b/packages/core/agents/index.ts
@@ -8,3 +8,4 @@ export * from "./constants";
export * from "./visibility-label";
export * from "./use-workspace-agent-availability";
export * from "./mcp-support";
+export * from "./openclaw-runtime-config";
diff --git a/packages/core/agents/openclaw-runtime-config.ts b/packages/core/agents/openclaw-runtime-config.ts
new file mode 100644
index 0000000000..a4e0198251
--- /dev/null
+++ b/packages/core/agents/openclaw-runtime-config.ts
@@ -0,0 +1,97 @@
+// OpenClaw-specific `runtime_config` schema (issue #3260).
+//
+// Stored under `agent.runtime_config` as freeform JSONB; only meaningful for
+// agents whose runtime provider is openclaw. The daemon decodes the same
+// schema in `server/internal/daemon/openclaw_runtime_config.go` — keep both
+// sides in lockstep when changing field names.
+
+export type OpenclawRoutingMode = "local" | "gateway";
+
+export interface OpenclawGatewayPin {
+ host?: string;
+ port?: number;
+ token?: string;
+ tls?: boolean;
+}
+
+export interface OpenclawRuntimeConfig {
+ mode?: OpenclawRoutingMode;
+ gateway?: OpenclawGatewayPin;
+}
+
+// Sentinel the API substitutes for a non-empty `gateway.token` on every read.
+// When the form re-submits the same sentinel we strip the field client-side
+// so the backend's matching preserve hook restores the persisted token
+// instead of overwriting it. Mirrors `runtimeConfigGatewayTokenMask` in
+// server/internal/handler/agent.go.
+export const OPENCLAW_GATEWAY_TOKEN_MASK = "***";
+
+// Parse an arbitrary runtime_config payload into the typed schema. Unknown
+// keys are dropped, malformed payloads collapse to an empty object. The form
+// never throws on bad input — invalid configs simply render as defaults so
+// the user can correct them without a JSON parse error blocking the UI.
+export function parseOpenclawRuntimeConfig(
+ raw: unknown,
+): OpenclawRuntimeConfig {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
+ const root = raw as Record<string, unknown>;
+ const out: OpenclawRuntimeConfig = {};
+ if (root.mode === "local" || root.mode === "gateway") {
+ out.mode = root.mode;
+ }
+ if (root.gateway && typeof root.gateway === "object" && !Array.isArray(root.gateway)) {
+ const gw = root.gateway as Record<string, unknown>;
+ const pin: OpenclawGatewayPin = {};
+ if (typeof gw.host === "string" && gw.host !== "") pin.host = gw.host;
+ if (typeof gw.port === "number" && Number.isFinite(gw.port) && gw.port > 0) pin.port = gw.port;
+ if (typeof gw.token === "string" && gw.token !== "") pin.token = gw.token;
+ if (typeof gw.tls === "boolean") pin.tls = gw.tls;
+ if (Object.keys(pin).length > 0) out.gateway = pin;
+ }
+ return out;
+}
+
+// Render the typed form state back into the wire shape the API accepts.
+// Empty gateway sub-objects collapse to `undefined` so the wire payload
+// only carries fields the user actually populated — partial pins (host+port
+// only, etc.) work as documented.
+export function serializeOpenclawRuntimeConfig(
+ cfg: OpenclawRuntimeConfig,
+): Record<string, unknown> {
+ const out: Record<string, unknown> = {};
+ if (cfg.mode) out.mode = cfg.mode;
+ if (cfg.gateway) {
+ const gw: Record<string, unknown> = {};
+ if (cfg.gateway.host) gw.host = cfg.gateway.host;
+ if (cfg.gateway.port) gw.port = cfg.gateway.port;
+ if (cfg.gateway.tls) gw.tls = true;
+ // The mask sentinel must NEVER round-trip back to the server; the
+ // matching preserve hook on the backend treats its presence as "keep
+ // the persisted token", but emitting it here would still hit the wire
+ // and trip any future schema validation. Drop it client-side so the
+ // payload genuinely omits the field.
+ if (cfg.gateway.token && cfg.gateway.token !== OPENCLAW_GATEWAY_TOKEN_MASK) {
+ gw.token = cfg.gateway.token;
+ }
+ if (Object.keys(gw).length > 0) out.gateway = gw;
+ }
+ return out;
+}
+
+// Stable shallow equality across two parsed configs, used by the form's
+// dirty detector. Treats absent gateway block and an empty gateway block as
+// identical so toggling between local/gateway without filling endpoint
+// fields doesn't surface a spurious "unsaved changes" notice.
+export function openclawRuntimeConfigEquals(
+ a: OpenclawRuntimeConfig,
+ b: OpenclawRuntimeConfig,
+): boolean {
+ if ((a.mode ?? "local") !== (b.mode ?? "local")) return false;
+ const aGw = a.gateway ?? {};
+ const bGw = b.gateway ?? {};
+ if ((aGw.host ?? "") !== (bGw.host ?? "")) return false;
+ if ((aGw.port ?? 0) !== (bGw.port ?? 0)) return false;
+ if ((aGw.token ?? "") !== (bGw.token ?? "")) return false;
+ if (Boolean(aGw.tls) !== Boolean(bGw.tls)) return false;
+ return true;
+}
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
index 0db93d0dbe..8d8a788c1d 100644
--- a/packages/views/agents/components/agent-overview-pane.tsx
+++ b/packages/views/agents/components/agent-overview-pane.tsx
@@ -8,6 +8,7 @@ import {
KeyRound,
ListTodo,
Plug,
+ Router,
Terminal,
Webhook,
} from "lucide-react";
@@ -33,6 +34,7 @@ import { EnvTab } from "./tabs/env-tab";
import { CustomArgsTab } from "./tabs/custom-args-tab";
import { McpConfigTab } from "./tabs/mcp-config-tab";
import { IntegrationsTab } from "./tabs/integrations-tab";
+import { RuntimeConfigTab } from "./tabs/runtime-config-tab";
import { ActorIssuesPanel } from "../../common/actor-issues-panel";
import { useT } from "../../i18n";
@@ -44,9 +46,10 @@ export type DetailTab =
| "env"
| "custom_args"
| "mcp_config"
- | "integrations";
+ | "integrations"
+ | "runtime_config";
-const TAB_LABEL_KEY: Record<DetailTab, "activity" | "tasks" | "instructions" | "skills" | "environment" | "custom_args" | "mcp_config" | "integrations"> = {
+const TAB_LABEL_KEY: Record<DetailTab, "activity" | "tasks" | "instructions" | "skills" | "environment" | "custom_args" | "mcp_config" | "integrations" | "runtime_config"> = {
activity: "activity",
tasks: "tasks",
instructions: "instructions",
@@ -55,6 +58,7 @@ const TAB_LABEL_KEY: Record<DetailTab, "activity" | "tasks" | "instructions" | "
custom_args: "custom_args",
mcp_config: "mcp_config",
integrations: "integrations",
+ runtime_config: "runtime_config",
};
const detailTabs: {
@@ -69,6 +73,7 @@ const detailTabs: {
{ id: "custom_args", icon: Terminal },
{ id: "mcp_config", icon: Plug },
{ id: "integrations", icon: Webhook },
+ { id: "runtime_config", icon: Router },
];
interface AgentOverviewPaneProps {
@@ -146,11 +151,18 @@ export function AgentOverviewPane({
// (configured). Unlike MCP we default to HIDING while the listing loads:
// deployments without Lark are the common case, so flashing the tab on
// then off would be the worse flicker.
+ //
+ // The Runtime Config tab is openclaw-only today (gateway mode lives there,
+ // issue #3260). Other providers' runtime_config is freeform JSONB that no
+ // backend currently reads, so surfacing the tab would let users save values
+ // their runtime ignores — same anti-footgun rationale as the MCP gate.
const visibleTabs = useMemo(() => {
const showMcp = runtime ? providerSupportsMcpConfig(runtime.provider) : true;
+ const showRuntimeConfig = runtime ? runtime.provider === "openclaw" : false;
return detailTabs.filter((tab) => {
if (tab.id === "mcp_config") return showMcp;
if (tab.id === "integrations") return larkConfigured;
+ if (tab.id === "runtime_config") return showRuntimeConfig;
return true;
});
}, [runtime, larkConfigured]);
@@ -271,6 +283,15 @@ export function AgentOverviewPane({
<IntegrationsTab agent={agent} />
</TabContent>
)}
+ {effectiveTab === "runtime_config" && (
+ <TabContent>
+ <RuntimeConfigTab
+ agent={agent}
+ onSave={(updates) => onUpdate(agent.id, updates)}
+ onDirtyChange={setActiveDirty}
+ />
+ </TabContent>
+ )}
</div>
{pendingTab !== null && (
diff --git a/packages/views/agents/components/tabs/runtime-config-tab.tsx b/packages/views/agents/components/tabs/runtime-config-tab.tsx
new file mode 100644
index 0000000000..ffe8328e55
--- /dev/null
+++ b/packages/views/agents/components/tabs/runtime-config-tab.tsx
@@ -0,0 +1,307 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { Loader2, Save } from "lucide-react";
+import type { Agent } from "@multica/core/types";
+import {
+ OPENCLAW_GATEWAY_TOKEN_MASK,
+ type OpenclawRoutingMode,
+ type OpenclawRuntimeConfig,
+ openclawRuntimeConfigEquals,
+ parseOpenclawRuntimeConfig,
+ serializeOpenclawRuntimeConfig,
+} from "@multica/core/agents";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import { Switch } from "@multica/ui/components/ui/switch";
+import { toast } from "sonner";
+import { useT } from "../../../i18n";
+
+// Form state mirrors OpenclawRuntimeConfig, but always carries a defined
+// mode value so the radio group is fully controlled. Empty-string mode
+// shouldn't be reachable in this form because the field defaults to "local"
+// the first time an openclaw agent's tab opens — equivalent to the daemon's
+// fail-soft default — but the union accepts it as a defensive belt.
+interface FormState {
+ mode: OpenclawRoutingMode;
+ host: string;
+ port: string;
+ token: string;
+ tls: boolean;
+ // tokenWasMasked records whether the form opened against a persisted token
+ // (server responded with the mask sentinel). It tracks "the user has not
+ // touched the token field since open" so submit can replay the sentinel
+ // back to the server, which the matching preserve hook treats as "keep
+ // the persisted value". Any user keystroke clears the flag, at which
+ // point token is taken at face value.
+ tokenWasMasked: boolean;
+}
+
+function configToForm(cfg: OpenclawRuntimeConfig): FormState {
+ const masked = cfg.gateway?.token === OPENCLAW_GATEWAY_TOKEN_MASK;
+ return {
+ mode: cfg.mode ?? "local",
+ host: cfg.gateway?.host ?? "",
+ port: cfg.gateway?.port ? String(cfg.gateway.port) : "",
+ // Never display the mask sentinel in the input — that would let users
+ // accidentally edit it. Show an empty field with a placeholder hint
+ // instead, and remember the masked state separately.
+ token: masked ? "" : (cfg.gateway?.token ?? ""),
+ tls: cfg.gateway?.tls === true,
+ tokenWasMasked: masked,
+ };
+}
+
+function formToConfig(state: FormState): OpenclawRuntimeConfig {
+ const cfg: OpenclawRuntimeConfig = { mode: state.mode };
+ if (state.mode === "gateway") {
+ const gw: NonNullable<OpenclawRuntimeConfig["gateway"]> = {};
+ if (state.host.trim() !== "") gw.host = state.host.trim();
+ const portNum = Number.parseInt(state.port, 10);
+ if (Number.isFinite(portNum) && portNum > 0) gw.port = portNum;
+ if (state.tls) gw.tls = true;
+ if (state.tokenWasMasked && state.token === "") {
+ // User opened a saved token and never touched the field — replay
+ // the mask sentinel so the server's preserve hook keeps the
+ // persisted value. The matching client-side serializer drops the
+ // sentinel before it hits the wire, but we need it on the typed
+ // object so the equality check sees an unchanged config.
+ gw.token = OPENCLAW_GATEWAY_TOKEN_MASK;
+ } else if (state.token !== "") {
+ gw.token = state.token;
+ }
+ if (Object.keys(gw).length > 0) cfg.gateway = gw;
+ }
+ return cfg;
+}
+
+export function RuntimeConfigTab({
+ agent,
+ onSave,
+ onDirtyChange,
+}: {
+ agent: Agent;
+ onSave: (updates: { runtime_config: Record<string, unknown> }) => Promise<void>;
+ onDirtyChange?: (dirty: boolean) => void;
+}) {
+ const { t } = useT("agents");
+
+ const original = useMemo<OpenclawRuntimeConfig>(
+ () => parseOpenclawRuntimeConfig(agent.runtime_config),
+ [agent.runtime_config],
+ );
+ const originalForm = useMemo(() => configToForm(original), [original]);
+
+ const [state, setState] = useState<FormState>(originalForm);
+ const [saving, setSaving] = useState(false);
+
+ // Sync local draft when the agent prop changes — same pattern as
+ // McpConfigTab. Only adopt the new server value when the user has no
+ // in-flight edits relative to the *previous* original.
+ const previousFormRef = useRef(originalForm);
+ useEffect(() => {
+ setState((current) =>
+ formEquals(current, previousFormRef.current) ? originalForm : current,
+ );
+ previousFormRef.current = originalForm;
+ }, [originalForm]);
+
+ const currentCfg = useMemo(() => formToConfig(state), [state]);
+ const dirty = !openclawRuntimeConfigEquals(original, currentCfg);
+
+ useEffect(() => {
+ onDirtyChange?.(dirty);
+ }, [dirty, onDirtyChange]);
+
+ const portValid = state.port === "" || /^\d+$/.test(state.port);
+ const canSave = portValid && !saving;
+
+ const handleSave = async () => {
+ if (!canSave) return;
+ setSaving(true);
+ try {
+ await onSave({
+ runtime_config: serializeOpenclawRuntimeConfig(currentCfg),
+ });
+ toast.success(t(($) => $.tab_body.runtime_config.saved_toast));
+ } catch (err) {
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.tab_body.runtime_config.save_failed_toast),
+ );
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const isGateway = state.mode === "gateway";
+
+ return (
+ <div className="flex h-full flex-col space-y-4">
+ <p className="text-xs text-muted-foreground">
+ {t(($) => $.tab_body.runtime_config.intro)}
+ </p>
+
+ <fieldset className="space-y-2">
+ <Label className="text-xs font-medium">
+ {t(($) => $.tab_body.runtime_config.mode_label)}
+ </Label>
+ <div className="flex gap-2">
+ {(["local", "gateway"] as const).map((mode) => (
+ <button
+ key={mode}
+ type="button"
+ onClick={() =>
+ setState((s) => {
+ if (s.mode === mode) return s;
+ // Switching modes clears `tokenWasMasked`. Without this
+ // a user who flips gateway → local → gateway would
+ // re-arm the "replay the mask sentinel back to the
+ // server" branch in formToConfig, silently restoring
+ // a token they had no intent of keeping (see CR for
+ // issue #3260).
+ return { ...s, mode, tokenWasMasked: false };
+ })
+ }
+ className={`rounded-md border px-3 py-1.5 text-xs ${
+ state.mode === mode
+ ? "border-foreground bg-foreground text-background"
+ : "border-border bg-background text-foreground hover:bg-muted"
+ }`}
+ >
+ {t(($) => $.tab_body.runtime_config[`mode_${mode}`])}
+ </button>
+ ))}
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {isGateway
+ ? t(($) => $.tab_body.runtime_config.mode_gateway_hint)
+ : t(($) => $.tab_body.runtime_config.mode_local_hint)}
+ </p>
+ </fieldset>
+
+ <fieldset
+ className={`space-y-3 rounded-md border p-3 ${isGateway ? "" : "opacity-50"}`}
+ disabled={!isGateway}
+ >
+ <legend className="px-1 text-xs font-medium">
+ {t(($) => $.tab_body.runtime_config.gateway_legend)}
+ </legend>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="openclaw-gw-host" className="text-xs">
+ {t(($) => $.tab_body.runtime_config.host_label)}
+ </Label>
+ <Input
+ id="openclaw-gw-host"
+ value={state.host}
+ onChange={(e) => setState((s) => ({ ...s, host: e.target.value }))}
+ placeholder={t(($) => $.tab_body.runtime_config.host_placeholder)}
+ className="font-mono text-xs"
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="openclaw-gw-port" className="text-xs">
+ {t(($) => $.tab_body.runtime_config.port_label)}
+ </Label>
+ <Input
+ id="openclaw-gw-port"
+ value={state.port}
+ onChange={(e) => setState((s) => ({ ...s, port: e.target.value }))}
+ placeholder="18789"
+ inputMode="numeric"
+ aria-invalid={!portValid || undefined}
+ className="font-mono text-xs"
+ />
+ {!portValid && (
+ <p className="text-xs text-destructive">
+ {t(($) => $.tab_body.runtime_config.port_invalid)}
+ </p>
+ )}
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="openclaw-gw-token" className="text-xs">
+ {t(($) => $.tab_body.runtime_config.token_label)}
+ </Label>
+ <Input
+ id="openclaw-gw-token"
+ type="password"
+ value={state.token}
+ onChange={(e) =>
+ setState((s) => ({
+ ...s,
+ token: e.target.value,
+ // The user touched the field — drop the masked-replay
+ // flag so a subsequent empty input genuinely clears the
+ // persisted token instead of preserving it.
+ tokenWasMasked: false,
+ }))
+ }
+ placeholder={
+ state.tokenWasMasked
+ ? t(($) => $.tab_body.runtime_config.token_masked_placeholder)
+ : t(($) => $.tab_body.runtime_config.token_placeholder)
+ }
+ autoComplete="off"
+ className="font-mono text-xs"
+ />
+ </div>
+
+ <div className="flex items-center justify-between gap-2 pt-1">
+ <div>
+ <Label htmlFor="openclaw-gw-tls" className="text-xs">
+ {t(($) => $.tab_body.runtime_config.tls_label)}
+ </Label>
+ <p className="text-xs text-muted-foreground">
+ {t(($) => $.tab_body.runtime_config.tls_hint)}
+ </p>
+ </div>
+ <Switch
+ id="openclaw-gw-tls"
+ checked={state.tls}
+ // Explicit `disabled` mirrors the surrounding fieldset's state.
+ // The native `<fieldset disabled>` attribute only deactivates
+ // built-in form controls; @base-ui's Switch is an ARIA component
+ // and stays interactive unless we tell it otherwise. Without
+ // this guard users could flip TLS on while still in Local mode.
+ disabled={!isGateway}
+ onCheckedChange={(checked: boolean) =>
+ setState((s) => ({ ...s, tls: checked }))
+ }
+ />
+ </div>
+ </fieldset>
+
+ <div className="flex items-center justify-end gap-3 pt-2">
+ {dirty && (
+ <span className="text-xs text-muted-foreground">
+ {t(($) => $.tab_body.common.unsaved_changes)}
+ </span>
+ )}
+ <Button onClick={handleSave} disabled={!dirty || !canSave} size="sm">
+ {saving ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Save className="h-3.5 w-3.5" />
+ )}
+ {t(($) => $.tab_body.common.save)}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function formEquals(a: FormState, b: FormState): boolean {
+ return (
+ a.mode === b.mode &&
+ a.host === b.host &&
+ a.port === b.port &&
+ a.token === b.token &&
+ a.tls === b.tls &&
+ a.tokenWasMasked === b.tokenWasMasked
+ );
+}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index a9ffc27f9e..344f3f57cf 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -210,6 +210,7 @@
"custom_args": "Custom Args",
"mcp_config": "MCP",
"integrations": "Integrations",
+ "runtime_config": "Routing",
"discard_dialog_title": "Discard unsaved changes?",
"discard_dialog_description": "You have unsaved changes in this tab. Leaving now will discard them.",
"discard_keep": "Keep editing",
@@ -321,6 +322,26 @@
"redacted_title": "Configured — hidden from your view",
"redacted_hint": "Only the agent owner or a workspace admin can read this config."
},
+ "runtime_config": {
+ "intro": "Choose how the OpenClaw runtime executes this agent's turns. Local mode runs the agent inside the daemon process. Gateway mode forwards each turn to an OpenClaw Gateway — useful when the daemon host is a lightweight coordinator and the agent should run on a more powerful machine.",
+ "mode_label": "Routing mode",
+ "mode_local": "Local",
+ "mode_gateway": "Gateway",
+ "mode_local_hint": "Default. The daemon spawns `openclaw agent --local …` and the agent loop runs on this host.",
+ "mode_gateway_hint": "The daemon dials an OpenClaw Gateway. Leave the endpoint fields blank to inherit them from the daemon host's `~/.openclaw/openclaw.json`.",
+ "gateway_legend": "Gateway endpoint",
+ "host_label": "Host",
+ "host_placeholder": "gw.internal",
+ "port_label": "Port",
+ "port_invalid": "Port must be a positive integer.",
+ "token_label": "Auth token",
+ "token_placeholder": "Bearer token issued by the gateway",
+ "token_masked_placeholder": "Saved — submit a new value to rotate, or leave blank to keep",
+ "tls_label": "Use TLS",
+ "tls_hint": "Dial https:// instead of http://",
+ "saved_toast": "Routing config saved",
+ "save_failed_toast": "Failed to save routing config"
+ },
"skills": {
"intro": "Workspace skills assigned to this agent. Local runtime skills are always available automatically.",
"add_action": "Add skill",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 44b05d2c74..98da4952c3 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -197,6 +197,7 @@
"custom_args": "カスタム引数",
"mcp_config": "MCP",
"integrations": "連携",
+ "runtime_config": "ルーティング",
"discard_dialog_title": "保存していない変更を破棄しますか?",
"discard_dialog_description": "このタブに保存していない変更があります。今移動すると変更は破棄されます。",
"discard_keep": "編集を続ける",
@@ -306,6 +307,26 @@
"redacted_title": "設定済み — 現在の表示では非表示",
"redacted_hint": "この config を読み取れるのは、エージェントのオーナーまたはワークスペースの admin のみです。"
},
+ "runtime_config": {
+ "intro": "OpenClaw ランタイムがこのエージェントの各ターンをどのように実行するかを選択します。Local モードはエージェントを daemon プロセス内で実行します。Gateway モードは各ターンを OpenClaw Gateway に転送します — daemon のホストが軽量な調整役で、エージェントの実作業はより強力なマシンで動かしたい場合に有用です。",
+ "mode_label": "ルーティングモード",
+ "mode_local": "Local",
+ "mode_gateway": "Gateway",
+ "mode_local_hint": "デフォルト。daemon は `openclaw agent --local …` を起動し、エージェントループがこのホストで実行されます。",
+ "mode_gateway_hint": "daemon は OpenClaw Gateway にダイヤルします。エンドポイントフィールドを空欄のままにすると daemon ホストの `~/.openclaw/openclaw.json` から継承します。",
+ "gateway_legend": "Gateway エンドポイント",
+ "host_label": "Host",
+ "host_placeholder": "gw.internal",
+ "port_label": "ポート",
+ "port_invalid": "ポートは正の整数である必要があります。",
+ "token_label": "認証トークン",
+ "token_placeholder": "Gateway が発行する bearer トークン",
+ "token_masked_placeholder": "保存済み — ローテーションするには新しい値を入力。空欄のままだと保持されます",
+ "tls_label": "TLS を使用",
+ "tls_hint": "http:// の代わりに https:// でダイヤル",
+ "saved_toast": "ルーティング設定を保存しました",
+ "save_failed_toast": "ルーティング設定の保存に失敗しました"
+ },
"skills": {
"intro": "このエージェントに割り当てられたワークスペースのスキルです。ローカルランタイムのスキルは常に自動的に利用できます。",
"add_action": "スキルを追加",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index caaac6d561..7db3eeb359 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -210,6 +210,7 @@
"custom_args": "사용자 지정 인자",
"mcp_config": "MCP",
"integrations": "연동",
+ "runtime_config": "라우팅",
"discard_dialog_title": "저장하지 않은 변경사항을 버릴까요?",
"discard_dialog_description": "이 탭에 저장하지 않은 변경사항이 있습니다. 지금 나가면 변경사항이 사라집니다.",
"discard_keep": "계속 편집",
@@ -321,6 +322,26 @@
"redacted_title": "설정됨 - 현재 보기에서는 숨김",
"redacted_hint": "에이전트 소유자 또는 워크스페이스 관리자만 이 config를 읽을 수 있습니다."
},
+ "runtime_config": {
+ "intro": "OpenClaw 런타임이 이 에이전트의 각 턴을 어떻게 실행할지 선택하세요. Local 모드는 에이전트를 daemon 프로세스 내부에서 실행합니다. Gateway 모드는 각 턴을 OpenClaw Gateway로 전달합니다 — daemon 호스트가 가벼운 조율기 역할을 하고 실제 작업은 더 강력한 머신에서 돌리고 싶을 때 유용합니다.",
+ "mode_label": "라우팅 모드",
+ "mode_local": "Local",
+ "mode_gateway": "Gateway",
+ "mode_local_hint": "기본값. daemon이 `openclaw agent --local …`을 실행하고 에이전트 루프가 이 호스트에서 동작합니다.",
+ "mode_gateway_hint": "daemon이 OpenClaw Gateway에 다이얼합니다. 엔드포인트 필드를 비워두면 daemon 호스트의 `~/.openclaw/openclaw.json`에서 상속받습니다.",
+ "gateway_legend": "Gateway 엔드포인트",
+ "host_label": "Host",
+ "host_placeholder": "gw.internal",
+ "port_label": "포트",
+ "port_invalid": "포트는 양의 정수여야 합니다.",
+ "token_label": "인증 토큰",
+ "token_placeholder": "Gateway가 발급한 bearer 토큰",
+ "token_masked_placeholder": "저장됨 — 회전하려면 새 값을 입력. 비워두면 유지됩니다",
+ "tls_label": "TLS 사용",
+ "tls_hint": "http:// 대신 https://로 다이얼",
+ "saved_toast": "라우팅 설정이 저장되었습니다",
+ "save_failed_toast": "라우팅 설정 저장 실패"
+ },
"skills": {
"intro": "이 에이전트에 할당된 워크스페이스 스킬입니다. 로컬 런타임 스킬은 항상 자동으로 사용할 수 있습니다.",
"add_action": "스킬 추가",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 4bcc0e12e7..45bf90e36d 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -205,6 +205,7 @@
"custom_args": "自定义参数",
"mcp_config": "MCP",
"integrations": "集成",
+ "runtime_config": "路由",
"discard_dialog_title": "放弃未保存的修改?",
"discard_dialog_description": "当前 tab 有未保存的修改,离开会丢弃这些修改。",
"discard_keep": "继续编辑",
@@ -314,6 +315,26 @@
"redacted_title": "已配置 —— 当前账号无权查看",
"redacted_hint": "只有智能体所有者或工作区管理员可以读取该配置。"
},
+ "runtime_config": {
+ "intro": "选择 OpenClaw 运行时执行该智能体每一回合的方式。Local 模式让智能体直接在 daemon 进程内运行;Gateway 模式则把每一回合转发到一个 OpenClaw Gateway —— 适合 daemon 宿主只是轻量协调机、希望真正算力落在更强的远端机器上的场景。",
+ "mode_label": "路由模式",
+ "mode_local": "Local",
+ "mode_gateway": "Gateway",
+ "mode_local_hint": "默认。daemon 调用 `openclaw agent --local …`,智能体循环跑在本机。",
+ "mode_gateway_hint": "daemon 连接 OpenClaw Gateway。端点字段留空则继承 daemon 宿主 `~/.openclaw/openclaw.json` 里的配置。",
+ "gateway_legend": "Gateway 端点",
+ "host_label": "Host",
+ "host_placeholder": "gw.internal",
+ "port_label": "端口",
+ "port_invalid": "端口必须是正整数。",
+ "token_label": "鉴权 Token",
+ "token_placeholder": "Gateway 颁发的 bearer token",
+ "token_masked_placeholder": "已保存 —— 输入新值可轮换,留空则保留原 token",
+ "tls_label": "启用 TLS",
+ "tls_hint": "用 https:// 代替 http:// 连接",
+ "saved_toast": "路由配置已保存",
+ "save_failed_toast": "保存路由配置失败"
+ },
"skills": {
"intro": "分配给该智能体的工作区 skill。本地运行时 skill 会自动可用。",
"add_action": "添加 skill",
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 771bc60f32..e13baa49e2 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -2715,28 +2715,39 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if task.Agent != nil {
agentMcpConfig = task.Agent.McpConfig
}
+ // Decode openclaw-specific runtime_config knobs once so reuse / prepare /
+ // ExecOptions all see the same mode + gateway pin (issue #3260). Parse
+ // failures fail soft to local mode — a broken JSON blob must never block
+ // task dispatch.
+ var openclawMode string
+ var openclawGateway execenv.OpenclawGatewayPin
+ if task.Agent != nil && provider == "openclaw" {
+ openclawMode, openclawGateway = decodeOpenclawRuntimeConfig(task.Agent.RuntimeConfig, d.logger)
+ }
if task.PriorWorkDir != "" && localAssignment == nil {
env = execenv.Reuse(execenv.ReuseParams{
- WorkDir: task.PriorWorkDir,
- Provider: provider,
- CodexVersion: codexVersion,
- OpenclawBin: openclawBin,
- McpConfig: agentMcpConfig,
- Task: taskCtx,
+ WorkDir: task.PriorWorkDir,
+ Provider: provider,
+ CodexVersion: codexVersion,
+ OpenclawBin: openclawBin,
+ McpConfig: agentMcpConfig,
+ OpenclawGateway: openclawGateway,
+ Task: taskCtx,
}, d.logger)
}
if env == nil {
var err error
prepParams := execenv.PrepareParams{
- WorkspacesRoot: d.cfg.WorkspacesRoot,
- WorkspaceID: task.WorkspaceID,
- TaskID: task.ID,
- AgentName: agentName,
- Provider: provider,
- CodexVersion: codexVersion,
- OpenclawBin: openclawBin,
- McpConfig: agentMcpConfig,
- Task: taskCtx,
+ WorkspacesRoot: d.cfg.WorkspacesRoot,
+ WorkspaceID: task.WorkspaceID,
+ TaskID: task.ID,
+ AgentName: agentName,
+ Provider: provider,
+ CodexVersion: codexVersion,
+ OpenclawBin: openclawBin,
+ McpConfig: agentMcpConfig,
+ OpenclawGateway: openclawGateway,
+ Task: taskCtx,
}
if localAssignment != nil {
prepParams.LocalWorkDir = localAssignment.AbsPath
@@ -2995,6 +3006,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
CustomArgs: customArgs,
McpConfig: mcpConfig,
ThinkingLevel: thinkingLevel,
+ OpenclawMode: openclawMode,
}
// Some providers do not reliably load the per-task runtime config files we
// write into the task workdir:
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index d7d280e6b8..b904c8ab79 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -44,6 +44,11 @@ type PrepareParams struct {
// via a per-task config file. Cursor and OpenClaw consume it here; other
// providers wire MCP via ExecOptions.McpConfig in the agent backend.
McpConfig json.RawMessage
+ // OpenclawGateway pins the OpenClaw Gateway endpoint inside the per-task
+ // wrapper. Only consulted when Provider == "openclaw" and the agent's
+ // runtime_config selected gateway mode (issue #3260). Zero means "inherit
+ // whatever the user's global openclaw.json already configures".
+ OpenclawGateway OpenclawGatewayPin
// LocalWorkDir, when non-empty, redirects the agent's working directory
// to a user-supplied absolute path instead of the synthesised envRoot/
// workdir. The path is NOT copied or mounted — the agent operates on
@@ -264,6 +269,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
result, err := prepareOpenclawConfig(envRoot, workDir, OpenclawConfigPrep{
OpenclawBin: params.OpenclawBin,
McpConfig: params.McpConfig,
+ Gateway: params.OpenclawGateway,
})
if err != nil {
return nil, fmt.Errorf("execenv: prepare openclaw config: %w", err)
@@ -289,6 +295,9 @@ type ReuseParams struct {
// task starts — without this a stale wrapper from a prior run would keep
// the old MCP set in play.
McpConfig json.RawMessage
+ // OpenclawGateway is the per-task Gateway pin re-applied on reuse so the
+ // agent picks up any runtime_config changes saved since the prior run.
+ OpenclawGateway OpenclawGatewayPin
// LocalDirectory is true when the reused WorkDir is a user-supplied
// directory (the local_directory flow). The flag is propagated into
// the returned Environment so downstream callers (notably the GC
@@ -417,6 +426,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
result, err := prepareOpenclawConfig(env.RootDir, params.WorkDir, OpenclawConfigPrep{
OpenclawBin: params.OpenclawBin,
McpConfig: params.McpConfig,
+ Gateway: params.OpenclawGateway,
})
if err != nil {
logger.Warn("execenv: refresh openclaw config failed", "error", err)
diff --git a/server/internal/daemon/execenv/openclaw_config.go b/server/internal/daemon/execenv/openclaw_config.go
index dab691a815..d87defc0ea 100644
--- a/server/internal/daemon/execenv/openclaw_config.go
+++ b/server/internal/daemon/execenv/openclaw_config.go
@@ -49,6 +49,62 @@ type OpenclawConfigPrep struct {
// Null / empty means inherit the user's global config — same three-state
// semantics codex uses (`hasManagedCodexMcpConfig`).
McpConfig json.RawMessage
+ // Gateway pins a specific OpenClaw Gateway endpoint inside the per-task
+ // wrapper. Only consulted when the agent is configured for gateway-mode
+ // openclaw (see ExecOptions.OpenclawMode); zero means "inherit whatever
+ // the user's global openclaw.json already configures under `gateway.*`"
+ // — which is the right default when the user already has a working
+ // gateway set up locally. See issue #3260.
+ Gateway OpenclawGatewayPin
+}
+
+// OpenclawGatewayPin describes the Gateway endpoint a per-task openclaw
+// wrapper should pin. Fields mirror OpenClaw's own `gateway.*` config shape
+// (see ~/.openclaw/openclaw.json). All fields are optional; only non-zero
+// fields are emitted into the wrapper so a partial pin (e.g. host+port
+// only, token left to inherit from the user's config) does the right
+// thing under OpenClaw's deep-merge $include semantics.
+type OpenclawGatewayPin struct {
+ Host string
+ Port int
+ Token string
+ TLS bool
+}
+
+// IsZero reports whether every field is zero, i.e. there is nothing to pin.
+func (p OpenclawGatewayPin) IsZero() bool {
+ return p == OpenclawGatewayPin{}
+}
+
+// String masks the bearer token when the pin is rendered as a string —
+// `%v` / `%+v` / direct `fmt.Stringer` use cases all go through here. The
+// raw Token field still exists for the wrapper-config emitter that needs
+// it; this is a belt against a future caller that logs a whole task-prep
+// summary at a level a non-admin can see (issue #3260 CR).
+func (p OpenclawGatewayPin) String() string {
+ tok := ""
+ if p.Token != "" {
+ tok = "***"
+ }
+ return fmt.Sprintf("OpenclawGatewayPin{Host:%q Port:%d Token:%s TLS:%t}", p.Host, p.Port, tok, p.TLS)
+}
+
+// MarshalJSON masks the bearer token in any default JSON dump (debug
+// endpoints, error envelopes, structured-log encoders). The wrapper config
+// writer goes through buildGatewayOverride which assembles a map directly,
+// so it is unaffected by this masking.
+func (p OpenclawGatewayPin) MarshalJSON() ([]byte, error) {
+ type alias struct {
+ Host string `json:"host,omitempty"`
+ Port int `json:"port,omitempty"`
+ Token string `json:"token,omitempty"`
+ TLS bool `json:"tls,omitempty"`
+ }
+ masked := alias{Host: p.Host, Port: p.Port, TLS: p.TLS}
+ if p.Token != "" {
+ masked.Token = "***"
+ }
+ return json.Marshal(masked)
}
// OpenclawConfigResult is what prepareOpenclawConfig returns to its callers
@@ -192,7 +248,7 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
}
}
- cfg := buildPerTaskOpenclawConfig(activePath, exists, snapshotPath, resolvedList, workDir, managedMcp, hasManagedMcp)
+ cfg := buildPerTaskOpenclawConfig(activePath, exists, snapshotPath, resolvedList, workDir, managedMcp, hasManagedMcp, opts.Gateway)
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
@@ -248,7 +304,7 @@ func prepareOpenclawConfig(envRoot, workDir string, opts OpenclawConfigPrep) (Op
// snapshot $include has already dropped the user's `mcp` block, the
// resulting view of `mcp.servers` is exactly the managed set — including
// `{}` for "admin saved no servers" (mirrors `hasManagedCodexMcpConfig`).
-func buildPerTaskOpenclawConfig(activePath string, exists bool, snapshotPath string, resolvedList []any, workDir string, managedMcp map[string]any, hasManagedMcp bool) map[string]any {
+func buildPerTaskOpenclawConfig(activePath string, exists bool, snapshotPath string, resolvedList []any, workDir string, managedMcp map[string]any, hasManagedMcp bool, gateway OpenclawGatewayPin) map[string]any {
agents := map[string]any{
"defaults": map[string]any{"workspace": workDir},
}
@@ -269,6 +325,15 @@ func buildPerTaskOpenclawConfig(activePath string, exists bool, snapshotPath str
}
cfg["mcp"] = map[string]any{"servers": servers}
}
+ // Gateway endpoint pin (issue #3260). Mirrors the user's openclaw.json
+ // `gateway.*` shape so OpenClaw's deep-merge $include semantics produce
+ // the right composed config: anything we set here wins over the user's
+ // global, anything we omit inherits from the user's global. Only emit
+ // fields the multica admin explicitly populated — zero strings/ints
+ // would override the user's value with junk.
+ if gw := buildGatewayOverride(gateway); gw != nil {
+ cfg["gateway"] = gw
+ }
switch {
case snapshotPath != "":
// Sanitized snapshot path; strict-replace flow for managed mcp_config.
@@ -282,6 +347,36 @@ func buildPerTaskOpenclawConfig(activePath string, exists bool, snapshotPath str
return cfg
}
+// buildGatewayOverride renders the non-zero subset of a Gateway pin into the
+// shape OpenClaw expects under `gateway.*` (see ~/.openclaw/openclaw.json:
+// host, port, tls at the top level and an `auth: {mode, token}` sub-object).
+// Returns nil when nothing is populated so the caller can skip emission.
+func buildGatewayOverride(p OpenclawGatewayPin) map[string]any {
+ if p.IsZero() {
+ return nil
+ }
+ out := map[string]any{}
+ if p.Host != "" {
+ out["host"] = p.Host
+ }
+ if p.Port != 0 {
+ out["port"] = p.Port
+ }
+ if p.TLS {
+ out["tls"] = true
+ }
+ if p.Token != "" {
+ out["auth"] = map[string]any{
+ "mode": "token",
+ "token": p.Token,
+ }
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
// rewriteAgentsListWorkspaces copies every entry of the resolved agents.list
// and pins its `workspace` field to workDir. Returns nil when the input is
// nil or empty so buildPerTaskOpenclawConfig can omit the key entirely
diff --git a/server/internal/daemon/execenv/openclaw_config_test.go b/server/internal/daemon/execenv/openclaw_config_test.go
index 088073b855..dded2763b7 100644
--- a/server/internal/daemon/execenv/openclaw_config_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_test.go
@@ -1097,3 +1097,84 @@ func TestPrepareEnvironmentNonOpenclawSkipsConfig(t *testing.T) {
t.Errorf("non-openclaw providers shelled out to openclaw CLI %d times: %+v", len(stub.calls), stub.calls)
}
}
+
+// ── Gateway endpoint pinning (issue #3260) ──
+//
+// When a multica agent is configured for gateway-mode openclaw and the
+// runtime_config carries a Gateway endpoint, the per-task wrapper must pin
+// that endpoint in its `gateway` block. OpenClaw deep-merges sibling object
+// keys after $include, so the wrapper's `gateway.*` settings override
+// whatever the user's global openclaw.json carried.
+
+func TestBuildPerTaskOpenclawConfigOmitsGatewayWhenZero(t *testing.T) {
+ t.Parallel()
+
+ cfg := buildPerTaskOpenclawConfig(
+ "", false, "", nil, "/workdir", nil, false,
+ OpenclawGatewayPin{},
+ )
+ if _, present := cfg["gateway"]; present {
+ t.Errorf("zero gateway must not emit a gateway block, got %v", cfg["gateway"])
+ }
+}
+
+func TestBuildPerTaskOpenclawConfigWritesGatewayBlock(t *testing.T) {
+ t.Parallel()
+
+ pin := OpenclawGatewayPin{
+ Host: "gw.internal",
+ Port: 18789,
+ Token: "secret-token",
+ TLS: true,
+ }
+ cfg := buildPerTaskOpenclawConfig(
+ "", false, "", nil, "/workdir", nil, false,
+ pin,
+ )
+
+ gw, ok := cfg["gateway"].(map[string]any)
+ if !ok {
+ t.Fatalf("expected gateway map, got %T: %v", cfg["gateway"], cfg["gateway"])
+ }
+ if gw["host"] != "gw.internal" {
+ t.Errorf("gateway.host = %v, want %q", gw["host"], "gw.internal")
+ }
+ if gw["port"] != 18789 {
+ t.Errorf("gateway.port = %v, want %d", gw["port"], 18789)
+ }
+ // Token nests under gateway.auth.{mode,token} to match OpenClaw's own
+ // config shape (see ~/.openclaw/openclaw.json `gateway.auth`).
+ auth, ok := gw["auth"].(map[string]any)
+ if !ok {
+ t.Fatalf("expected gateway.auth map, got %T: %v", gw["auth"], gw["auth"])
+ }
+ if auth["mode"] != "token" {
+ t.Errorf("gateway.auth.mode = %v, want %q", auth["mode"], "token")
+ }
+ if auth["token"] != "secret-token" {
+ t.Errorf("gateway.auth.token = %v, want %q", auth["token"], "secret-token")
+ }
+ if gw["tls"] != true {
+ t.Errorf("gateway.tls = %v, want true", gw["tls"])
+ }
+}
+
+func TestBuildPerTaskOpenclawConfigPartialGatewayOmitsZeroFields(t *testing.T) {
+ t.Parallel()
+
+ // Users may pin only host/port and rely on the user's local openclaw.json
+ // for the token (which still flows in via the $include). Zero-valued
+ // fields must not land in the wrapper as empty strings/zeros — that
+ // would override the user's value with junk.
+ cfg := buildPerTaskOpenclawConfig(
+ "", false, "", nil, "/workdir", nil, false,
+ OpenclawGatewayPin{Host: "gw.internal", Port: 18789},
+ )
+ gw := cfg["gateway"].(map[string]any)
+ if _, present := gw["auth"]; present {
+ t.Errorf("auth block must be omitted when token is empty, got %v", gw["auth"])
+ }
+ if _, present := gw["tls"]; present {
+ t.Errorf("tls field must be omitted when false, got %v", gw["tls"])
+ }
+}
diff --git a/server/internal/daemon/openclaw_runtime_config.go b/server/internal/daemon/openclaw_runtime_config.go
new file mode 100644
index 0000000000..69787565e0
--- /dev/null
+++ b/server/internal/daemon/openclaw_runtime_config.go
@@ -0,0 +1,86 @@
+package daemon
+
+import (
+ "encoding/json"
+ "log/slog"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+)
+
+// openclawRuntimeConfig is the schema the daemon expects under an openclaw
+// agent's `runtime_config` JSONB column. All fields are optional; absence
+// (or the agent's whole runtime_config being null/empty) keeps the
+// historical embedded behaviour so existing agents are unaffected.
+//
+// Schema (issue #3260):
+//
+// {
+// "mode": "local" | "gateway", // default: "local"
+// "gateway": {
+// "host": "<hostname>", // remote OpenClaw gateway host
+// "port": 18789, // gateway port
+// "token": "<bearer>", // gateway auth token (masked in API responses)
+// "tls": false // dial https if true
+// }
+// }
+//
+// Other providers' runtime_config payloads pass through untouched — this
+// decoder only reads keys that have meaning for the openclaw backend.
+type openclawRuntimeConfig struct {
+ Mode string `json:"mode"`
+ Gateway openclawRuntimeGatewayConfig `json:"gateway"`
+}
+
+// openclawRuntimeGatewayConfig is the owner-supplied Gateway endpoint.
+//
+// Trust boundary: in gateway mode the daemon writes this host:port into the
+// per-task wrapper and the spawned openclaw CLI dials it. For self-hosted,
+// single-tenant daemons this is the same trust level as custom_args /
+// custom_env — the owner already controls the daemon host. Operators running
+// a SHARED / managed daemon host should treat it as an SSRF surface (an agent
+// owner could point the daemon at an arbitrary internal address) and
+// gate/allowlist gateway targets accordingly.
+type openclawRuntimeGatewayConfig struct {
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Token string `json:"token"`
+ TLS bool `json:"tls"`
+}
+
+// decodeOpenclawRuntimeConfig extracts the openclaw-specific knobs from an
+// agent's runtime_config payload. Returns the routing mode plus the gateway
+// pin shaped for execenv. The pin is non-zero only in gateway mode — any
+// other mode drops it so a local-mode payload can't smuggle a bearer token
+// into the per-task wrapper. A malformed payload logs a warning and degrades
+// to local mode (mode="", zero gateway) rather than failing dispatch — the
+// alternative would let one bad save block every task that agent runs.
+func decodeOpenclawRuntimeConfig(raw json.RawMessage, logger *slog.Logger) (string, execenv.OpenclawGatewayPin) {
+ if len(raw) == 0 {
+ return "", execenv.OpenclawGatewayPin{}
+ }
+ var cfg openclawRuntimeConfig
+ if err := json.Unmarshal(raw, &cfg); err != nil {
+ logger.Warn("openclaw runtime_config: parse failed; falling back to local mode", "error", err)
+ return "", execenv.OpenclawGatewayPin{}
+ }
+ // Surface an unrecognized non-empty mode instead of silently treating it
+ // as local — a typo like "gatway" would otherwise leave the user wondering
+ // why their gateway config is ignored.
+ if cfg.Mode != "" && cfg.Mode != "local" && cfg.Mode != "gateway" {
+ logger.Warn("openclaw runtime_config: unrecognized mode; falling back to local mode",
+ "mode", cfg.Mode)
+ }
+ // Only gateway mode consults the pin. For every other mode (local / empty /
+ // unrecognized) drop the gateway block so a stray
+ // {"mode":"local","gateway":{...,"token":"..."}} never writes the bearer
+ // token into the 0o600 per-task wrapper that `--local` makes openclaw ignore.
+ if cfg.Mode != "gateway" {
+ return cfg.Mode, execenv.OpenclawGatewayPin{}
+ }
+ return cfg.Mode, execenv.OpenclawGatewayPin{
+ Host: cfg.Gateway.Host,
+ Port: cfg.Gateway.Port,
+ Token: cfg.Gateway.Token,
+ TLS: cfg.Gateway.TLS,
+ }
+}
diff --git a/server/internal/daemon/openclaw_runtime_config_test.go b/server/internal/daemon/openclaw_runtime_config_test.go
new file mode 100644
index 0000000000..f891e26f8b
--- /dev/null
+++ b/server/internal/daemon/openclaw_runtime_config_test.go
@@ -0,0 +1,163 @@
+package daemon
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+)
+
+func quietLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}
+
+func TestDecodeOpenclawRuntimeConfigEmpty(t *testing.T) {
+ t.Parallel()
+
+ mode, gw := decodeOpenclawRuntimeConfig(nil, quietLogger())
+ if mode != "" {
+ t.Errorf("mode for nil payload: got %q, want \"\"", mode)
+ }
+ if !gw.IsZero() {
+ t.Errorf("gateway for nil payload: got %+v, want zero", gw)
+ }
+}
+
+func TestDecodeOpenclawRuntimeConfigGatewayMode(t *testing.T) {
+ t.Parallel()
+
+ raw := json.RawMessage(`{
+ "mode": "gateway",
+ "gateway": {
+ "host": "gw.internal",
+ "port": 18789,
+ "token": "secret",
+ "tls": true
+ }
+ }`)
+ mode, gw := decodeOpenclawRuntimeConfig(raw, quietLogger())
+ if mode != "gateway" {
+ t.Errorf("mode: got %q, want %q", mode, "gateway")
+ }
+ want := execenv.OpenclawGatewayPin{
+ Host: "gw.internal",
+ Port: 18789,
+ Token: "secret",
+ TLS: true,
+ }
+ if gw != want {
+ t.Errorf("gateway: got %+v, want %+v", gw, want)
+ }
+}
+
+func TestDecodeOpenclawRuntimeConfigMalformedFailsSoftToLocal(t *testing.T) {
+ t.Parallel()
+
+ // A broken JSON blob must never block dispatch — the agent runs in the
+ // historical embedded mode until the user fixes the config.
+ mode, gw := decodeOpenclawRuntimeConfig(json.RawMessage(`{"mode": "gateway"`), quietLogger())
+ if mode != "" {
+ t.Errorf("mode for malformed payload: got %q, want \"\"", mode)
+ }
+ if !gw.IsZero() {
+ t.Errorf("gateway for malformed payload: got %+v, want zero", gw)
+ }
+}
+
+func TestDecodeOpenclawRuntimeConfigModeOnly(t *testing.T) {
+ t.Parallel()
+
+ // Users may switch to gateway mode and rely on the daemon host's local
+ // ~/.openclaw/openclaw.json for the endpoint — gateway block stays zero.
+ mode, gw := decodeOpenclawRuntimeConfig(json.RawMessage(`{"mode": "gateway"}`), quietLogger())
+ if mode != "gateway" {
+ t.Errorf("mode: got %q, want %q", mode, "gateway")
+ }
+ if !gw.IsZero() {
+ t.Errorf("gateway: got %+v, want zero", gw)
+ }
+}
+
+// TestOpenclawGatewayPinDefaultFormattingMasksToken — a stray `%v` /
+// `%+v` / json.Marshal of an OpenclawGatewayPin must NOT print the bearer
+// token verbatim. The wrapper-config writer still gets the real value
+// directly off the Token field; only default formatters get redacted.
+// Guards against the secondary leak path called out in the issue #3260 CR.
+func TestOpenclawGatewayPinDefaultFormattingMasksToken(t *testing.T) {
+ t.Parallel()
+
+ pin := execenv.OpenclawGatewayPin{
+ Host: "gw.internal",
+ Port: 18789,
+ Token: "real-secret",
+ TLS: true,
+ }
+
+ if got := pin.String(); strings.Contains(got, "real-secret") {
+ t.Errorf("String() leaks token: %q", got)
+ }
+ if got := fmt.Sprintf("%+v", pin); strings.Contains(got, "real-secret") {
+ t.Errorf("%%+v leaks token: %q", got)
+ }
+ raw, err := json.Marshal(pin)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if strings.Contains(string(raw), "real-secret") {
+ t.Errorf("MarshalJSON leaks token: %s", raw)
+ }
+ // Sanity: the host stays visible so the masked payload is still
+ // useful for debugging the non-secret half of the pin.
+ if !strings.Contains(string(raw), "gw.internal") {
+ t.Errorf("MarshalJSON dropped host along with token: %s", raw)
+ }
+}
+
+// TestDecodeOpenclawRuntimeConfigLocalModeDropsGatewayPin — a local-mode
+// payload that still carries a gateway block (craftable via a direct PATCH)
+// must not surface the pin. Otherwise the bearer token would be written into
+// the 0o600 per-task wrapper that `--local` makes openclaw ignore.
+func TestDecodeOpenclawRuntimeConfigLocalModeDropsGatewayPin(t *testing.T) {
+ t.Parallel()
+
+ raw := json.RawMessage(`{
+ "mode": "local",
+ "gateway": {"host": "gw.internal", "port": 18789, "token": "secret", "tls": true}
+ }`)
+ mode, gw := decodeOpenclawRuntimeConfig(raw, quietLogger())
+ if mode != "local" {
+ t.Errorf("mode: got %q, want %q", mode, "local")
+ }
+ if !gw.IsZero() {
+ t.Errorf("gateway for local mode: got %+v, want zero", gw)
+ }
+}
+
+// TestDecodeOpenclawRuntimeConfigUnknownModeWarnsAndDropsPin — a typo'd mode
+// neither behaves like gateway nor silently like local: it falls back to local
+// (zero pin) AND logs a WARN so the misconfiguration is discoverable.
+func TestDecodeOpenclawRuntimeConfigUnknownModeWarnsAndDropsPin(t *testing.T) {
+ t.Parallel()
+
+ var buf bytes.Buffer
+ logger := slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn}))
+ raw := json.RawMessage(`{
+ "mode": "gatway",
+ "gateway": {"host": "gw.internal", "port": 18789, "token": "secret"}
+ }`)
+ mode, gw := decodeOpenclawRuntimeConfig(raw, logger)
+ if mode != "gatway" {
+ t.Errorf("mode: got %q, want %q", mode, "gatway")
+ }
+ if !gw.IsZero() {
+ t.Errorf("gateway for unknown mode: got %+v, want zero", gw)
+ }
+ if !strings.Contains(buf.String(), "unrecognized mode") {
+ t.Errorf("expected WARN about unrecognized mode, got: %q", buf.String())
+ }
+}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 28d4ee74e1..af97796c20 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -127,6 +127,11 @@ type AgentData struct {
McpConfig json.RawMessage `json:"mcp_config,omitempty"`
Model string `json:"model,omitempty"`
ThinkingLevel string `json:"thinking_level,omitempty"`
+ // RuntimeConfig is the per-provider runtime_config JSON as stored on
+ // the agent record, forwarded verbatim by the claim endpoint. The
+ // daemon decodes provider-specific fields (e.g. openclaw mode +
+ // gateway endpoint, see issue #3260); other backends ignore it.
+ RuntimeConfig json.RawMessage `json:"runtime_config,omitempty"`
}
// SkillData represents a structured skill for task execution.
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 0994592895..b78017d6d1 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -69,6 +69,15 @@ type AgentResponse struct {
ArchivedBy *string `json:"archived_by"`
}
+// runtimeConfigGatewayTokenMask is the placeholder the API substitutes for
+// any non-empty `runtime_config.gateway.token` (openclaw gateway mode, issue
+// #3260). The token is a bearer credential; surfacing the real value through
+// GET responses would let anyone with read access to the agent dump the
+// gateway secret. The mask is a sentinel — when the UI later PATCHes the
+// agent and submits the same mask verbatim under that field, the update
+// handler restores the persisted token instead of overwriting it.
+const runtimeConfigGatewayTokenMask = "***"
+
func agentToResponse(a db.Agent) AgentResponse {
var rc any
if a.RuntimeConfig != nil {
@@ -77,6 +86,7 @@ func agentToResponse(a db.Agent) AgentResponse {
if rc == nil {
rc = map[string]any{}
}
+ maskGatewayToken(rc)
// Compute env metadata WITHOUT exposing the values. We unmarshal here
// only to count keys; the map never reaches the response. A coarse
@@ -135,6 +145,62 @@ func agentToResponse(a db.Agent) AgentResponse {
}
}
+// maskGatewayToken replaces runtime_config.gateway.token with the public
+// mask sentinel when a non-empty value is present. No-op for any other
+// shape so non-openclaw / non-gateway agents pass through untouched.
+func maskGatewayToken(rc any) {
+ root, ok := rc.(map[string]any)
+ if !ok {
+ return
+ }
+ gw, ok := root["gateway"].(map[string]any)
+ if !ok {
+ return
+ }
+ tok, _ := gw["token"].(string)
+ if tok == "" {
+ return
+ }
+ gw["token"] = runtimeConfigGatewayTokenMask
+}
+
+// preserveMaskedGatewayToken substitutes the previously persisted gateway
+// token back into an incoming runtime_config when the request submitted the
+// public mask sentinel under `gateway.token`. Without this the next PATCH
+// after a GET would round-trip the masked sentinel into the database and
+// silently destroy the real secret. The previous value is taken from the
+// agent row the handler has just loaded for ownership / scoping checks.
+func preserveMaskedGatewayToken(incoming any, persistedRuntimeConfig []byte) {
+ root, ok := incoming.(map[string]any)
+ if !ok {
+ return
+ }
+ gw, ok := root["gateway"].(map[string]any)
+ if !ok {
+ return
+ }
+ tok, _ := gw["token"].(string)
+ if tok != runtimeConfigGatewayTokenMask {
+ return
+ }
+ // The incoming token is the mask — fish the real one out of the row.
+ var prev struct {
+ Gateway struct {
+ Token string `json:"token"`
+ } `json:"gateway"`
+ }
+ if len(persistedRuntimeConfig) == 0 {
+ // No prior token to keep; the field becomes effectively empty.
+ delete(gw, "token")
+ return
+ }
+ if err := json.Unmarshal(persistedRuntimeConfig, &prev); err != nil || prev.Gateway.Token == "" {
+ delete(gw, "token")
+ return
+ }
+ gw["token"] = prev.Gateway.Token
+}
+
// RepoData holds repository information included in claim responses so the
// daemon can set up worktrees for each workspace repo.
type RepoData struct {
@@ -284,6 +350,12 @@ type TaskAgentData struct {
McpConfig json.RawMessage `json:"mcp_config,omitempty"`
Model string `json:"model,omitempty"`
ThinkingLevel string `json:"thinking_level,omitempty"`
+ // RuntimeConfig is the agent's saved runtime_config JSON as-is. The
+ // daemon decodes it per-provider — e.g. the openclaw backend reads
+ // `mode` + `gateway.*` to choose between embedded and gateway routing
+ // (issue #3260). Other providers ignore the payload entirely. Sent
+ // raw so the daemon can evolve its schema without a server roundtrip.
+ RuntimeConfig json.RawMessage `json:"runtime_config,omitempty"`
}
// taskToResponse maps a queue row to its wire shape. workspaceID is threaded
@@ -706,6 +778,10 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
isFirstAgent = len(existing) == 0
}
+ // A create has no prior token to restore, so if the caller submitted the
+ // public mask sentinel as gateway.token (e.g. replayed a masked GET body)
+ // drop it rather than persisting a literal "***" as a real bearer token.
+ preserveMaskedGatewayToken(req.RuntimeConfig, nil)
rc, _ := json.Marshal(req.RuntimeConfig)
if req.RuntimeConfig == nil {
rc = []byte("{}")
@@ -860,6 +936,13 @@ func canViewAgentSecrets(agent db.Agent, userID string, memberRole string) bool
func broadcastAgentResponse(resp AgentResponse) AgentResponse {
out := resp
redactMcpConfig(&out)
+ // Belt-and-suspenders: agentToResponse already masks gateway.token on
+ // every read, so by the time a response reaches this broadcast helper
+ // the field is already "***". Re-mask anyway so a future refactor that
+ // bypasses agentToResponse (e.g. constructing AgentResponse from raw
+ // db.Agent in a new handler) cannot silently leak the token to every
+ // WebSocket subscriber on the workspace, agent processes included.
+ maskGatewayToken(out.RuntimeConfig)
return out
}
@@ -953,6 +1036,11 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
params.AvatarUrl = pgtype.Text{String: *req.AvatarURL, Valid: true}
}
if req.RuntimeConfig != nil {
+ // Restore the persisted gateway token when the request submitted the
+ // public mask sentinel. Without this, a UI that GETs the agent and
+ // PATCHes the same payload back round-trips "***" into the database
+ // and silently destroys the real secret (issue #3260).
+ preserveMaskedGatewayToken(req.RuntimeConfig, existing.RuntimeConfig)
rc, _ := json.Marshal(req.RuntimeConfig)
params.RuntimeConfig = rc
}
diff --git a/server/internal/handler/agent_runtime_config_mask_test.go b/server/internal/handler/agent_runtime_config_mask_test.go
new file mode 100644
index 0000000000..d72111b281
--- /dev/null
+++ b/server/internal/handler/agent_runtime_config_mask_test.go
@@ -0,0 +1,130 @@
+package handler
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestMaskGatewayTokenReplacesNonEmpty(t *testing.T) {
+ t.Parallel()
+
+ rc := map[string]any{
+ "mode": "gateway",
+ "gateway": map[string]any{
+ "host": "gw.internal",
+ "port": float64(18789), // json.Unmarshal yields float64 for numbers
+ "token": "real-secret",
+ "tls": true,
+ },
+ }
+ maskGatewayToken(rc)
+ gw := rc["gateway"].(map[string]any)
+ if gw["token"] != runtimeConfigGatewayTokenMask {
+ t.Errorf("token: got %v, want %q", gw["token"], runtimeConfigGatewayTokenMask)
+ }
+ if gw["host"] != "gw.internal" {
+ t.Errorf("host must not be touched, got %v", gw["host"])
+ }
+}
+
+func TestMaskGatewayTokenSkipsEmptyToken(t *testing.T) {
+ t.Parallel()
+
+ // host+port-only configs (token still inherited from the user's local
+ // openclaw.json) must not surface a misleading "***" placeholder.
+ rc := map[string]any{
+ "gateway": map[string]any{
+ "host": "gw.internal",
+ "port": float64(18789),
+ },
+ }
+ maskGatewayToken(rc)
+ gw := rc["gateway"].(map[string]any)
+ if _, present := gw["token"]; present {
+ t.Errorf("empty token must not gain a mask, got %v", gw["token"])
+ }
+}
+
+func TestMaskGatewayTokenNoOpOnNonOpenclawShape(t *testing.T) {
+ t.Parallel()
+
+ // rc with no `gateway` key (e.g. other providers' runtime_config) must
+ // pass through untouched.
+ rc := map[string]any{"some_other_key": "value"}
+ maskGatewayToken(rc)
+ if _, present := rc["gateway"]; present {
+ t.Errorf("must not synthesise gateway key, got %v", rc)
+ }
+}
+
+func TestPreserveMaskedGatewayTokenRestoresFromPersisted(t *testing.T) {
+ t.Parallel()
+
+ persisted := []byte(`{"mode":"gateway","gateway":{"token":"real-secret","host":"gw.internal"}}`)
+ incoming := map[string]any{
+ "mode": "gateway",
+ "gateway": map[string]any{
+ "host": "gw.internal",
+ "port": float64(18789),
+ "token": runtimeConfigGatewayTokenMask,
+ },
+ }
+ preserveMaskedGatewayToken(incoming, persisted)
+ gw := incoming["gateway"].(map[string]any)
+ if gw["token"] != "real-secret" {
+ t.Errorf("token should be restored from persisted row, got %v", gw["token"])
+ }
+}
+
+func TestPreserveMaskedGatewayTokenPassesThroughRealValue(t *testing.T) {
+ t.Parallel()
+
+ // A genuine new token in the PATCH body must overwrite the persisted one.
+ persisted := []byte(`{"gateway":{"token":"old-secret"}}`)
+ incoming := map[string]any{
+ "gateway": map[string]any{"token": "rotated-secret"},
+ }
+ preserveMaskedGatewayToken(incoming, persisted)
+ gw := incoming["gateway"].(map[string]any)
+ if gw["token"] != "rotated-secret" {
+ t.Errorf("real PATCH token must win, got %v", gw["token"])
+ }
+}
+
+func TestPreserveMaskedGatewayTokenDropsMaskWhenNoPersistedToken(t *testing.T) {
+ t.Parallel()
+
+ // A first-time gateway config that only contained host/port has no
+ // stored token. If a later PATCH sends the mask back (e.g. a UI that
+ // always includes the field), we must drop the placeholder rather than
+ // landing the literal "***" string in the database as a fake bearer.
+ persisted := []byte(`{"gateway":{"host":"gw.internal"}}`)
+ incoming := map[string]any{
+ "gateway": map[string]any{"token": runtimeConfigGatewayTokenMask},
+ }
+ preserveMaskedGatewayToken(incoming, persisted)
+ gw := incoming["gateway"].(map[string]any)
+ if _, present := gw["token"]; present {
+ t.Errorf("token must be dropped, got %v", gw["token"])
+ }
+}
+
+// Round-trip: marshal a runtime_config, mask it, ensure it stays a valid
+// shape that can survive json.Marshal again (no NaNs, no funny types).
+func TestMaskGatewayTokenRoundTripsAsJSON(t *testing.T) {
+ t.Parallel()
+
+ raw := []byte(`{"gateway":{"token":"plaintext","host":"gw"}}`)
+ var rc any
+ if err := json.Unmarshal(raw, &rc); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ maskGatewayToken(rc)
+ out, err := json.Marshal(rc)
+ if err != nil {
+ t.Fatalf("marshal after mask: %v", err)
+ }
+ if string(out) == string(raw) {
+ t.Errorf("mask should change the bytes, got %q", out)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index ac049ffa2c..0109212235 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1,6 +1,7 @@
package handler
import (
+ "bytes"
"context"
"crypto/sha256"
"encoding/hex"
@@ -1131,6 +1132,14 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
if agent.McpConfig != nil {
mcpConfig = json.RawMessage(agent.McpConfig)
}
+ // runtime_config is stored as JSONB and may legitimately be the
+ // empty object `{}` for agents that haven't opted into any
+ // provider-specific tuning. Forward only non-empty payloads so the
+ // daemon's per-provider decoders treat absent-or-empty identically.
+ var runtimeConfig json.RawMessage
+ if rc := bytes.TrimSpace(agent.RuntimeConfig); len(rc) > 0 && !bytes.Equal(rc, []byte("{}")) && !bytes.Equal(rc, []byte("null")) {
+ runtimeConfig = json.RawMessage(agent.RuntimeConfig)
+ }
resp.Agent = &TaskAgentData{
ID: uuidToString(agent.ID),
Name: agent.Name,
@@ -1141,6 +1150,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
McpConfig: mcpConfig,
Model: agent.Model.String,
ThinkingLevel: agent.ThinkingLevel.String,
+ RuntimeConfig: runtimeConfig,
}
}
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index 8570f9a1ef..2f94039d36 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -46,6 +46,17 @@ type ExecOptions struct {
// field rather than fail (so MUL-2339 can grow runtime support
// incrementally without breaking unrelated agents).
ThinkingLevel string
+ // OpenclawMode chooses between local (embedded) and gateway routing for
+ // the openclaw backend. "" or "local" keeps the historical behaviour —
+ // the daemon spawns `openclaw agent --local …` and the agent loop runs
+ // in-process on the daemon host. "gateway" instructs the daemon to drop
+ // the --local flag and let openclaw route the turn through a Gateway (the
+ // user's globally-configured one, or an endpoint pinned in the per-task
+ // config wrapper that the daemon writes from execenv.OpenclawGatewayPin —
+ // see server/internal/daemon/execenv/openclaw_config.go). Other backends
+ // ignore this field, mirroring ThinkingLevel's renderer-side fall-through
+ // pattern. See issue #3260.
+ OpenclawMode string
}
// runContext derives the execution context for an agent subprocess from the
diff --git a/server/pkg/agent/openclaw.go b/server/pkg/agent/openclaw.go
index 1f5ce366a1..5ba51adeae 100644
--- a/server/pkg/agent/openclaw.go
+++ b/server/pkg/agent/openclaw.go
@@ -175,8 +175,21 @@ func (b *openclawBackend) Execute(ctx context.Context, prompt string, opts ExecO
// registration time via `openclaw agents add/update --model`, and instructions
// must be injected inline into --message because openclaw loads AGENTS.md from
// its own workspace directory, not from cwd.
+//
+// Routing (issue #3260): `openclaw agent` defaults to Gateway routing; --local
+// is the embedded-mode opt-in. The daemon historically forced --local so every
+// run executed in-process on the daemon host. When opts.OpenclawMode ==
+// "gateway" the daemon drops --local so openclaw dials its configured Gateway
+// instead — useful when the daemon host is a lightweight coordinator and the
+// real agent work should land on a remote machine running the Gateway.
+// --local stays in openclawBlockedArgs so users cannot smuggle it back in via
+// custom_args under gateway mode (mode is the single source of truth).
func buildOpenclawArgs(prompt, sessionID string, opts ExecOptions, logger *slog.Logger) []string {
- args := []string{"agent", "--local", "--json", "--session-id", sessionID}
+ args := []string{"agent"}
+ if opts.OpenclawMode != "gateway" {
+ args = append(args, "--local")
+ }
+ args = append(args, "--json", "--session-id", sessionID)
if opts.Timeout > 0 {
args = append(args, "--timeout", fmt.Sprintf("%d", int(opts.Timeout.Seconds())))
}
diff --git a/server/pkg/agent/openclaw_test.go b/server/pkg/agent/openclaw_test.go
index 72cac9594a..9ebbc1d138 100644
--- a/server/pkg/agent/openclaw_test.go
+++ b/server/pkg/agent/openclaw_test.go
@@ -1083,6 +1083,63 @@ func TestBuildOpenclawArgsFiltersBlockedCustomArgs(t *testing.T) {
}
}
+// ── Mode matrix (issue #3260) ──
+//
+// `openclaw agent` runs through the Gateway by default; `--local` is the
+// embedded-mode escape hatch. Multica historically hard-coded `--local` so
+// every spawn went embedded. The OpenclawMode field lets a user-configured
+// agent opt into Gateway routing by setting mode="gateway" in runtime_config.
+
+func TestBuildOpenclawArgsLocalModeIsDefault(t *testing.T) {
+ t.Parallel()
+
+ // Both empty and explicit "local" must keep the historical --local
+ // behaviour so existing agents do not silently change routing.
+ for _, mode := range []string{"", "local"} {
+ args := buildOpenclawArgs("do work", "ses-local", ExecOptions{
+ OpenclawMode: mode,
+ }, slog.Default())
+ if idx := indexOf(args, "--local"); idx == -1 {
+ t.Errorf("mode=%q: expected --local in args, got %v", mode, args)
+ }
+ }
+}
+
+func TestBuildOpenclawArgsGatewayModeDropsLocal(t *testing.T) {
+ t.Parallel()
+
+ args := buildOpenclawArgs("do work", "ses-gw", ExecOptions{
+ OpenclawMode: "gateway",
+ }, slog.Default())
+
+ if idx := indexOf(args, "--local"); idx != -1 {
+ t.Errorf("gateway mode must not append --local, got %v", args)
+ }
+ // Daemon-managed flags must still be present so the run is well-formed.
+ for _, want := range []string{"agent", "--json", "--session-id", "--message"} {
+ if idx := indexOf(args, want); idx == -1 {
+ t.Errorf("gateway mode dropped daemon-managed flag %q: %v", want, args)
+ }
+ }
+}
+
+func TestBuildOpenclawArgsGatewayModeStillFiltersLocalFromCustomArgs(t *testing.T) {
+ t.Parallel()
+
+ // Mode is the single source of truth for local/gateway routing. A user
+ // trying to re-introduce --local via custom_args under gateway mode is
+ // expressing contradictory intent; the filter wins so the run actually
+ // reaches the gateway as the agent config requested.
+ args := buildOpenclawArgs("do work", "ses-mix", ExecOptions{
+ OpenclawMode: "gateway",
+ CustomArgs: []string{"--local"},
+ }, slog.Default())
+
+ if idx := indexOf(args, "--local"); idx != -1 {
+ t.Errorf("gateway mode must filter custom_args --local, got %v", args)
+ }
+}
+
func TestOpenclawProcessOutputExtractsModelFromAgentMeta(t *testing.T) {
t.Parallel()