Skip to content

Commit f512082

Browse files
authored
refactor(canvas): reuse canonical node CLI helpers (#135303)
1 parent 111b771 commit f512082

9 files changed

Lines changed: 154 additions & 69 deletions

File tree

‎docs/plugins/sdk-overview.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,18 @@ For paired-node features, prefer
623623
`api.registerCli(..., { parentPath: ["nodes"] })` and makes commands such as
624624
`openclaw nodes canvas` explicit plugin-owned node features.
625625

626+
Reuse the core node CLI owners when a plugin-owned node command needs the same
627+
Gateway flags, invoke envelope, terminal presentation, and authorization hints:
628+
629+
```typescript
630+
import {
631+
buildNodeInvokeParams,
632+
getNodesTheme,
633+
nodesCallOpts,
634+
runNodesCommand,
635+
} from "openclaw/plugin-sdk/node-cli-runtime";
636+
```
637+
626638
If you want a plugin command to stay lazy-loaded in the normal root CLI path,
627639
provide `descriptors` that cover every top-level command root exposed by that
628640
registrar.

‎docs/plugins/sdk-subpaths.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@ Use `isLoopbackHost(host)` when a plugin must accept only the local machine. It
263263
| `plugin-sdk/node-selection-runtime` | Private-local bundled runtime facade for shared capability-gated node selection policy |
264264
| `plugin-sdk/cli-argv` | Dependency-light root-option parsing for CLI metadata, including `getRootOptionAwareCommandPath` and `consumeRootOptionToken` |
265265
| `plugin-sdk/cli-runtime` | Private-local after July 2026; Deprecated broad barrel for CLI formatting, wait, version, argument-invocation, and lazy command-group helpers; prefer focused CLI/runtime subpaths |
266+
| `plugin-sdk/node-cli-runtime` | Shared node CLI Gateway options, invoke envelope, terminal presentation, and authorization-hint error handling for plugin-owned node commands |
266267
| `plugin-sdk/qa-runner-runtime` | Private-local after July 2026; Supported facade exposing plugin QA scenarios through the CLI command surface |
267268
| `plugin-sdk/tts-runtime` | Private-local after July 2026; Supported facade for text-to-speech config schemas and runtime helpers |
268269
| `plugin-sdk/gateway-config-runtime` | Private-local bundled runtime facade for dependency-light Gateway port resolution (`resolveGatewayPort`); not for third-party plugins |

‎extensions/canvas/src/cli.ts‎

Lines changed: 10 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
/**
22
* Canvas node CLI command registration and runtime dependency wiring.
33
*/
4-
import { randomUUID } from "node:crypto";
54
import type { Command } from "commander";
6-
import { runCommandWithRuntime, theme } from "openclaw/plugin-sdk/cli-runtime";
7-
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
85
import {
96
callGatewayFromCli,
107
isGatewayClientRequestError,
118
resolveNodeFromNodeList,
129
type NodeMatchCandidate,
1310
} from "openclaw/plugin-sdk/gateway-runtime";
11+
import {
12+
buildNodeInvokeParams,
13+
getNodesTheme,
14+
nodesCallOpts,
15+
runNodesCommand,
16+
} from "openclaw/plugin-sdk/node-cli-runtime";
1417
import {
1518
addTimerTimeoutGraceMs,
1619
clampPositiveTimerTimeoutMs,
1720
parseStrictFiniteNumber,
1821
parseStrictPositiveInteger,
1922
} from "openclaw/plugin-sdk/number-runtime";
2023
import { defaultRuntime } from "openclaw/plugin-sdk/runtime";
21-
import {
22-
normalizeLowercaseStringOrEmpty,
23-
normalizeOptionalString,
24-
} from "openclaw/plugin-sdk/string-coerce-runtime";
24+
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
2525

2626
/** Runtime output surface used by Canvas CLI commands. */
2727
type CanvasCliRuntime = {
@@ -136,33 +136,8 @@ function parseNodeCandidates(raw: unknown): CanvasNodeCandidate[] {
136136
.filter((entry): entry is CanvasNodeCandidate => entry !== null);
137137
}
138138

139-
function unauthorizedHintForMessage(message: string): string | null {
140-
const haystack = normalizeLowercaseStringOrEmpty(message);
141-
if (
142-
haystack.includes("unauthorizedclient") ||
143-
haystack.includes("bridge client is not authorized") ||
144-
haystack.includes("unsigned bridge clients are not allowed")
145-
) {
146-
return [
147-
"peekaboo bridge rejected the client.",
148-
"sign the peekaboo CLI (TeamID Y5PE65HELJ) or launch the host with",
149-
"PEEKABOO_ALLOW_UNSIGNED_SOCKET_CLIENTS=1 for local dev.",
150-
].join(" ");
151-
}
152-
return null;
153-
}
154-
155139
/** Creates the default Canvas CLI dependency bundle backed by the OpenClaw gateway CLI. */
156140
export function createDefaultCanvasCliDependencies(): CanvasCliDependencies {
157-
const nodesCallOpts = (cmd: Command, defaults?: { timeoutMs?: number }) =>
158-
cmd
159-
.option(
160-
"--url <url>",
161-
"Gateway WebSocket URL (defaults to gateway.remote.url when configured)",
162-
)
163-
.option("--token <token>", "Gateway token (if required)")
164-
.option("--timeout <ms>", "Timeout in ms", String(defaults?.timeoutMs ?? 10_000))
165-
.option("--json", "Output JSON", false);
166141
const callGatewayCli: CanvasCliDependencies["callGatewayCli"] = async (
167142
method,
168143
opts,
@@ -177,17 +152,8 @@ export function createDefaultCanvasCliDependencies(): CanvasCliDependencies {
177152
return {
178153
defaultRuntime,
179154
nodesCallOpts,
180-
runNodesCommand: (label, action) =>
181-
runCommandWithRuntime(defaultRuntime, action, (err) => {
182-
const message = formatErrorMessage(err);
183-
defaultRuntime.error(theme.error(`nodes ${label} failed: ${message}`));
184-
const hint = unauthorizedHintForMessage(message);
185-
if (hint) {
186-
defaultRuntime.error(theme.warn(hint));
187-
}
188-
defaultRuntime.exit(1);
189-
}),
190-
getNodesTheme: () => ({ ok: theme.success }),
155+
runNodesCommand,
156+
getNodesTheme,
191157
parseTimeoutMs,
192158
resolveNodeId: async (opts, query) => {
193159
let raw: unknown;
@@ -206,13 +172,7 @@ export function createDefaultCanvasCliDependencies(): CanvasCliDependencies {
206172
}
207173
return resolveNodeFromNodeList(parseNodeCandidates(raw), query).nodeId;
208174
},
209-
buildNodeInvokeParams: ({ nodeId, command, params, timeoutMs }) => ({
210-
nodeId,
211-
command,
212-
params,
213-
idempotencyKey: randomUUID(),
214-
...(typeof timeoutMs === "number" && Number.isFinite(timeoutMs) ? { timeoutMs } : {}),
215-
}),
175+
buildNodeInvokeParams,
216176
callGatewayCli,
217177
};
218178
}

‎package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,10 @@
805805
"./plugin-sdk/cli-runtime": {
806806
"default": "./dist/plugin-sdk/cli-runtime.js"
807807
},
808+
"./plugin-sdk/node-cli-runtime": {
809+
"types": "./dist/plugin-sdk/node-cli-runtime.d.ts",
810+
"default": "./dist/plugin-sdk/node-cli-runtime.js"
811+
},
808812
"./plugin-sdk/cli-backend": {
809813
"default": "./dist/plugin-sdk/cli-backend.js"
810814
},

‎scripts/lib/plugin-sdk-entrypoints.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@
114114
"gateway-runtime",
115115
"cli-argv",
116116
"cli-runtime",
117+
"node-cli-runtime",
117118
"cli-backend",
118119
"claude-model-runtime",
119120
"codex-mcp-projection",

‎scripts/plugin-sdk-surface-report.mts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,8 @@ export function readPluginSdkSurfaceBudgets(env: NodeJS.ProcessEnv = process.env
199199
// +2: bounded provider streams and read-only SecretRef resolution.
200200
// +1: diagnostic flag checks without event, trace, or redaction initialization.
201201
// +1: restore the shipped read-only conversation-binding inspection facade.
202-
148,
202+
// +1: canonical node CLI owners for plugin-provided node commands.
203+
149,
203204
env,
204205
),
205206
publicExports: readPluginSdkSurfaceBudgetEnv(
@@ -335,7 +336,8 @@ export function readPluginSdkSurfaceBudgets(env: NodeJS.ProcessEnv = process.env
335336
// +2: bounded display-only error diagnostic attachment and rendering.
336337
// +1: shared presentation delivery policy for core and channel plugins.
337338
// +2: shipped conversation-binding inspection function and result type.
338-
4364,
339+
// +4: canonical node CLI option, envelope, presentation, and error owners.
340+
4368,
339341
env,
340342
),
341343
publicFunctionExports: readPluginSdkSurfaceBudgetEnv(
@@ -446,7 +448,8 @@ export function readPluginSdkSurfaceBudgets(env: NodeJS.ProcessEnv = process.env
446448
// +2: bounded display-only error diagnostic attachment and rendering.
447449
// +1: shared presentation delivery policy for core and channel plugins.
448450
// +1: shipped read-only conversation-binding inspection function.
449-
2598,
451+
// +4: canonical node CLI option, envelope, presentation, and error owners.
452+
2602,
450453
env,
451454
),
452455
publicDeprecatedExports: readPluginSdkSurfaceBudgetEnv(

‎src/cli/nodes-cli/rpc.test.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ vi.mock("../gateway-rpc.js", () => ({
1010
callGatewayFromCliWithTransport: gatewayMocks.callGatewayFromCliWithTransport,
1111
}));
1212

13-
import { resolveCliNode, resolveNodeDiagnosticsId } from "./rpc.js";
13+
import { buildNodeInvokeParams, resolveCliNode, resolveNodeDiagnosticsId } from "./rpc.js";
1414

1515
function requestError(params: {
1616
code?: string;
@@ -136,3 +136,43 @@ describe("node inventory resolution", () => {
136136
expect(gatewayMocks.callGatewayFromCliWithTransport).not.toHaveBeenCalled();
137137
});
138138
});
139+
140+
describe("node invoke envelope", () => {
141+
it("preserves caller-owned params, idempotency key, descriptors, and key order", () => {
142+
const params = { url: "openclaw://widget/local" };
143+
const result = buildNodeInvokeParams({
144+
nodeId: "mac-1",
145+
command: "canvas.present",
146+
params,
147+
idempotencyKey: "caller-supplied-key",
148+
timeoutMs: 35_000,
149+
});
150+
151+
expect(Object.keys(result)).toEqual([
152+
"nodeId",
153+
"command",
154+
"params",
155+
"idempotencyKey",
156+
"timeoutMs",
157+
]);
158+
expect(result.params).toBe(params);
159+
expect(result.idempotencyKey).toBe("caller-supplied-key");
160+
expect(Object.getOwnPropertyDescriptor(result, "params")).toEqual({
161+
value: params,
162+
writable: true,
163+
enumerable: true,
164+
configurable: true,
165+
});
166+
});
167+
168+
it("retains undefined params while generating an idempotency key", () => {
169+
const result = buildNodeInvokeParams({ nodeId: "mac-1", command: "canvas.hide" });
170+
171+
expect(Object.keys(result)).toEqual(["nodeId", "command", "params", "idempotencyKey"]);
172+
expect(Object.hasOwn(result, "params")).toBe(true);
173+
expect(result.params).toBeUndefined();
174+
expect(result.idempotencyKey).toMatch(
175+
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
176+
);
177+
});
178+
});

‎src/node-host/node-worker-bundle-installer.test.ts‎

Lines changed: 75 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1+
import type { ChildProcess } from "node:child_process";
12
import { createHash } from "node:crypto";
3+
import { channel } from "node:diagnostics_channel";
24
import fs from "node:fs/promises";
35
import http from "node:http";
46
import os from "node:os";
57
import path from "node:path";
68
import * as tar from "tar";
79
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
810
import * as openclawRoot from "../infra/openclaw-root.js";
11+
import { createDeferredCore } from "../shared/deferred.js";
912
import {
1013
DEFAULT_WORKER_BUNDLE_ARCHIVE_LIMITS,
1114
readWorkerBundleDirectoryManifest,
@@ -17,12 +20,16 @@ import { NodeWorkerBundleInstaller } from "./node-worker-bundle-installer.js";
1720
describe("node worker bundle installer", () => {
1821
let root: string;
1922
let server: http.Server | undefined;
23+
let cleanupPrewarming: (() => Promise<void>) | undefined;
2024

2125
beforeEach(async () => {
2226
root = await fs.mkdtemp(path.join(await fs.realpath(os.tmpdir()), "openclaw-node-bundle-"));
2327
});
2428

2529
afterEach(async () => {
30+
const cleanup = cleanupPrewarming;
31+
cleanupPrewarming = undefined;
32+
await cleanup?.();
2633
vi.restoreAllMocks();
2734
await new Promise<void>((resolve) => {
2835
if (!server) {
@@ -703,20 +710,25 @@ describe("node worker bundle installer", () => {
703710
).rejects.toThrow("gateway returned an unexpected worker bundle length");
704711
});
705712

706-
it("cancels prewarming and releases the namespace queue for the next install", async () => {
707-
const slowStarted = path.join(root, "slow-prewarm-started");
713+
it("cancels prewarming and releases the namespace queue for the next install", async ({
714+
signal,
715+
}) => {
708716
const slow = await bundleFixture({
709717
fixtureName: "slow",
710718
bundlePrewarm: 1,
711-
workerSource: `import fs from "node:fs";\nfs.writeFileSync(${JSON.stringify(slowStarted)}, "started");\nawait new Promise((resolve) => setTimeout(resolve, 2_000));\n`,
719+
workerSource: 'process.stdout.write("started");\nprocess.stdin.resume();\n',
712720
});
713721
const fastMarker = path.join(root, "fast-prewarm-finished");
714722
const fast = await bundleFixture({
715723
fixtureName: "fast",
716724
bundlePrewarm: 1,
717725
prewarmMarker: fastMarker,
718726
});
727+
const fastRequested = createDeferredCore();
719728
server = http.createServer((req, res) => {
729+
if (req.url?.endsWith(fast.input.build.bundleHash)) {
730+
fastRequested.resolve();
731+
}
720732
const archive = req.url?.endsWith(slow.input.build.bundleHash) ? slow.archive : fast.archive;
721733
res.writeHead(200, {
722734
"content-type": "application/octet-stream",
@@ -734,25 +746,73 @@ describe("node worker bundle installer", () => {
734746
const gatewayUrl = `ws://127.0.0.1:${address.port}`;
735747
const installer = new NodeWorkerBundleInstaller({ root });
736748
const controller = new AbortController();
749+
const cleanupController = new AbortController();
750+
const testSignal = AbortSignal.any([signal, cleanupController.signal]);
751+
const started = createDeferredCore<ChildProcess>();
752+
const children = new Map<ChildProcess, Promise<void>>();
753+
const entries = [slow, fast].map((fixture) =>
754+
path.join(
755+
root,
756+
fixture.input.gatewayNamespace,
757+
"bundles",
758+
fixture.input.build.bundleHash,
759+
"worker.mjs",
760+
),
761+
);
762+
const childProcesses = channel("child_process");
763+
const trackPrewarm = (message: unknown) => {
764+
const child = (message as { process: ChildProcess }).process;
765+
child.once("spawn", () => {
766+
if (!entries.includes(child.spawnargs[1] ?? "")) {
767+
return;
768+
}
769+
const closed = createDeferredCore();
770+
child.once("close", () => closed.resolve());
771+
children.set(child, closed.promise);
772+
if (child.spawnargs[1] === entries[0]) {
773+
child.stdout!.once("data", () => started.resolve(child));
774+
}
775+
});
776+
};
777+
childProcesses.subscribe(trackPrewarm);
737778
const first = installer.ensure({
738779
input: slow.input,
739780
gatewayUrl,
740-
signal: controller.signal,
781+
signal: AbortSignal.any([controller.signal, testSignal]),
741782
});
742-
await vi.waitFor(async () => await expect(fs.access(slowStarted)).resolves.toBeUndefined());
743-
const second = installer.ensure({ input: fast.input, gatewayUrl });
783+
const installs = [first];
784+
cleanupPrewarming = async () => {
785+
cleanupController.abort();
786+
for (const child of children.keys()) {
787+
if (child.exitCode === null && child.signalCode === null) {
788+
child.kill("SIGKILL");
789+
}
790+
}
791+
await Promise.allSettled([...installs, ...children.values()]);
792+
childProcesses.unsubscribe(trackPrewarm);
793+
};
794+
// Startup time is not the cancellation contract: hold the real child until
795+
// abort, and join its close event even when readiness or assertions fail.
796+
const slowChild = await Promise.race([
797+
started.promise,
798+
first.then(() => {
799+
throw new Error("prewarm finished before cancellation");
800+
}),
801+
]);
802+
testSignal.throwIfAborted();
803+
const second = installer.ensure({ input: fast.input, gatewayUrl, signal: testSignal });
804+
installs.push(second);
744805

745806
controller.abort(new Error("launch fenced"));
746807

747-
await expect(first).rejects.toThrow("launch fenced");
748-
await expect(
749-
Promise.race([
750-
second,
751-
new Promise<never>((_, reject) => {
752-
setTimeout(() => reject(new Error("namespace queue stayed occupied")), 750);
753-
}),
754-
]),
755-
).resolves.toEqual(fast.input.build);
808+
// Bound handoff from cancellation; acquisition precedes cold extraction and prewarm.
809+
await Promise.all([
810+
vi.waitFor(() => expect(fastRequested.promise).resolves.toBeUndefined(), { timeout: 750 }),
811+
expect(first).rejects.toThrow("launch fenced"),
812+
]);
813+
await expect(second).resolves.toEqual(fast.input.build);
814+
await children.get(slowChild);
815+
expect(slowChild.killed).toBe(true);
756816
await expect(fs.readFile(fastMarker, "utf8")).resolves.toBe("ready");
757817
});
758818
});

‎src/plugin-sdk/node-cli-runtime.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Canonical node CLI option, invocation, presentation, and error-handling owners.
2+
3+
export { getNodesTheme, runNodesCommand } from "../cli/nodes-cli/cli-utils.js";
4+
export { buildNodeInvokeParams, nodesCallOpts } from "../cli/nodes-cli/rpc.js";

0 commit comments

Comments
 (0)