Compare commits

...

5 Commits

Author SHA1 Message Date
d0b19cf116 feat: make notifyBotToken/adminUserId optional
The client never sends pairing notifications (the server does); these
Discord fields were required but unused. Make them optional + drop from
the config schema's required list. Back-compat: still accepted if set.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 15:59:08 +01:00
root
c3c11c1b27 fix: gate runtime startup behind gateway_start; migrate to current plugin SDK
Lifecycle:
- Move runtime.start() and shutdown handlers out of register() into
  api.on("gateway_start", ...) and api.on("gateway_stop", ...). register()
  runs in every CLI subprocess that loads plugins (e.g. `openclaw completion`,
  `openclaw doctor`); without this gate the runtime would open a network
  connection / bind a listener every time those one-shot commands ran.
- Drop process.once("SIGTERM"/"SIGINT") in favour of the gateway_stop hook,
  which is the documented way for plugins to react to shutdown.
- Stop relying on the non-standard `api.rootDir` field (not present on the
  current OpenClawPluginApi); compute the per-plugin data directory as
  ~/.openclaw/yonexus-client and ensure it exists before use.

Plugin SDK convention update:
- Wrap default export with definePluginEntry({ id, name, description, register })
  per the current openclaw plugin authoring contract.
- Re-type the register function to accept OpenClawPluginApi instead of the
  hand-crafted { rootDir, pluginConfig, ... } shape.
- Use focused subpath imports openclaw/plugin-sdk/plugin-entry and
  openclaw/plugin-sdk/core.
- Add openclaw as a devDependency (file:/usr/lib/node_modules/openclaw) so
  tsc resolves the SDK type subpaths at build time.
- Modernize openclaw.plugin.json: drop version/entry/permissions, add
  activation.onStartup so gateway_start fires for this plugin at boot.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 08:08:52 +00:00
6b51bc6475 Merge pull request 'dev/2026-04-08' (#1) from dev/2026-04-08 into main
Reviewed-on: #1
2026-04-13 09:34:01 +00:00
8b26919790 fix: globalThis 2026-04-10 21:58:59 +01:00
4adb187331 fix: migrate startup guard and shared state to globalThis
Module-level _clientStarted / ruleRegistry / onAuthenticatedCallbacks
reset on hot-reload (new VM context), causing a second runtime to start
and the exposed __yonexusClient API to point at orphaned objects.

- Replace let _clientStarted with _G["_yonexusClientStarted"]
- Store ruleRegistry and onAuthenticatedCallbacks under globalThis keys,
  initialising only when absent (survives hot-reload)
- Store runtime under _G["_yonexusClientRuntime"]; sendRule / submitPairingCode
  closures read it from globalThis instead of capturing a module-local ref
- Re-write __yonexusClient every register() call so closures stay current,
  but skip runtime.start() when the globalThis flag is already set

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 20:41:27 +01:00
6 changed files with 106 additions and 67 deletions

8
package-lock.json generated
View File

@@ -12,10 +12,14 @@
},
"devDependencies": {
"@types/node": "^25.5.2",
"openclaw": "file:/usr/lib/node_modules/openclaw",
"typescript": "^5.6.3",
"vitest": "^4.1.3"
}
},
"../../../../../usr/lib/node_modules/openclaw": {
"dev": true
},
"node_modules/@emnapi/core": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz",
@@ -914,6 +918,10 @@
],
"license": "MIT"
},
"node_modules/openclaw": {
"resolved": "../../../../../usr/lib/node_modules/openclaw",
"link": true
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",

View File

@@ -32,6 +32,7 @@
"devDependencies": {
"@types/node": "^25.5.2",
"typescript": "^5.6.3",
"vitest": "^4.1.3"
"vitest": "^4.1.3",
"openclaw": "file:/usr/lib/node_modules/openclaw"
}
}

View File

