Compare commits

...

5 Commits

Author SHA1 Message Date
h z
b270649f21 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
8824e768fb feat: wire rule registry and authenticated callback into client runtime
- Add ruleRegistry and onAuthenticated options to YonexusClientRuntime
- Dispatch non-builtin messages to rule registry
- Fire onAuthenticated callback on auth_success
- Reload persisted state on reconnect so externally-written secrets are picked up
- Re-send hello on auth_failed("not_paired") when client has a valid secret
- Always enter waiting_pair_confirm after pair_request regardless of notification status
- Expose __yonexusClient on globalThis for cross-plugin communication
- Wire onStateChange in transport creation (previously missing, prevented connection)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-10 20:14:57 +01:00
nav
57b53fc122 Fix strict TypeScript checks for client 2026-04-09 04:38:03 +00:00
10 changed files with 167 additions and 36 deletions

View File

@@ -5,6 +5,9 @@
"description": "Yonexus.Client OpenClaw plugin scaffold", "description": "Yonexus.Client OpenClaw plugin scaffold",
"type": "module", "type": "module",
"main": "dist/plugin/index.js", "main": "dist/plugin/index.js",
"openclaw": {
"extensions": ["./dist/Yonexus.Client/plugin/index.js"]
},
"files": [ "files": [
"dist", "dist",
"plugin", "plugin",

View File

@@ -32,25 +32,25 @@ export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
const source = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>; const source = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
const issues: string[] = []; const issues: string[] = [];
const mainHost = source.mainHost; const rawMainHost = source.mainHost;
if (!isNonEmptyString(mainHost)) { if (!isNonEmptyString(rawMainHost)) {
issues.push("mainHost is required"); issues.push("mainHost is required");
} else if (!isValidWsUrl(mainHost.trim())) { } else if (!isValidWsUrl(rawMainHost.trim())) {
issues.push("mainHost must be a valid ws:// or wss:// URL"); issues.push("mainHost must be a valid ws:// or wss:// URL");
} }
const identifier = source.identifier; const rawIdentifier = source.identifier;
if (!isNonEmptyString(identifier)) { if (!isNonEmptyString(rawIdentifier)) {
issues.push("identifier is required"); issues.push("identifier is required");
} }
const notifyBotToken = source.notifyBotToken; const rawNotifyBotToken = source.notifyBotToken;
if (!isNonEmptyString(notifyBotToken)) { if (!isNonEmptyString(rawNotifyBotToken)) {
issues.push("notifyBotToken is required"); issues.push("notifyBotToken is required");
} }
const adminUserId = source.adminUserId; const rawAdminUserId = source.adminUserId;
if (!isNonEmptyString(adminUserId)) { if (!isNonEmptyString(rawAdminUserId)) {
issues.push("adminUserId is required"); issues.push("adminUserId is required");
} }
@@ -58,10 +58,15 @@ export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
throw new YonexusClientConfigError(issues); throw new YonexusClientConfigError(issues);
} }
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 { return {
mainHost: mainHost.trim(), mainHost,
identifier: identifier.trim(), identifier,
notifyBotToken: notifyBotToken.trim(), notifyBotToken,
adminUserId: adminUserId.trim() adminUserId
}; };
} }

View File

