Skip to content

Commit d17bbfc

Browse files
authored
feat(nodes): expose plugin duplex channels (#126961)
* feat(nodes): expose plugin duplex channels * fix(nodes): enforce duplex declarations
1 parent 32fb2fc commit d17bbfc

29 files changed

Lines changed: 2496 additions & 60 deletions

‎docs/plugins/sdk-runtime.md‎

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,95 @@ snapshots; OpenClaw owns all persistence and lifecycle coordination.
507507
in-flight requests and release local resources. Existing calls that omit the
508508
signal retain their previous behavior.
509509

510+
Gateway-loaded plugins can open a connection-scoped binary channel to a
511+
registered node-host command with `nodes.openDuplex(...)`:
512+
513+
```typescript
514+
const controller = new AbortController();
515+
const channel = await api.runtime.nodes.openDuplex({
516+
nodeId: "paired-node",
517+
command: "my-plugin.image-bridge",
518+
params: { format: "png" },
519+
timeoutMs: 30000,
520+
maxMessageBytes: 4 * 1024 * 1024,
521+
signal: controller.signal,
522+
});
523+
524+
const unsubscribe = channel.onMessage((message: Uint8Array) => {
525+
console.log("Received one complete binary message:", message.byteLength);
526+
});
527+
528+
try {
529+
await channel.send(Uint8Array.of(1, 2, 3));
530+
const result = await channel.closed;
531+
} finally {
532+
unsubscribe();
533+
channel.close();
534+
}
535+
```
536+
537+
`openDuplex` accepts the same node, command, parameters, timeout,
538+
idempotency key, session key, caller signal, and requested scopes as
539+
`nodes.invoke`, plus an optional `maxMessageBytes`. The limit defaults to
540+
100 MiB and can be reduced, but never increased beyond 100 MiB. OpenClaw
541+
splits each binary message into ordered 8 KiB payload fragments that fit the
542+
existing 16 KiB transport-frame limit; callers always send and receive
543+
complete `Uint8Array` messages. Concurrent sends preserve message
544+
boundaries.
545+
546+
Register the channel's single message listener immediately after
547+
`openDuplex` resolves. Before a listener is registered, OpenClaw buffers at
548+
most eight complete messages and 1 MiB total; exceeding either limit closes
549+
the invocation. The unsubscribe callback removes that listener. Listeners
550+
may return `Promise<void>`; a thrown error or rejected promise, caller
551+
abort, `close()`, node disconnect, pairing change, plugin reload or
552+
retirement, or Gateway shutdown closes the channel and cancels outstanding
553+
node work. Successful node command completion and `channel.closed` wait
554+
for asynchronous message listeners already in progress. `close()` is
555+
idempotent, and retained channel methods reject after closure.
556+
`channel.closed` resolves with the successful command result or rejects
557+
with the node, authorization, transport, or cancellation error. Channels
558+
cannot reconnect or survive a node disconnection.
559+
560+
The node plugin declares `duplex: true` and registers a message listener
561+
through the optional framed command I/O capability:
562+
563+
```typescript
564+
api.registerNodeHostCommand({
565+
command: "my-plugin.image-bridge",
566+
duplex: true,
567+
async handle(_paramsJSON, io) {
568+
if (!io?.frames) {
569+
throw new Error("Framed node command I/O is unavailable.");
570+
}
571+
572+
const frames = io.frames;
573+
return await new Promise<string>((resolve, reject) => {
574+
frames.onMessage((message) => {
575+
void frames.send(message).then(() => resolve('{"ok":true}'), reject);
576+
});
577+
io.signal.addEventListener(
578+
"abort",
579+
() => reject(new Error("Node command was canceled.")),
580+
{ once: true },
581+
);
582+
});
583+
},
584+
});
585+
```
586+
587+
Register `frames.onMessage(...)` before sending: the node announces framed
588+
readiness only after the listener exists, and `openDuplex` resolves only
589+
after both command dispatch and framed readiness. This prevents input from
590+
arriving before the plugin can consume it. The existing raw `emitChunk`
591+
and `onInput` helpers remain available to terminal-style commands.
592+
593+
`openDuplex` is available only to a current, trusted in-process Gateway
594+
plugin runtime. Plugin CLI runtimes reject it with an actionable error;
595+
there is no remote polling or local fallback. Every invocation uses the
596+
same pairing, declared-command allowlist, plugin policy, approval,
597+
authorization, and connection-ownership checks as `nodes.invoke`.
598+
510599
`nodes.list(...)` includes each connected node's advertised
511600
`nodePluginTools` descriptors when that node exposes plugin or MCP-backed
512601
tools to the agent. Those descriptors are live connection state: the Gateway
@@ -518,7 +607,7 @@ snapshots; OpenClaw owns all persistence and lifecycle coordination.
518607
Plugins that expose node-hosted agent tools can set `agentTool.defaultPlatforms` for non-dangerous commands that should be allowlisted by default. Omit it when operators must opt in with `gateway.nodes.commands.allow`. Dangerous node-host commands should register a node-invoke policy with `api.registerNodeInvokePolicy(...)`; the policy runs in the Gateway after command allowlist checks and before the command is forwarded to the node, so direct `node.invoke` calls, node-hosted plugin tools, and higher-level plugin tools share the same enforcement path.
519608

520609
<Warning>
521-
The optional `scopes` field requests Gateway operator scopes for the invocation. OpenClaw honors it only for bundled plugins and trusted official plugin installations; requests from other plugins do not elevate the call. Use it only when a trusted plugin must invoke a node command with a stricter Gateway scope, such as `operator.admin`.
610+
The optional `scopes` field requests Gateway operator scopes for the invocation. OpenClaw honors it only for bundled plugins and trusted official plugin installations; requests from other plugins do not elevate the call. When `openDuplex` runs inside an authenticated Gateway request, its effective scopes never exceed that authenticated caller's actual scopes, even if a trusted plugin requests stronger scopes. Without an authenticated incoming client, existing trusted-plugin scope behavior applies. Use requested scopes only when a trusted plugin must invoke a node command with a stricter Gateway scope, such as `operator.admin`.
522611
</Warning>
523612

524613
</Accordion>

‎extensions/canvas/src/widget-presenter.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ function createNodesRuntime(
1010
return {
1111
list: vi.fn(async () => ({ nodes })),
1212
invoke: vi.fn(async () => ({ ok: true })),
13+
openDuplex: vi.fn(),
1314
};
1415
}
1516

‎src/gateway/node-invoke-plugin-policy.test.ts‎

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ function createContext(opts?: {
6969
const invoke = vi.fn(
7070
async (params?: {
7171
onDispatchReady?: (invokeId: string) => void;
72+
onProgress?: (chunk: string) => void;
73+
isDispatchAuthorized?: () => boolean;
7274
}): Promise<NodeInvokeResult> => {
7375
params?.onDispatchReady?.("invoke-1");
7476
return {
@@ -84,7 +86,11 @@ function createContext(opts?: {
8486
getRuntimeConfig:
8587
opts?.getRuntimeConfig ??
8688
(() => ({ gateway: { nodes: { commands: { allow: [DEMO_COMMAND] } } } })),
87-
nodeRegistry: { get: () => nodeSession, invoke },
89+
nodeRegistry: {
90+
get: () => nodeSession,
91+
getForPairingGeneration: () => nodeSession,
92+
invoke,
93+
},
8894
broadcast: vi.fn(),
8995
broadcastToConnIds: vi.fn(),
9096
pluginApprovalManager: opts?.pluginApprovalManager,
@@ -283,6 +289,77 @@ describe("applyPluginNodeInvokePolicy", () => {
283289
});
284290
});
285291

292+
it("streams approved dangerous commands through the existing scoped policy transport", async () => {
293+
const manager = new ExecApprovalManager<PluginApprovalRequestPayload>();
294+
const nodeSession = createNodeSession();
295+
nodeSession.pairingGeneration = "paired-generation-1";
296+
const reviewer = createOperatorClient();
297+
reviewer.connId = "conn-owner-approval";
298+
setDangerousDemoCommandRegistry([
299+
createDemoPolicy(async (policyContext) => {
300+
expect(policyContext.client?.scopes).toEqual(["operator.approvals"]);
301+
const approval = await policyContext.approvals?.request({
302+
title: "Open fixture duplex",
303+
description: "Approve the declared node command",
304+
});
305+
if (approval?.decision !== "allow-once") {
306+
return { ok: false, code: "APPROVAL_DENIED", message: "node command was not approved" };
307+
}
308+
return await policyContext.invokeNode();
309+
}),
310+
]);
311+
const { context, invoke } = createContext({
312+
nodeSession,
313+
pluginApprovalManager: manager,
314+
getApprovalClientConnIds: createApprovalClientLookup([reviewer]),
315+
});
316+
let runtimeCurrent = true;
317+
const stream = {
318+
onProgress: vi.fn(),
319+
onDispatchReady: vi.fn(),
320+
idleTimeoutMs: 5_000,
321+
isRuntimeCurrent: () => runtimeCurrent,
322+
};
323+
invoke.mockImplementationOnce(async (params) => {
324+
params?.onDispatchReady?.("approved-duplex-invoke");
325+
params?.onProgress?.("approved-duplex-progress");
326+
return { ok: true, payload: { approved: true }, payloadJSON: null, error: null };
327+
});
328+
const resultPromise = applyPluginNodeInvokePolicy({
329+
context,
330+
client: {
331+
...createOperatorClient(),
332+
internal: {
333+
syntheticClient: true,
334+
pluginRuntimeOwnerId: DEMO_PLUGIN_ID,
335+
nodeInvokeStream: stream,
336+
},
337+
},
338+
nodeSession,
339+
command: DEMO_COMMAND,
340+
params: DEMO_PARAMS,
341+
nodeInvokeStream: stream,
342+
});
343+
344+
const approval = await expectSinglePendingApproval(manager);
345+
expect(invoke).not.toHaveBeenCalled();
346+
expect(manager.resolve(approval.id, "allow-once")).toBe(true);
347+
348+
await expect(resultPromise).resolves.toMatchObject({ ok: true });
349+
expect(stream.onDispatchReady).toHaveBeenCalledWith("approved-duplex-invoke");
350+
expect(stream.onProgress).toHaveBeenCalledWith("approved-duplex-progress");
351+
expect(invoke).toHaveBeenCalledWith(
352+
expect.objectContaining({
353+
expectedConnId: "conn-1",
354+
expectedPairingGeneration: "paired-generation-1",
355+
idleTimeoutMs: 5_000,
356+
}),
357+
);
358+
359+
runtimeCurrent = false;
360+
expect(invoke.mock.calls[0]?.[0]?.isDispatchAuthorized?.()).toBe(false);
361+
});
362+
286363
it("classifies exact arguments before the policy handler and transport", async () => {
287364
const policy = createDemoPolicy((ctx: OpenClawPluginNodeInvokePolicyContext) => {
288365
expect(ctx.risk).toEqual({ level: "high", family: "fixture_mutation" });

‎src/gateway/node-invoke-plugin-policy.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
buildRequestedApprovalEvent,
2525
handlePendingApprovalRequest,
2626
} from "./server-methods/approval-shared.js";
27+
import type { GatewayNodeInvokeStream } from "./server-methods/shared-types.js";
2728
import type { GatewayClient, GatewayRequestContext, RespondFn } from "./server-methods/types.js";
2829

2930
// Plugin node.invoke policies are the last gateway-side guard before a
@@ -241,6 +242,7 @@ export async function applyPluginNodeInvokePolicy(params: {
241242
signal?: AbortSignal;
242243
resolveRemainingTimeoutMs?: () => number | undefined;
243244
onNodeCommandDispatched?: () => void;
245+
nodeInvokeStream?: GatewayNodeInvokeStream;
244246
idempotencyKey?: string;
245247
isInvocationCurrent?: () => boolean | Promise<boolean>;
246248
isApprovalAuthorityActive?: () => boolean;
@@ -394,15 +396,21 @@ export async function applyPluginNodeInvokePolicy(params: {
394396
timeoutMs,
395397
...(params.signal ? { signal: params.signal } : {}),
396398
idempotencyKey: override.idempotencyKey ?? params.idempotencyKey,
399+
...(params.nodeInvokeStream && {
400+
onProgress: params.nodeInvokeStream.onProgress,
401+
idleTimeoutMs: params.nodeInvokeStream.idleTimeoutMs,
402+
}),
397403
isDispatchAuthorized: () =>
404+
(params.nodeInvokeStream?.isRuntimeCurrent() ?? true) &&
398405
(!callerIdentity ||
399406
params.context.validateAgentRuntimeApprovalAuthority?.(callerIdentity) === true) &&
400407
params.isApprovalAuthorityActive?.() !== false,
401-
onDispatchReady: () => {
408+
onDispatchReady: (invokeId) => {
402409
// Only the registry knows that the transport send succeeded. Preserve
403410
// pre-send failures as retry-safe while making later failures ambiguous.
404411
nodeCommandDispatched = true;
405412
params.onNodeCommandDispatched?.();
413+
params.nodeInvokeStream?.onDispatchReady(invokeId);
406414
},
407415
});
408416
if (!res.ok) {

0 commit comments

Comments
 (0)