@@ -1,8 +1,12 @@
export interface YonexusClientConfig {
mainHost: string;
identifier: string;
notifyBotToken: string;
adminUserId: string;
/**
* Optional. The client never sends pairing notifications (the server
* does); accepted for back-compat but no longer required.
*/
notifyBotToken?: string;
adminUserId?: string;
}
export class YonexusClientConfigError extends Error {
@@ -44,15 +48,9 @@ export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
issues.push("identifier is required");
}
// Optional (back-compat): the client does not send notifications.
const rawNotifyBotToken = source.notifyBotToken;
if (!isNonEmptyString(rawNotifyBotToken)) {
issues.push("notifyBotToken is required");
}
const rawAdminUserId = source.adminUserId;
if (!isNonEmptyString(rawAdminUserId)) {
issues.push("adminUserId is required");
}
if (issues.length > 0) {
throw new YonexusClientConfigError(issues);
@@ -60,13 +58,15 @@ export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
const mainHost = (rawMainHost as string).trim();
const identifier = (rawIdentifier as string).trim();
const notifyBotToken = (rawNotifyBotToken as string).trim();
const adminUserId = (rawAdminUserId as string).trim();
return {
mainHost,
identifier,
notifyBotToken,
adminUserId
notifyBotToken: isNonEmptyString(rawNotifyBotToken)
? rawNotifyBotToken.trim()
: undefined,
adminUserId: isNonEmptyString(rawAdminUserId)
? rawAdminUserId.trim()
: undefined
};
}

View File