@@ -29,6 +29,7 @@ import {
} from "./state.js"; } from "./state.js";
import { generateNonce, signMessage } from "../crypto/keypair.js"; import { generateNonce, signMessage } from "../crypto/keypair.js";
import type { ClientConnectionState, ClientTransport } from "./transport.js"; import type { ClientConnectionState, ClientTransport } from "./transport.js";
import type { ClientRuleRegistry } from "./rules.js";
export type YonexusClientPhase = export type YonexusClientPhase =
| "idle" | "idle"
@@ -44,6 +45,8 @@ export interface YonexusClientRuntimeOptions {
config: YonexusClientConfig; config: YonexusClientConfig;
transport: ClientTransport; transport: ClientTransport;
stateStore: YonexusClientStateStore; stateStore: YonexusClientStateStore;
ruleRegistry?: ClientRuleRegistry;
onAuthenticated?: () => void;
now?: () => number; now?: () => number;
} }
@@ -118,6 +121,7 @@ export class YonexusClientRuntime {
} }
if (!isBuiltinMessage(raw)) { if (!isBuiltinMessage(raw)) {
this.options.ruleRegistry?.dispatch(raw);
return; return;
} }
@@ -159,6 +163,7 @@ export class YonexusClientRuntime {
}; };
await this.options.stateStore.save(this.clientState); await this.options.stateStore.save(this.clientState);
this.phase = "authenticated"; this.phase = "authenticated";
this.options.onAuthenticated?.();
return; return;
} }
@@ -177,7 +182,17 @@ export class YonexusClientRuntime {
handleTransportStateChange(state: ClientConnectionState): void { handleTransportStateChange(state: ClientConnectionState): void {
if (state === "connected") { if (state === "connected") {
this.sendHello(); // Reload state from disk before hello so that any secret written by an
// external process (e.g. a pairing script) is picked up on reconnect.
this.options.stateStore.load(this.options.config.identifier).then((fresh) => {
if (fresh) {
this.clientState = { ...this.clientState, ...fresh };
}
this.sendHello();
}).catch(() => {
// If reload fails, proceed with in-memory state
this.sendHello();
});
} }
if (state === "disconnected") { if (state === "disconnected") {
@@ -259,7 +274,10 @@ export class YonexusClientRuntime {
adminNotification: payload.adminNotification adminNotification: payload.adminNotification
}; };
this.lastPairingFailure = undefined; this.lastPairingFailure = undefined;
this.phase = payload.adminNotification === "sent" ? "waiting_pair_confirm" : "pair_required"; // Always wait for the pairing code regardless of notification status.
// When adminNotification is "failed", the admin can retrieve the code
// via the server CLI command and deliver it through an alternate channel.
this.phase = "waiting_pair_confirm";
} }
private async handlePairSuccess(envelope: TypedBuiltinEnvelope<"pair_success">): Promise<void> { private async handlePairSuccess(envelope: TypedBuiltinEnvelope<"pair_success">): Promise<void> {
@@ -316,6 +334,12 @@ export class YonexusClientRuntime {
} }
this.lastPairingFailure = payload.reason; this.lastPairingFailure = payload.reason;
// If the server lost our session (race condition), re-announce via hello
// so the server creates a new session and we can retry auth.
if (payload.reason === "not_paired" && hasClientSecret(this.clientState)) {
this.sendHello();
return;
}
this.phase = "auth_required"; this.phase = "auth_required";
} }

View File

@@ -181,7 +181,8 @@ function assertClientStateShape(
); );
} }
if (!Number.isInteger(candidate.updatedAt) || candidate.updatedAt < 0) { const updatedAt = candidate.updatedAt;
if (typeof updatedAt !== "number" || !Number.isInteger(updatedAt) || updatedAt < 0) {
throw new YonexusClientStateCorruptionError( throw new YonexusClientStateCorruptionError(
`Client state file has invalid updatedAt value: ${filePath}` `Client state file has invalid updatedAt value: ${filePath}`
); );

View File

@@ -39,30 +39,95 @@ export {
type ClientRuleProcessor type ClientRuleProcessor
} from "./core/rules.js"; } from "./core/rules.js";
import path from "node:path";
import { validateYonexusClientConfig } from "./core/config.js";
import { createYonexusClientStateStore } from "./core/state.js";
import { createClientTransport } from "./core/transport.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";
export interface YonexusClientPluginManifest { export interface YonexusClientPluginManifest {
readonly name: "Yonexus.Client"; readonly name: "Yonexus.Client";
readonly version: string; readonly version: string;
readonly description: string; readonly description: string;
} }
export interface YonexusClientPluginRuntime {
readonly hooks: readonly [];
readonly commands: readonly [];
readonly tools: readonly [];
}
const manifest: YonexusClientPluginManifest = { const manifest: YonexusClientPluginManifest = {
name: "Yonexus.Client", name: "Yonexus.Client",
version: "0.1.0", version: "0.1.0",
description: "Yonexus client plugin for cross-instance OpenClaw communication" description: "Yonexus client plugin for cross-instance OpenClaw communication"
}; };
export function createYonexusClientPlugin(): YonexusClientPluginRuntime { export function createYonexusClientPlugin(api: { rootDir: string; pluginConfig: unknown }): void {
return { // 1. Ensure shared state survives hot-reload — only initialise when absent
hooks: [], if (!(_G[_REGISTRY_KEY] instanceof YonexusClientRuleRegistry)) {
commands: [], _G[_REGISTRY_KEY] = createClientRuleRegistry();
tools: [] }
if (!Array.isArray(_G[_CALLBACKS_KEY])) {
_G[_CALLBACKS_KEY] = [];
}
const ruleRegistry = _G[_REGISTRY_KEY] as YonexusClientRuleRegistry;
const onAuthenticatedCallbacks = _G[_CALLBACKS_KEY] as Array<() => void>;
// 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 =>
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.sendRuleMessage(ruleId, content) ?? false,
submitPairingCode: (code: string): boolean =>
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.submitPairingCode(code) ?? false,
onAuthenticated: onAuthenticatedCallbacks
}; };
// 3. Start the runtime only once — the globalThis flag survives hot-reload
if (_G[_STARTED_KEY]) return;
_G[_STARTED_KEY] = true;
const config = validateYonexusClientConfig(api.pluginConfig);
const stateStore = createYonexusClientStateStore(path.join(api.rootDir, "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;
const shutdown = (): void => {
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 createYonexusClientPlugin;

View File

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

24
plugin/types/ws.d.ts vendored Normal file
View File

@@ -0,0 +1,24 @@
declare module "ws" {
export type RawData = Buffer | ArrayBuffer | Buffer[] | string;
export class WebSocket {
static readonly OPEN: number;
constructor(url: string);
readonly readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
terminate(): void;
on(event: "open", listener: () => void): this;
on(event: "message", listener: (data: RawData) => void): this;
on(event: "close", listener: (code: number, reason: Buffer) => void): this;
on(event: "error", listener: (error: Error) => void): this;
once(event: "open", listener: () => void): this;
once(event: "error", listener: (error: Error) => void): this;
off(event: "error", listener: (error: Error) => void): this;
removeAllListeners?(event?: string): this;
}
export class WebSocketServer {
constructor(options: { host?: string; port: number });
}
}

View File

@@ -29,6 +29,7 @@ if (mode === "install") {
fs.rmSync(targetDir, { recursive: true, force: true }); fs.rmSync(targetDir, { recursive: true, force: true });
fs.cpSync(sourceDist, path.join(targetDir, "dist"), { recursive: true }); fs.cpSync(sourceDist, path.join(targetDir, "dist"), { recursive: true });
fs.copyFileSync(path.join(repoRoot, "plugin", "openclaw.plugin.json"), path.join(targetDir, "openclaw.plugin.json")); fs.copyFileSync(path.join(repoRoot, "plugin", "openclaw.plugin.json"), path.join(targetDir, "openclaw.plugin.json"));
fs.copyFileSync(path.join(repoRoot, "package.json"), path.join(targetDir, "package.json"));
console.log(`Installed ${pluginName} to ${targetDir}`); console.log(`Installed ${pluginName} to ${targetDir}`);
process.exit(0); process.exit(0);
} }

View File

@@ -4,7 +4,7 @@
"module": "NodeNext", "module": "NodeNext",
"moduleResolution": "NodeNext", "moduleResolution": "NodeNext",
"outDir": "dist", "outDir": "dist",
"rootDir": ".", "rootDir": "..",
"strict": true, "strict": true,
"skipLibCheck": true, "skipLibCheck": true,
"esModuleInterop": true, "esModuleInterop": true,
@@ -15,7 +15,9 @@
}, },
"include": [ "include": [
"plugin/**/*.ts", "plugin/**/*.ts",
"servers/**/*.ts" "plugin/**/*.d.ts",
"servers/**/*.ts",
"../Yonexus.Protocol/src/**/*.ts"
], ],
"exclude": [ "exclude": [
"dist", "dist",