Skip to content

Commit 9bcc443

Browse files
authored
fix(nodes): preserve gateway connections and local inference (#114857)
1 parent 3806c38 commit 9bcc443

12 files changed

Lines changed: 320 additions & 85 deletions

File tree

‎extensions/ollama/src/node-inference.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@ async function withOllamaServer<T>(
4242
remote_host: "https://ollama.com",
4343
details: {},
4444
},
45+
{
46+
name: "tagged-only:cloud",
47+
size: 1,
48+
details: {},
49+
},
50+
{
51+
name: "tagged-only:120b-cloud",
52+
size: 1,
53+
details: {},
54+
},
4555
{
4656
name: "chat:small",
4757
size: 500,
@@ -204,6 +214,16 @@ describe("Ollama node host inference", () => {
204214
JSON.stringify({ model: "remote:cloud", prompt: "hello" }),
205215
),
206216
).rejects.toThrow("is not a local chat model");
217+
await expect(
218+
commandByName(baseUrl, OLLAMA_CHAT_COMMAND).handle(
219+
JSON.stringify({ model: "tagged-only:cloud", prompt: "hello" }),
220+
),
221+
).rejects.toThrow("is not a local chat model");
222+
await expect(
223+
commandByName(baseUrl, OLLAMA_CHAT_COMMAND).handle(
224+
JSON.stringify({ model: "tagged-only:120b-cloud", prompt: "hello" }),
225+
),
226+
).rejects.toThrow("is not a local chat model");
207227
await expect(
208228
commandByName(baseUrl, OLLAMA_CHAT_COMMAND).handle(
209229
JSON.stringify({ model: "embedding:latest", prompt: "hello" }),
@@ -237,6 +257,15 @@ describe("Ollama node host inference", () => {
237257
});
238258

239259
describe("node_inference agent tool", () => {
260+
it("uses a flat action enum supported by local model providers", () => {
261+
const tool = createOllamaNodeInferenceTool(createTestPluginApi());
262+
const action = (tool.parameters as { properties: { action: unknown } }).properties.action;
263+
264+
expect(action).toMatchObject({ type: "string", enum: ["discover", "run"] });
265+
expect(action).not.toHaveProperty("anyOf");
266+
expect(action).not.toHaveProperty("oneOf");
267+
});
268+
240269
it("discovers models through the connected node runtime", async () => {
241270
const invoke = vi.fn(async () => ({
242271
payload: { provider: "ollama", models: [{ name: "chat:small", loaded: true }] },
@@ -283,6 +312,83 @@ describe("node_inference agent tool", () => {
283312
});
284313
});
285314

315+
it("discovers only nodes authorized for local model discovery", async () => {
316+
const invoke = vi.fn(async () => ({
317+
payload: { provider: "ollama", models: [{ name: "chat:small" }] },
318+
}));
319+
const api = createTestPluginApi({
320+
runtime: {
321+
nodes: {
322+
list: async () => ({
323+
nodes: [
324+
{
325+
nodeId: "denied-node",
326+
connected: true,
327+
commands: [OLLAMA_MODELS_COMMAND, OLLAMA_CHAT_COMMAND],
328+
invocableCommands: [],
329+
},
330+
{
331+
nodeId: "allowed-node",
332+
connected: true,
333+
commands: [OLLAMA_MODELS_COMMAND, OLLAMA_CHAT_COMMAND],
334+
invocableCommands: [OLLAMA_MODELS_COMMAND],
335+
},
336+
],
337+
}),
338+
invoke,
339+
},
340+
} as never,
341+
});
342+
343+
const result = await createOllamaNodeInferenceTool(api).execute("call-discover", {
344+
action: "discover",
345+
});
346+
347+
expect(invoke).toHaveBeenCalledOnce();
348+
expect(invoke).toHaveBeenCalledWith(expect.objectContaining({ nodeId: "allowed-node" }));
349+
expect(result.details).toMatchObject({ nodes: [{ nodeId: "allowed-node", ok: true }] });
350+
});
351+
352+
it("routes inference to the node authorized for model discovery and chat", async () => {
353+
const invoke = vi.fn(async () => ({
354+
payload: { provider: "ollama", model: "chat:small", response: "done" },
355+
}));
356+
const api = createTestPluginApi({
357+
runtime: {
358+
nodes: {
359+
list: async () => ({
360+
nodes: [
361+
{
362+
nodeId: "denied-node",
363+
connected: true,
364+
commands: [OLLAMA_MODELS_COMMAND, OLLAMA_CHAT_COMMAND],
365+
invocableCommands: [OLLAMA_MODELS_COMMAND],
366+
},
367+
{
368+
nodeId: "allowed-node",
369+
connected: true,
370+
commands: [OLLAMA_MODELS_COMMAND, OLLAMA_CHAT_COMMAND],
371+
invocableCommands: [OLLAMA_MODELS_COMMAND, OLLAMA_CHAT_COMMAND],
372+
},
373+
],
374+
}),
375+
invoke,
376+
},
377+
} as never,
378+
});
379+
380+
await createOllamaNodeInferenceTool(api).execute("call-authorized", {
381+
action: "run",
382+
model: "chat:small",
383+
prompt: "answer fast",
384+
});
385+
386+
expect(invoke).toHaveBeenCalledOnce();
387+
expect(invoke).toHaveBeenCalledWith(
388+
expect.objectContaining({ nodeId: "allowed-node", command: OLLAMA_CHAT_COMMAND }),
389+
);
390+
});
391+
286392
it("routes a run to the sole capable node", async () => {
287393
const invoke = vi.fn(async () => ({
288394
payload: { provider: "ollama", model: "chat:small", response: "done" },

‎extensions/ollama/src/node-inference.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { jsonResult } from "openclaw/plugin-sdk/channel-actions";
1+
import { jsonResult, stringEnum } from "openclaw/plugin-sdk/channel-actions";
22
import { formatErrorMessage as errorMessage } from "openclaw/plugin-sdk/error-runtime";
33
// Ollama node inference exposes local models to agents through paired node hosts.
44
import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
@@ -24,6 +24,7 @@ import {
2424
buildOllamaBaseUrlSsrFPolicy,
2525
enrichOllamaModelsWithContext,
2626
fetchOllamaModels,
27+
isOllamaCloudModel,
2728
resolveOllamaApiBase,
2829
} from "./provider-models.js";
2930

@@ -185,7 +186,7 @@ async function discoverOllamaNodeModels(
185186
throw new Error(`Ollama is not running at ${apiBase}`);
186187
}
187188
const localModels = discovered.models
188-
.filter((model) => !model.remote_host?.trim())
189+
.filter((model) => !model.remote_host?.trim() && !isOllamaCloudModel(model.name))
189190
.slice(0, MAX_DISCOVERED_MODELS);
190191
const [models, loadedNames] = await Promise.all([
191192
enrichOllamaModelsWithContext(apiBase, localModels),
@@ -247,7 +248,8 @@ async function runOllamaNodeChat(params: {
247248
const apiBase = resolveOllamaApiBase(params.baseUrl);
248249
const discovered = await fetchOllamaModels(apiBase);
249250
const localModel = discovered.models.find(
250-
(model) => model.name === params.model && !model.remote_host?.trim(),
251+
(model) =>
252+
model.name === params.model && !model.remote_host?.trim() && !isOllamaCloudModel(model.name),
251253
);
252254
const [model] = localModel ? await enrichOllamaModelsWithContext(apiBase, [localModel]) : [];
253255
if (!discovered.reachable || model?.capabilities?.includes("completion") !== true) {
@@ -424,7 +426,7 @@ const ollamaNodeInferenceToolDefinition = {
424426
"Discover and run chat-capable Ollama models installed on paired desktop/server nodes. Use action=discover first, then action=run with a node and model from that result. Inference stays on the selected node.",
425427
parameters: Type.Object(
426428
{
427-
action: Type.Union([Type.Literal("discover"), Type.Literal("run")]),
429+
action: stringEnum(["discover", "run"] as const),
428430
node: Type.Optional(
429431
Type.String({ description: "Connected node id or display name. Required when ambiguous." }),
430432
),
@@ -450,7 +452,7 @@ export function createOllamaNodeInferenceTool(api: OpenClawPluginApi): AnyAgentT
450452
const nodeQuery = readStringParam(params, "node");
451453
const listed = await api.runtime.nodes.list({ connected: true });
452454
const modelNodes = listed.nodes.filter((node) =>
453-
node.commands?.includes(OLLAMA_MODELS_COMMAND),
455+
(node.invocableCommands ?? node.commands)?.includes(OLLAMA_MODELS_COMMAND),
454456
);
455457

456458
if (action === "discover") {
@@ -494,7 +496,9 @@ export function createOllamaNodeInferenceTool(api: OpenClawPluginApi): AnyAgentT
494496
if (action !== "run") {
495497
throw new Error("action must be discover or run");
496498
}
497-
const chatNodes = modelNodes.filter((node) => node.commands?.includes(OLLAMA_CHAT_COMMAND));
499+
const chatNodes = modelNodes.filter((node) =>
500+
(node.invocableCommands ?? node.commands)?.includes(OLLAMA_CHAT_COMMAND),
501+
);
498502
const node = nodeQuery
499503
? findNode(chatNodes, nodeQuery)
500504
: chatNodes.length === 1

‎src/cli/node-cli/daemon.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ describe("runNodeDaemonInstall", () => {
121121

122122
expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
123123
expect.objectContaining({
124+
contextPath: undefined,
124125
tls: false,
125126
tlsFingerprint: undefined,
126127
}),
@@ -149,11 +150,35 @@ describe("runNodeDaemonInstall", () => {
149150

150151
expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
151152
expect.objectContaining({
153+
contextPath: "/saved",
152154
tls: true,
153155
tlsFingerprint: "saved-fingerprint",
154156
}),
155157
);
156158
});
159+
160+
it("installs an explicitly plaintext node for a saved TLS gateway", async () => {
161+
await runNodeDaemonInstall({ force: true, tls: false });
162+
163+
expect(mocks.buildNodeInstallPlan).toHaveBeenCalledWith(
164+
expect.objectContaining({
165+
host: "saved-gateway.local",
166+
port: 18789,
167+
contextPath: "/saved",
168+
tls: false,
169+
tlsFingerprint: undefined,
170+
}),
171+
);
172+
});
173+
174+
it("rejects a TLS fingerprint when installing an explicitly plaintext node", async () => {
175+
await runNodeDaemonInstall({ force: true, tls: false, tlsFingerprint: "new-fingerprint" });
176+
177+
expect(mocks.buildNodeInstallPlan).not.toHaveBeenCalled();
178+
expect(mocks.runtime.error).toHaveBeenCalledWith(
179+
expect.stringContaining("--no-tls cannot be combined with --tls-fingerprint"),
180+
);
181+
});
157182
});
158183

159184
describe("runNodeDaemonStatus", () => {

‎src/cli/node-cli/daemon.ts‎

Lines changed: 8 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
// Node-host daemon lifecycle commands for install, status, start, stop, and restart.
2-
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
32
import { colorize } from "../../../packages/terminal-core/src/theme.js";
43
import {
54
DEFAULT_GATEWAY_DAEMON_RUNTIME,
@@ -33,10 +32,10 @@ import {
3332
failIfNixDaemonInstallMode,
3433
filterDaemonEnv,
3534
formatRuntimeStatus,
36-
parsePort,
3735
resolveRuntimeStatusColor,
3836
} from "../daemon-cli/shared.js";
3937
import { formatInvalidConfigPort, formatInvalidPortOption } from "../error-format.js";
38+
import { resolveNodeGatewayOptions } from "./gateway-options.js";
4039

4140
type NodeDaemonInstallOptions = {
4241
host?: string;
@@ -78,38 +77,14 @@ function buildNodeRuntimeHints(env: NodeJS.ProcessEnv = process.env): string[] {
7877
});
7978
}
8079

81-
function resolveNodeDefaults(
82-
opts: NodeDaemonInstallOptions,
83-
config: Awaited<ReturnType<typeof loadNodeHostConfig>>,
84-
) {
85-
// CLI flags override node-host config; missing values fall back to loopback Gateway defaults.
86-
const savedHost = config?.gateway?.host || "127.0.0.1";
87-
const host = normalizeOptionalString(opts.host) || savedHost;
88-
const retargeted = opts.host !== undefined || opts.port !== undefined;
89-
const portOverride = parsePort(opts.port);
90-
if (opts.port !== undefined && portOverride === null) {
91-
return { host, port: null, retargeted, endpointChanged: false };
92-
}
93-
const savedPort = config?.gateway?.port ?? 18789;
94-
const port = portOverride ?? savedPort;
95-
const endpointChanged =
96-
(opts.host !== undefined && host !== savedHost) ||
97-
(opts.port !== undefined && port !== savedPort);
98-
const explicitContextPath = opts.contextPath !== undefined;
99-
const contextPath =
100-
normalizeOptionalString(opts.contextPath) ||
101-
(explicitContextPath || retargeted ? undefined : config?.gateway?.contextPath);
102-
return { host, port, contextPath, retargeted, endpointChanged };
103-
}
104-
10580
export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
10681
const { json, stdout, warnings, emit, fail } = createDaemonInstallActionContext(opts.json);
10782
if (failIfNixDaemonInstallMode(fail)) {
10883
return;
10984
}
11085

11186
const config = await loadNodeHostConfig();
112-
const { host, port, contextPath, endpointChanged } = resolveNodeDefaults(opts, config);
87+
const { host, port, contextPath, tls, tlsFingerprint } = resolveNodeGatewayOptions(opts, config);
11388
if (!Number.isFinite(port ?? Number.NaN) || (port ?? 0) <= 0 || (port ?? 0) > 65_535) {
11489
fail(
11590
opts.port !== undefined
@@ -118,6 +93,10 @@ export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
11893
);
11994
return;
12095
}
96+
if (opts.tls === false && opts.tlsFingerprint !== undefined) {
97+
fail("--no-tls cannot be combined with --tls-fingerprint");
98+
return;
99+
}
121100

122101
const runtimeRaw = opts.runtime ? opts.runtime : DEFAULT_GATEWAY_DAEMON_RUNTIME;
123102
if (!isGatewayDaemonRuntime(runtimeRaw)) {
@@ -148,19 +127,14 @@ export async function runNodeDaemonInstall(opts: NodeDaemonInstallOptions) {
148127
return;
149128
}
150129

151-
const tlsFingerprint =
152-
normalizeOptionalString(opts.tlsFingerprint) ||
153-
(endpointChanged ? undefined : config?.gateway?.tlsFingerprint);
154-
const inheritedTls = endpointChanged ? undefined : config?.gateway?.tls;
155-
const tls = Boolean(opts.tls) || Boolean(tlsFingerprint) || Boolean(inheritedTls);
156130
const { programArguments, workingDirectory, environment, environmentValueSources, description } =
157131
await buildNodeInstallPlan({
158132
env: process.env,
159133
host,
160134
port: port ?? 18789,
161135
contextPath,
162-
tls,
163-
tlsFingerprint: tlsFingerprint || undefined,
136+
tls: Boolean(tls),
137+
tlsFingerprint,
164138
nodeId: opts.nodeId,
165139
displayName: opts.displayName,
166140
installedAppsSharing: opts.shareInstalledApps,
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
2+
import type { NodeHostConfig } from "../../node-host/config.js";
3+
import { parsePort } from "../daemon-cli/shared.js";
4+
5+
type NodeGatewayOptions = {
6+
host?: string;
7+
port?: string | number;
8+
contextPath?: string;
9+
tls?: boolean;
10+
tlsFingerprint?: string;
11+
};
12+
13+
export function resolveNodeGatewayOptions(
14+
options: NodeGatewayOptions,
15+
config: NodeHostConfig | null,
16+
) {
17+
const savedHost = config?.gateway?.host || "127.0.0.1";
18+
const savedPort = config?.gateway?.port ?? 18789;
19+
const host = normalizeOptionalString(options.host) || savedHost;
20+
const port = options.port === undefined ? savedPort : parsePort(options.port);
21+
const endpointChanged = host !== savedHost || (port !== null && port !== savedPort);
22+
const tlsFingerprint =
23+
options.tls === false
24+
? undefined
25+
: (normalizeOptionalString(options.tlsFingerprint) ??
26+
(endpointChanged ? undefined : config?.gateway?.tlsFingerprint));
27+
const tls =
28+
typeof options.tls === "boolean"
29+
? options.tls
30+
: Boolean(tlsFingerprint) || (endpointChanged ? undefined : config?.gateway?.tls);
31+
const contextPath =
32+
normalizeOptionalString(options.contextPath) ??
33+
(options.contextPath !== undefined || endpointChanged
34+
? undefined
35+
: config?.gateway?.contextPath);
36+
37+
return { host, port, contextPath, tls, tlsFingerprint };
38+
}

0 commit comments

Comments
 (0)