refactor(cli): unify on clawdis CLI + node permissions
This commit is contained in:
110
src/cli/canvas-cli.coverage.test.ts
Normal file
110
src/cli/canvas-cli.coverage.test.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { Command } from "commander";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const callGateway = vi.fn(
|
||||
async (opts: { method?: string; params?: { command?: string } }) => {
|
||||
if (opts.method === "node.list") {
|
||||
return {
|
||||
nodes: [
|
||||
{
|
||||
nodeId: "mac-1",
|
||||
displayName: "Mac",
|
||||
platform: "macos",
|
||||
caps: ["canvas"],
|
||||
connected: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (opts.method === "node.invoke") {
|
||||
if (opts.params?.command === "canvas.eval") {
|
||||
return { payload: { result: "ok" } };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
return { ok: true };
|
||||
},
|
||||
);
|
||||
|
||||
const randomIdempotencyKey = vi.fn(() => "rk_test");
|
||||
|
||||
const runtimeLogs: string[] = [];
|
||||
const runtimeErrors: string[] = [];
|
||||
const defaultRuntime = {
|
||||
log: (msg: string) => runtimeLogs.push(msg),
|
||||
error: (msg: string) => runtimeErrors.push(msg),
|
||||
exit: (code: number) => {
|
||||
throw new Error(`__exit__:${code}`);
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("../gateway/call.js", () => ({
|
||||
callGateway: (opts: unknown) => callGateway(opts as { method?: string }),
|
||||
randomIdempotencyKey: () => randomIdempotencyKey(),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime.js", () => ({
|
||||
defaultRuntime,
|
||||
}));
|
||||
|
||||
describe("canvas-cli coverage", () => {
|
||||
it("invokes canvas.present with placement and target", async () => {
|
||||
runtimeLogs.length = 0;
|
||||
runtimeErrors.length = 0;
|
||||
callGateway.mockClear();
|
||||
randomIdempotencyKey.mockClear();
|
||||
|
||||
const { registerCanvasCli } = await import("./canvas-cli.js");
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
registerCanvasCli(program);
|
||||
|
||||
await program.parseAsync(
|
||||
[
|
||||
"canvas",
|
||||
"present",
|
||||
"--node",
|
||||
"mac-1",
|
||||
"--target",
|
||||
"https://example.com",
|
||||
"--x",
|
||||
"10",
|
||||
"--y",
|
||||
"20",
|
||||
"--width",
|
||||
"800",
|
||||
"--height",
|
||||
"600",
|
||||
],
|
||||
{ from: "user" },
|
||||
);
|
||||
|
||||
const invoke = callGateway.mock.calls.find(
|
||||
(call) => call[0]?.method === "node.invoke",
|
||||
)?.[0];
|
||||
|
||||
expect(invoke).toBeTruthy();
|
||||
expect(invoke?.params?.command).toBe("canvas.present");
|
||||
expect(invoke?.params?.idempotencyKey).toBe("rk_test");
|
||||
expect(invoke?.params?.params).toEqual({
|
||||
url: "https://example.com",
|
||||
placement: { x: 10, y: 20, width: 800, height: 600 },
|
||||
});
|
||||
});
|
||||
|
||||
it("prints canvas.eval result", async () => {
|
||||
runtimeLogs.length = 0;
|
||||
runtimeErrors.length = 0;
|
||||
callGateway.mockClear();
|
||||
|
||||
const { registerCanvasCli } = await import("./canvas-cli.js");
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
registerCanvasCli(program);
|
||||
|
||||
await program.parseAsync(["canvas", "eval", "1+1"], { from: "user" });
|
||||
|
||||
expect(runtimeErrors).toHaveLength(0);
|
||||
expect(runtimeLogs.join("\n")).toContain("ok");
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import type { Command } from "commander";
|
||||
import { callGateway, randomIdempotencyKey } from "../gateway/call.js";
|
||||
import { defaultRuntime } from "../runtime.js";
|
||||
@@ -13,6 +15,13 @@ type CanvasOpts = {
|
||||
timeout?: string;
|
||||
json?: boolean;
|
||||
node?: string;
|
||||
target?: string;
|
||||
x?: string;
|
||||
y?: string;
|
||||
width?: string;
|
||||
height?: string;
|
||||
js?: string;
|
||||
jsonl?: string;
|
||||
format?: string;
|
||||
maxWidth?: string;
|
||||
quality?: string;
|
||||
@@ -176,7 +185,21 @@ function normalizeFormat(format: string) {
|
||||
export function registerCanvasCli(program: Command) {
|
||||
const canvas = program
|
||||
.command("canvas")
|
||||
.description("Render the canvas to a snapshot via nodes");
|
||||
.description("Control node canvases (present/navigate/eval/snapshot/a2ui)");
|
||||
|
||||
const invokeCanvas = async (
|
||||
opts: CanvasOpts,
|
||||
command: string,
|
||||
params?: Record<string, unknown>,
|
||||
) => {
|
||||
const nodeId = await resolveNodeId(opts, opts.node);
|
||||
await callGatewayCli("node.invoke", opts, {
|
||||
nodeId,
|
||||
command,
|
||||
params,
|
||||
idempotencyKey: randomIdempotencyKey(),
|
||||
});
|
||||
};
|
||||
|
||||
canvasCallOpts(
|
||||
canvas
|
||||
@@ -242,4 +265,161 @@ export function registerCanvasCli(program: Command) {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
canvasCallOpts(
|
||||
canvas
|
||||
.command("present")
|
||||
.description("Show the canvas (optionally with a target URL/path)")
|
||||
.option("--node <idOrNameOrIp>", "Node id, name, or IP")
|
||||
.option("--target <urlOrPath>", "Target URL/path (optional)")
|
||||
.option("--x <px>", "Placement x coordinate")
|
||||
.option("--y <px>", "Placement y coordinate")
|
||||
.option("--width <px>", "Placement width")
|
||||
.option("--height <px>", "Placement height")
|
||||
.action(async (opts: CanvasOpts) => {
|
||||
try {
|
||||
const placement = {
|
||||
x: opts.x ? Number.parseFloat(opts.x) : undefined,
|
||||
y: opts.y ? Number.parseFloat(opts.y) : undefined,
|
||||
width: opts.width ? Number.parseFloat(opts.width) : undefined,
|
||||
height: opts.height ? Number.parseFloat(opts.height) : undefined,
|
||||
};
|
||||
const params: Record<string, unknown> = {};
|
||||
if (opts.target) params.url = String(opts.target);
|
||||
if (
|
||||
Number.isFinite(placement.x) ||
|
||||
Number.isFinite(placement.y) ||
|
||||
Number.isFinite(placement.width) ||
|
||||
Number.isFinite(placement.height)
|
||||
) {
|
||||
params.placement = placement;
|
||||
}
|
||||
await invokeCanvas(opts, "canvas.present", params);
|
||||
if (!opts.json) {
|
||||
defaultRuntime.log("canvas present ok");
|
||||
}
|
||||
} catch (err) {
|
||||
defaultRuntime.error(`canvas present failed: ${String(err)}`);
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
canvasCallOpts(
|
||||
canvas
|
||||
.command("hide")
|
||||
.description("Hide the canvas")
|
||||
.option("--node <idOrNameOrIp>", "Node id, name, or IP")
|
||||
.action(async (opts: CanvasOpts) => {
|
||||
try {
|
||||
await invokeCanvas(opts, "canvas.hide", undefined);
|
||||
if (!opts.json) {
|
||||
defaultRuntime.log("canvas hide ok");
|
||||
}
|
||||
} catch (err) {
|
||||
defaultRuntime.error(`canvas hide failed: ${String(err)}`);
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
canvasCallOpts(
|
||||
canvas
|
||||
.command("navigate")
|
||||
.description("Navigate the canvas to a URL")
|
||||
.argument("<url>", "Target URL/path")
|
||||
.option("--node <idOrNameOrIp>", "Node id, name, or IP")
|
||||
.action(async (url: string, opts: CanvasOpts) => {
|
||||
try {
|
||||
await invokeCanvas(opts, "canvas.navigate", { url });
|
||||
if (!opts.json) {
|
||||
defaultRuntime.log("canvas navigate ok");
|
||||
}
|
||||
} catch (err) {
|
||||
defaultRuntime.error(`canvas navigate failed: ${String(err)}`);
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
canvasCallOpts(
|
||||
canvas
|
||||
.command("eval")
|
||||
.description("Evaluate JavaScript in the canvas")
|
||||
.argument("[js]", "JavaScript to evaluate")
|
||||
.option("--js <code>", "JavaScript to evaluate")
|
||||
.option("--node <idOrNameOrIp>", "Node id, name, or IP")
|
||||
.action(async (jsArg: string | undefined, opts: CanvasOpts) => {
|
||||
try {
|
||||
const js = opts.js ?? jsArg;
|
||||
if (!js) throw new Error("missing --js or <js>");
|
||||
const nodeId = await resolveNodeId(opts, opts.node);
|
||||
const raw = (await callGatewayCli("node.invoke", opts, {
|
||||
nodeId,
|
||||
command: "canvas.eval",
|
||||
params: { javaScript: js },
|
||||
idempotencyKey: randomIdempotencyKey(),
|
||||
})) as unknown;
|
||||
if (opts.json) {
|
||||
defaultRuntime.log(JSON.stringify(raw, null, 2));
|
||||
return;
|
||||
}
|
||||
const payload =
|
||||
typeof raw === "object" && raw !== null
|
||||
? (raw as { payload?: { result?: string } }).payload
|
||||
: undefined;
|
||||
if (payload?.result) {
|
||||
defaultRuntime.log(payload.result);
|
||||
} else {
|
||||
defaultRuntime.log("canvas eval ok");
|
||||
}
|
||||
} catch (err) {
|
||||
defaultRuntime.error(`canvas eval failed: ${String(err)}`);
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const a2ui = canvas
|
||||
.command("a2ui")
|
||||
.description("Render A2UI content on the canvas");
|
||||
|
||||
canvasCallOpts(
|
||||
a2ui
|
||||
.command("push")
|
||||
.description("Push A2UI JSONL to the canvas")
|
||||
.option("--jsonl <path>", "Path to JSONL payload")
|
||||
.option("--node <idOrNameOrIp>", "Node id, name, or IP")
|
||||
.action(async (opts: CanvasOpts) => {
|
||||
try {
|
||||
if (!opts.jsonl) throw new Error("missing --jsonl");
|
||||
const jsonl = await fs.readFile(String(opts.jsonl), "utf8");
|
||||
await invokeCanvas(opts, "canvas.a2ui.pushJSONL", { jsonl });
|
||||
if (!opts.json) {
|
||||
defaultRuntime.log("canvas a2ui push ok");
|
||||
}
|
||||
} catch (err) {
|
||||
defaultRuntime.error(`canvas a2ui push failed: ${String(err)}`);
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
canvasCallOpts(
|
||||
a2ui
|
||||
.command("reset")
|
||||
.description("Reset A2UI renderer state")
|
||||
.option("--node <idOrNameOrIp>", "Node id, name, or IP")
|
||||
.action(async (opts: CanvasOpts) => {
|
||||
try {
|
||||
await invokeCanvas(opts, "canvas.a2ui.reset", undefined);
|
||||
if (!opts.json) {
|
||||
defaultRuntime.log("canvas a2ui reset ok");
|
||||
}
|
||||
} catch (err) {
|
||||
defaultRuntime.error(`canvas a2ui reset failed: ${String(err)}`);
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -152,9 +152,10 @@ describe("gateway-cli coverage", () => {
|
||||
programForceFail.exitOverride();
|
||||
registerGatewayCli(programForceFail);
|
||||
await expect(
|
||||
programForceFail.parseAsync(["gateway", "--port", "18789", "--force"], {
|
||||
from: "user",
|
||||
}),
|
||||
programForceFail.parseAsync(
|
||||
["gateway", "--port", "18789", "--force", "--allow-unconfigured"],
|
||||
{ from: "user" },
|
||||
),
|
||||
).rejects.toThrow("__exit__:1");
|
||||
|
||||
// Start failure (generic)
|
||||
@@ -165,9 +166,10 @@ describe("gateway-cli coverage", () => {
|
||||
const beforeSigterm = new Set(process.listeners("SIGTERM"));
|
||||
const beforeSigint = new Set(process.listeners("SIGINT"));
|
||||
await expect(
|
||||
programStartFail.parseAsync(["gateway", "--port", "18789"], {
|
||||
from: "user",
|
||||
}),
|
||||
programStartFail.parseAsync(
|
||||
["gateway", "--port", "18789", "--allow-unconfigured"],
|
||||
{ from: "user" },
|
||||
),
|
||||
).rejects.toThrow("__exit__:1");
|
||||
for (const listener of process.listeners("SIGTERM")) {
|
||||
if (!beforeSigterm.has(listener))
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
|
||||
import type { Command } from "commander";
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import { CONFIG_PATH_CLAWDIS, loadConfig } from "../config/config.js";
|
||||
import { callGateway, randomIdempotencyKey } from "../gateway/call.js";
|
||||
import { startGatewayServer } from "../gateway/server.js";
|
||||
import {
|
||||
@@ -55,6 +57,11 @@ export function registerGatewayCli(program: Command) {
|
||||
"--token <token>",
|
||||
"Shared token required in connect.params.auth.token (default: CLAWDIS_GATEWAY_TOKEN env if set)",
|
||||
)
|
||||
.option(
|
||||
"--allow-unconfigured",
|
||||
"Allow gateway start without gateway.mode=local in config",
|
||||
false,
|
||||
)
|
||||
.option(
|
||||
"--force",
|
||||
"Kill any existing listener on the target port before starting",
|
||||
@@ -135,6 +142,21 @@ export function registerGatewayCli(program: Command) {
|
||||
process.env.CLAWDIS_GATEWAY_TOKEN = String(opts.token);
|
||||
}
|
||||
const cfg = loadConfig();
|
||||
const configExists = fs.existsSync(CONFIG_PATH_CLAWDIS);
|
||||
const mode = cfg.gateway?.mode;
|
||||
if (!opts.allowUnconfigured && mode !== "local") {
|
||||
if (!configExists) {
|
||||
defaultRuntime.error(
|
||||
"Missing config. Run `clawdis setup` or set gateway.mode=local (or pass --allow-unconfigured).",
|
||||
);
|
||||
} else {
|
||||
defaultRuntime.error(
|
||||
"Gateway start blocked: set gateway.mode=local (or pass --allow-unconfigured).",
|
||||
);
|
||||
}
|
||||
defaultRuntime.exit(1);
|
||||
return;
|
||||
}
|
||||
const bindRaw = String(opts.bind ?? cfg.gateway?.bind ?? "loopback");
|
||||
const bind =
|
||||
bindRaw === "loopback" ||
|
||||
|
||||
@@ -79,7 +79,15 @@ describe("gateway SIGTERM", () => {
|
||||
|
||||
child = spawn(
|
||||
process.execPath,
|
||||
["--import", "tsx", "src/index.ts", "gateway", "--port", String(port)],
|
||||
[
|
||||
"--import",
|
||||
"tsx",
|
||||
"src/index.ts",
|
||||
"gateway",
|
||||
"--port",
|
||||
String(port),
|
||||
"--allow-unconfigured",
|
||||
],
|
||||
{
|
||||
cwd: process.cwd(),
|
||||
env: {
|
||||
|
||||
161
src/cli/nodes-cli.coverage.test.ts
Normal file
161
src/cli/nodes-cli.coverage.test.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
import { Command } from "commander";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const callGateway = vi.fn(async (opts: { method?: string }) => {
|
||||
if (opts.method === "node.list") {
|
||||
return {
|
||||
nodes: [
|
||||
{
|
||||
nodeId: "mac-1",
|
||||
displayName: "Mac",
|
||||
platform: "macos",
|
||||
caps: ["canvas"],
|
||||
connected: true,
|
||||
permissions: { screenRecording: true },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (opts.method === "node.invoke") {
|
||||
return {
|
||||
payload: {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
success: true,
|
||||
timedOut: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
const randomIdempotencyKey = vi.fn(() => "rk_test");
|
||||
|
||||
const runtimeLogs: string[] = [];
|
||||
const runtimeErrors: string[] = [];
|
||||
const defaultRuntime = {
|
||||
log: (msg: string) => runtimeLogs.push(msg),
|
||||
error: (msg: string) => runtimeErrors.push(msg),
|
||||
exit: (code: number) => {
|
||||
throw new Error(`__exit__:${code}`);
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("../gateway/call.js", () => ({
|
||||
callGateway: (opts: unknown) => callGateway(opts as { method?: string }),
|
||||
randomIdempotencyKey: () => randomIdempotencyKey(),
|
||||
}));
|
||||
|
||||
vi.mock("../runtime.js", () => ({
|
||||
defaultRuntime,
|
||||
}));
|
||||
|
||||
describe("nodes-cli coverage", () => {
|
||||
it("lists nodes via node.list", async () => {
|
||||
runtimeLogs.length = 0;
|
||||
runtimeErrors.length = 0;
|
||||
callGateway.mockClear();
|
||||
|
||||
const { registerNodesCli } = await import("./nodes-cli.js");
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
registerNodesCli(program);
|
||||
|
||||
await program.parseAsync(["nodes", "status"], { from: "user" });
|
||||
|
||||
expect(callGateway).toHaveBeenCalled();
|
||||
expect(callGateway.mock.calls[0]?.[0]?.method).toBe("node.list");
|
||||
expect(runtimeErrors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("invokes system.run with parsed params", async () => {
|
||||
runtimeLogs.length = 0;
|
||||
runtimeErrors.length = 0;
|
||||
callGateway.mockClear();
|
||||
randomIdempotencyKey.mockClear();
|
||||
|
||||
const { registerNodesCli } = await import("./nodes-cli.js");
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
registerNodesCli(program);
|
||||
|
||||
await program.parseAsync(
|
||||
[
|
||||
"nodes",
|
||||
"run",
|
||||
"--node",
|
||||
"mac-1",
|
||||
"--cwd",
|
||||
"/tmp",
|
||||
"--env",
|
||||
"FOO=bar",
|
||||
"--command-timeout",
|
||||
"1200",
|
||||
"--needs-screen-recording",
|
||||
"--invoke-timeout",
|
||||
"5000",
|
||||
"echo",
|
||||
"hi",
|
||||
],
|
||||
{ from: "user" },
|
||||
);
|
||||
|
||||
const invoke = callGateway.mock.calls.find(
|
||||
(call) => call[0]?.method === "node.invoke",
|
||||
)?.[0];
|
||||
|
||||
expect(invoke).toBeTruthy();
|
||||
expect(invoke?.params?.idempotencyKey).toBe("rk_test");
|
||||
expect(invoke?.params?.command).toBe("system.run");
|
||||
expect(invoke?.params?.params).toEqual({
|
||||
command: ["echo", "hi"],
|
||||
cwd: "/tmp",
|
||||
env: { FOO: "bar" },
|
||||
timeoutMs: 1200,
|
||||
needsScreenRecording: true,
|
||||
});
|
||||
expect(invoke?.params?.timeoutMs).toBe(5000);
|
||||
});
|
||||
|
||||
it("invokes system.notify with provided fields", async () => {
|
||||
runtimeLogs.length = 0;
|
||||
runtimeErrors.length = 0;
|
||||
callGateway.mockClear();
|
||||
|
||||
const { registerNodesCli } = await import("./nodes-cli.js");
|
||||
const program = new Command();
|
||||
program.exitOverride();
|
||||
registerNodesCli(program);
|
||||
|
||||
await program.parseAsync(
|
||||
[
|
||||
"nodes",
|
||||
"notify",
|
||||
"--node",
|
||||
"mac-1",
|
||||
"--title",
|
||||
"Ping",
|
||||
"--body",
|
||||
"Gateway ready",
|
||||
"--delivery",
|
||||
"overlay",
|
||||
],
|
||||
{ from: "user" },
|
||||
);
|
||||
|
||||
const invoke = callGateway.mock.calls.find(
|
||||
(call) => call[0]?.method === "node.invoke",
|
||||
)?.[0];
|
||||
|
||||
expect(invoke).toBeTruthy();
|
||||
expect(invoke?.params?.command).toBe("system.notify");
|
||||
expect(invoke?.params?.params).toEqual({
|
||||
title: "Ping",
|
||||
body: "Gateway ready",
|
||||
sound: undefined,
|
||||
priority: undefined,
|
||||
delivery: "overlay",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,15 @@ type NodesRpcOpts = {
|
||||
params?: string;
|
||||
invokeTimeout?: string;
|
||||
idempotencyKey?: string;
|
||||
cwd?: string;
|
||||
env?: string[];
|
||||
commandTimeout?: string;
|
||||
needsScreenRecording?: boolean;
|
||||
title?: string;
|
||||
body?: string;
|
||||
sound?: string;
|
||||
priority?: string;
|
||||
delivery?: string;
|
||||
facing?: string;
|
||||
format?: string;
|
||||
maxWidth?: string;
|
||||
@@ -49,6 +58,7 @@ type NodeListNode = {
|
||||
modelIdentifier?: string;
|
||||
caps?: string[];
|
||||
commands?: string[];
|
||||
permissions?: Record<string, boolean>;
|
||||
paired?: boolean;
|
||||
connected?: boolean;
|
||||
};
|
||||
@@ -71,6 +81,7 @@ type PairedNode = {
|
||||
platform?: string;
|
||||
version?: string;
|
||||
remoteIp?: string;
|
||||
permissions?: Record<string, boolean>;
|
||||
createdAtMs?: number;
|
||||
approvedAtMs?: number;
|
||||
};
|
||||
@@ -137,6 +148,19 @@ function parseNodeList(value: unknown): NodeListNode[] {
|
||||
return Array.isArray(obj.nodes) ? (obj.nodes as NodeListNode[]) : [];
|
||||
}
|
||||
|
||||
function formatPermissions(raw: unknown) {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const entries = Object.entries(raw as Record<string, unknown>)
|
||||
.map(([key, value]) => [String(key).trim(), value === true] as const)
|
||||
.filter(([key]) => key.length > 0)
|
||||
.sort((a, b) => a[0].localeCompare(b[0]));
|
||||
if (entries.length === 0) return null;
|
||||
const parts = entries.map(
|
||||
([key, granted]) => `${key}=${granted ? "yes" : "no"}`,
|
||||
);
|
||||
return `[${parts.join(", ")}]`;
|
||||
}
|
||||
|
||||
function normalizeNodeKey(value: string) {
|
||||
return value
|
||||
.toLowerCase()
|
||||
@@ -145,6 +169,20 @@ function normalizeNodeKey(value: string) {
|
||||
.replace(/-+$/, "");
|
||||
}
|
||||
|
||||
function parseEnvPairs(pairs: string[] | undefined) {
|
||||
if (!Array.isArray(pairs) || pairs.length === 0) return undefined;
|
||||
const env: Record<string, string> = {};
|
||||
for (const pair of pairs) {
|
||||
const idx = pair.indexOf("=");
|
||||
if (idx <= 0) continue;
|
||||
const key = pair.slice(0, idx).trim();
|
||||
const value = pair.slice(idx + 1);
|
||||
if (!key) continue;
|
||||
env[key] = value;
|
||||
}
|
||||
return Object.keys(env).length > 0 ? env : undefined;
|
||||
}
|
||||
|
||||
async function resolveNodeId(opts: NodesRpcOpts, query: string) {
|
||||
const q = String(query ?? "").trim();
|
||||
if (!q) throw new Error("node required");
|
||||
@@ -223,6 +261,8 @@ export function registerNodesCli(program: Command) {
|
||||
const ip = n.remoteIp ? ` · ${n.remoteIp}` : "";
|
||||
const device = n.deviceFamily ? ` · device: ${n.deviceFamily}` : "";
|
||||
const hw = n.modelIdentifier ? ` · hw: ${n.modelIdentifier}` : "";
|
||||
const perms = formatPermissions(n.permissions);
|
||||
const permsText = perms ? ` · perms: ${perms}` : "";
|
||||
const caps =
|
||||
Array.isArray(n.caps) && n.caps.length > 0
|
||||
? `[${n.caps.map(String).filter(Boolean).sort().join(",")}]`
|
||||
@@ -231,7 +271,7 @@ export function registerNodesCli(program: Command) {
|
||||
: "?";
|
||||
const pairing = n.paired ? "paired" : "unpaired";
|
||||
defaultRuntime.log(
|
||||
`- ${name} · ${n.nodeId}${ip}${device}${hw} · ${pairing} · ${n.connected ? "connected" : "disconnected"} · caps: ${caps}`,
|
||||
`- ${name} · ${n.nodeId}${ip}${device}${hw}${permsText} · ${pairing} · ${n.connected ? "connected" : "disconnected"} · caps: ${caps}`,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -270,6 +310,7 @@ export function registerNodesCli(program: Command) {
|
||||
const commands = Array.isArray(obj.commands)
|
||||
? obj.commands.map(String).filter(Boolean).sort()
|
||||
: [];
|
||||
const perms = formatPermissions(obj.permissions);
|
||||
const family =
|
||||
typeof obj.deviceFamily === "string" ? obj.deviceFamily : null;
|
||||
const model =
|
||||
@@ -282,6 +323,7 @@ export function registerNodesCli(program: Command) {
|
||||
if (ip) parts.push(ip);
|
||||
if (family) parts.push(`device: ${family}`);
|
||||
if (model) parts.push(`hw: ${model}`);
|
||||
if (perms) parts.push(`perms: ${perms}`);
|
||||
parts.push(connected ? "connected" : "disconnected");
|
||||
parts.push(`caps: ${caps ? `[${caps.join(",")}]` : "?"}`);
|
||||
defaultRuntime.log(parts.join(" · "));
|
||||
@@ -474,6 +516,173 @@ export function registerNodesCli(program: Command) {
|
||||
{ timeoutMs: 30_000 },
|
||||
);
|
||||
|
||||
nodesCallOpts(
|
||||
nodes
|
||||
.command("run")
|
||||
.description("Run a shell command on a node (mac only)")
|
||||
.requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP")
|
||||
.option("--cwd <path>", "Working directory")
|
||||
.option(
|
||||
"--env <key=val>",
|
||||
"Environment override (repeatable)",
|
||||
(value: string, prev: string[] = []) => [...prev, value],
|
||||
)
|
||||
.option("--command-timeout <ms>", "Command timeout (ms)")
|
||||
.option("--needs-screen-recording", "Require screen recording permission")
|
||||
.option(
|
||||
"--invoke-timeout <ms>",
|
||||
"Node invoke timeout in ms (default 30000)",
|
||||
"30000",
|
||||
)
|
||||
.argument("<command...>", "Command and args")
|
||||
.action(async (command: string[], opts: NodesRpcOpts) => {
|
||||
try {
|
||||
const nodeId = await resolveNodeId(opts, String(opts.node ?? ""));
|
||||
if (!Array.isArray(command) || command.length === 0) {
|
||||
throw new Error("command required");
|
||||
}
|
||||
const env = parseEnvPairs(opts.env);
|
||||
const timeoutMs = opts.commandTimeout
|
||||
? Number.parseInt(String(opts.commandTimeout), 10)
|
||||
: undefined;
|
||||
const invokeTimeout = opts.invokeTimeout
|
||||
? Number.parseInt(String(opts.invokeTimeout), 10)
|
||||
: undefined;
|
||||
|
||||
const invokeParams: Record<string, unknown> = {
|
||||
nodeId,
|
||||
command: "system.run",
|
||||
params: {
|
||||
command,
|
||||
cwd: opts.cwd,
|
||||
env,
|
||||
timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : undefined,
|
||||
needsScreenRecording: opts.needsScreenRecording === true,
|
||||
},
|
||||
idempotencyKey: String(
|
||||
opts.idempotencyKey ?? randomIdempotencyKey(),
|
||||
),
|
||||
};
|
||||
if (
|
||||
typeof invokeTimeout === "number" &&
|
||||
Number.isFinite(invokeTimeout)
|
||||
) {
|
||||
invokeParams.timeoutMs = invokeTimeout;
|
||||
}
|
||||
|
||||
const result = (await callGatewayCli(
|
||||
"node.invoke",
|
||||
opts,
|
||||
invokeParams,
|
||||
)) as unknown;
|
||||
|
||||
if (opts.json) {
|
||||
defaultRuntime.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
const payload =
|
||||
typeof result === "object" && result !== null
|
||||
? (result as { payload?: Record<string, unknown> }).payload
|
||||
: undefined;
|
||||
|
||||
const stdout =
|
||||
typeof payload?.stdout === "string" ? payload.stdout : "";
|
||||
const stderr =
|
||||
typeof payload?.stderr === "string" ? payload.stderr : "";
|
||||
const exitCode =
|
||||
typeof payload?.exitCode === "number" ? payload.exitCode : null;
|
||||
const timedOut = payload?.timedOut === true;
|
||||
const success = payload?.success === true;
|
||||
|
||||
if (stdout) process.stdout.write(stdout);
|
||||
if (stderr) process.stderr.write(stderr);
|
||||
if (timedOut) {
|
||||
defaultRuntime.error("run timed out");
|
||||
defaultRuntime.exit(1);
|
||||
return;
|
||||
}
|
||||
if (exitCode !== null && exitCode !== 0 && !success) {
|
||||
defaultRuntime.error(`run exit ${exitCode}`);
|
||||
defaultRuntime.exit(1);
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
defaultRuntime.error(`nodes run failed: ${String(err)}`);
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
}),
|
||||
{ timeoutMs: 35_000 },
|
||||
);
|
||||
|
||||
nodesCallOpts(
|
||||
nodes
|
||||
.command("notify")
|
||||
.description("Send a local notification on a node (mac only)")
|
||||
.requiredOption("--node <idOrNameOrIp>", "Node id, name, or IP")
|
||||
.option("--title <text>", "Notification title")
|
||||
.option("--body <text>", "Notification body")
|
||||
.option("--sound <name>", "Notification sound")
|
||||
.option(
|
||||
"--priority <passive|active|timeSensitive>",
|
||||
"Notification priority",
|
||||
)
|
||||
.option("--delivery <system|overlay|auto>", "Delivery mode", "system")
|
||||
.option(
|
||||
"--invoke-timeout <ms>",
|
||||
"Node invoke timeout in ms (default 15000)",
|
||||
"15000",
|
||||
)
|
||||
.action(async (opts: NodesRpcOpts) => {
|
||||
try {
|
||||
const nodeId = await resolveNodeId(opts, String(opts.node ?? ""));
|
||||
const title = String(opts.title ?? "").trim();
|
||||
const body = String(opts.body ?? "").trim();
|
||||
if (!title && !body) {
|
||||
throw new Error("missing --title or --body");
|
||||
}
|
||||
const invokeTimeout = opts.invokeTimeout
|
||||
? Number.parseInt(String(opts.invokeTimeout), 10)
|
||||
: undefined;
|
||||
const invokeParams: Record<string, unknown> = {
|
||||
nodeId,
|
||||
command: "system.notify",
|
||||
params: {
|
||||
title,
|
||||
body,
|
||||
sound: opts.sound,
|
||||
priority: opts.priority,
|
||||
delivery: opts.delivery,
|
||||
},
|
||||
idempotencyKey: String(
|
||||
opts.idempotencyKey ?? randomIdempotencyKey(),
|
||||
),
|
||||
};
|
||||
if (
|
||||
typeof invokeTimeout === "number" &&
|
||||
Number.isFinite(invokeTimeout)
|
||||
) {
|
||||
invokeParams.timeoutMs = invokeTimeout;
|
||||
}
|
||||
|
||||
const result = await callGatewayCli(
|
||||
"node.invoke",
|
||||
opts,
|
||||
invokeParams,
|
||||
);
|
||||
|
||||
if (opts.json) {
|
||||
defaultRuntime.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
defaultRuntime.log("notify ok");
|
||||
} catch (err) {
|
||||
defaultRuntime.error(`nodes notify failed: ${String(err)}`);
|
||||
defaultRuntime.exit(1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const parseFacing = (value: string): CameraFacing => {
|
||||
const v = String(value ?? "")
|
||||
.trim()
|
||||
|
||||
Reference in New Issue
Block a user