@@ -39,12 +39,24 @@ export {
type ClientRuleProcessor
} from "./core/rules.js";
import os from "node:os";
import path from "node:path";
import fs from "node:fs";
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
import { validateYonexusClientConfig } from "./core/config.js";
import { createYonexusClientStateStore } from "./core/state.js";
import { createClientTransport } from "./core/transport.js";
import { createYonexusClientRuntime } from "./core/runtime.js";
import { createClientRuleRegistry } from "./core/rules.js";
import { createYonexusClientRuntime, type YonexusClientRuntime } from "./core/runtime.js";
import { createClientRuleRegistry, YonexusClientRuleRegistry } from "./core/rules.js";
const _G = globalThis as Record<string, unknown>;
const _STARTED_KEY = "_yonexusClientStarted";
const _RUNTIME_KEY = "_yonexusClientRuntime";
const _REGISTRY_KEY = "_yonexusClientRegistry";
const _CALLBACKS_KEY = "_yonexusClientOnAuthCallbacks";
const PLUGIN_DATA_DIR = path.join(os.homedir(), ".openclaw", "yonexus-client");
export interface YonexusClientPluginManifest {
readonly name: "Yonexus.Client";
@@ -58,64 +70,82 @@ const manifest: YonexusClientPluginManifest = {
description: "Yonexus client plugin for cross-instance OpenClaw communication"
};
let _clientStarted = false;
export function createYonexusClientPlugin(api: OpenClawPluginApi): void {
// 1. Ensure shared state survives hot-reload — only initialise when absent
if (!(_G[_REGISTRY_KEY] instanceof YonexusClientRuleRegistry)) {
_G[_REGISTRY_KEY] = createClientRuleRegistry();
}
if (!Array.isArray(_G[_CALLBACKS_KEY])) {
_G[_CALLBACKS_KEY] = [];
}
export function createYonexusClientPlugin(api: { rootDir: string; pluginConfig: unknown }): void {
if (_clientStarted) return;
_clientStarted = true;
const ruleRegistry = _G[_REGISTRY_KEY] as YonexusClientRuleRegistry;
const onAuthenticatedCallbacks = _G[_CALLBACKS_KEY] as Array<() => void>;
const config = validateYonexusClientConfig(api.pluginConfig);
const stateStore = createYonexusClientStateStore(path.join(api.rootDir, "state.json"));
const ruleRegistry = createClientRuleRegistry();
const onAuthenticatedCallbacks: Array<() => void> = [];
let runtimeRef: ReturnType<typeof createYonexusClientRuntime> | null = null;
const transport = createClientTransport({
config,
onMessage: (msg) => {
runtimeRef?.handleMessage(msg).catch((err: unknown) => {
console.error("[yonexus-client] message handler error:", err);
});
},
onStateChange: (state) => {
runtimeRef?.handleTransportStateChange(state);
}
});
// Expose registry and helpers for other plugins loaded in the same process
(globalThis as Record<string, unknown>)["__yonexusClient"] = {
// 2. Refresh the cross-plugin API object every call so that sendRule / submitPairingCode
// closures always read the live runtime from globalThis.
_G["__yonexusClient"] = {
ruleRegistry,
sendRule: (ruleId: string, content: string): boolean =>
runtimeRef?.sendRuleMessage(ruleId, content) ?? false,
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.sendRuleMessage(ruleId, content) ?? false,
submitPairingCode: (code: string): boolean =>
runtimeRef?.submitPairingCode(code) ?? false,
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.submitPairingCode(code) ?? false,
onAuthenticated: onAuthenticatedCallbacks
};
const runtime = createYonexusClientRuntime({
config,
transport,
stateStore,
ruleRegistry,
onAuthenticated: () => {
for (const cb of onAuthenticatedCallbacks) cb();
}
});
runtimeRef = runtime;
// 3. Runtime startup — only fire when the gateway boots, not eagerly during
// register() inside one-shot CLI subprocesses (e.g. `openclaw completion`).
// Without this gate, every CLI invocation that loads plugins would open
// a WebSocket to the Yonexus server.
api.on("gateway_start", () => {
if (_G[_STARTED_KEY]) return;
_G[_STARTED_KEY] = true;
const shutdown = (): void => {
runtime.stop().catch((err: unknown) => {
fs.mkdirSync(PLUGIN_DATA_DIR, { recursive: true });
const config = validateYonexusClientConfig(api.pluginConfig);
const stateStore = createYonexusClientStateStore(path.join(PLUGIN_DATA_DIR, "state.json"));
const transport = createClientTransport({
config,
onMessage: (msg) => {
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.handleMessage(msg).catch((err: unknown) => {
console.error("[yonexus-client] message handler error:", err);
});
},
onStateChange: (state) => {
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.handleTransportStateChange(state);
}
});
const runtime = createYonexusClientRuntime({
config,
transport,
stateStore,
ruleRegistry,
onAuthenticated: () => {
for (const cb of onAuthenticatedCallbacks) cb();
}
});
_G[_RUNTIME_KEY] = runtime;
runtime.start().catch((err: unknown) => {
console.error("[yonexus-client] failed to start:", err);
});
});
api.on("gateway_stop", () => {
const runtime = _G[_RUNTIME_KEY] as YonexusClientRuntime | undefined;
runtime?.stop().catch((err: unknown) => {
console.error("[yonexus-client] shutdown error:", err);
});
};
process.once("SIGTERM", shutdown);
process.once("SIGINT", shutdown);
runtime.start().catch((err: unknown) => {
console.error("[yonexus-client] failed to start:", err);
});
}
export default createYonexusClientPlugin;
export default definePluginEntry({
id: "yonexus-client",
name: "Yonexus.Client",
description: "Yonexus client plugin for cross-instance OpenClaw communication",
register: createYonexusClientPlugin,
});
export { manifest };

View File

@@ -1,10 +1,10 @@
{
"id": "yonexus-client",
"name": "Yonexus.Client",
"version": "0.1.0",
"description": "Yonexus client plugin for cross-instance OpenClaw communication",
"entry": "./dist/Yonexus.Client/plugin/index.js",
"permissions": [],
"activation": {
"onStartup": true
},
"configSchema": {
"type": "object",
"additionalProperties": false,
@@ -14,6 +14,6 @@
"notifyBotToken": { "type": "string" },
"adminUserId": { "type": "string" }
},
"required": ["mainHost", "identifier", "notifyBotToken", "adminUserId"]
"required": ["mainHost", "identifier"]
}
}