File size: 8,292 Bytes
fcd8223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import fs from "node:fs";
import path from "node:path";
import { afterAll, afterEach, assert, describe, expect, it } from "vitest";
import { loadBundledCapabilityRuntimeRegistry } from "./bundled-capability-runtime.js";
import { setGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot.js";
import type { PluginDiscoveryResult } from "./discovery.js";
import {
  cleanupPluginLoaderFixturesForTest,
  makePluginLoaderTempDir,
  resetPluginLoaderTestStateForTest,
  type TempPlugin,
  writePlugin,
} from "./loader.test-fixtures.js";
import { createPluginCache, withPluginCache } from "./plugin-cache.js";
import {
  completePluginMetadataSnapshot,
  loadPluginMetadataSnapshot,
} from "./plugin-metadata-snapshot.js";
import { createEmptyPluginRegistry } from "./registry-empty.js";
import {
  captureActivePluginRegistrySnapshot,
  getActivePluginRegistry,
  getPluginRegistrationContext,
  listImportedRuntimePluginIds,
  setActivePluginRegistry,
} from "./runtime.js";

afterEach(resetPluginLoaderTestStateForTest);
afterAll(cleanupPluginLoaderFixturesForTest);

function discoveryFor(...plugins: TempPlugin[]): PluginDiscoveryResult {
  return {
    candidates: plugins.map((plugin) => ({
      idHint: plugin.id,
      rootDir: plugin.dir,
      source: plugin.file,
      origin: "bundled",
    })),
    diagnostics: [],
  };
}

function writeChannelCapabilityPlugin(id: string): TempPlugin {
  const plugin = writePlugin({
    id,
    body: `module.exports = {
      id: ${JSON.stringify(id)},
      register(api) {
        if (api.registrationMode === "discovery") {
          api.registerTranscriptSourceProvider({
            id: ${JSON.stringify(`${id}-voice`)},
            name: "Voice transcripts",
            sourceKinds: ["meeting"],
          });
        }
      },
    };`,
  });
  fs.writeFileSync(
    path.join(plugin.dir, "openclaw.plugin.json"),
    JSON.stringify(
      {
        id,
        channels: [id],
        configSchema: { type: "object", additionalProperties: false, properties: {} },
      },
      null,
      2,
    ),
  );
  return plugin;
}

describe("loadBundledCapabilityRuntimeRegistry", () => {
  it("retains the bundled owner under an external shadow without rediscovering changed manifests", () => {
    const root = makePluginLoaderTempDir();
    const bundledRoot = path.join(root, "bundled");
    const target = writePlugin({
      id: "shadowed-capability",
      dir: path.join(bundledRoot, "shadowed-capability"),
      registration: `api.registerProvider({ id: "bundled-capability", label: "Bundled owner", auth: [] });`,
    });
    fs.writeFileSync(
      path.join(target.dir, "package.json"),
      JSON.stringify({
        name: "@fixture/shadowed-capability",
        openclaw: { extensions: ["./shadowed-capability.cjs"] },
      }),
    );
    const shadow = writePlugin({
      id: target.id,
      body: 'throw new Error("external shadow imported");',
    });
    const config = { plugins: { load: { paths: [shadow.dir] } } };
    const env = {
      OPENCLAW_HOME: path.join(root, "home"),
      OPENCLAW_BUNDLED_PLUGINS_DIR: bundledRoot,
    };
    const snapshot = completePluginMetadataSnapshot({
      snapshot: loadPluginMetadataSnapshot({ config, env, preferPersisted: false }),
      config,
      env,
    });
    assert(snapshot);
    expect(snapshot.byPluginId.get(target.id)?.origin).toBe("config");
    expect(
      snapshot.bundledManifestRegistry?.plugins.find((plugin) => plugin.id === target.id)?.origin,
    ).toBe("bundled");
    setGatewayPluginMetadataSnapshot(snapshot, { config, env });
    fs.writeFileSync(path.join(target.dir, "openclaw.plugin.json"), "{}");

    const registry = loadBundledCapabilityRuntimeRegistry({ pluginIds: [target.id], config, env });
    expect(registry.providers.map((entry) => entry.provider.id)).toEqual(["bundled-capability"]);
    expect(registry.plugins.find((plugin) => plugin.id === target.id)?.origin).toBe("bundled");
    const loadExplicitDiscovery = () =>
      loadBundledCapabilityRuntimeRegistry({
        pluginIds: [target.id],
        config,
        env,
        discovery: discoveryFor(target),
      });
    expect(loadExplicitDiscovery().providers.map((entry) => entry.provider.id)).toEqual([
      "bundled-capability",
    ]);
    const freshRegistry = withPluginCache(createPluginCache(), loadExplicitDiscovery);
    expect(freshRegistry.providers).toEqual([]);
    expect(freshRegistry.diagnostics).toEqual(
      expect.arrayContaining([
        expect.objectContaining({ pluginId: target.id, message: "plugin manifest requires id" }),
      ]),
    );
    expect(
      loadBundledCapabilityRuntimeRegistry({ pluginIds: [target.id], config, env }).providers.map(
        (entry) => entry.provider.id,
      ),
    ).toEqual(["bundled-capability"]);
  });

  it("loads only the requested bundled plugin without replacing the active registry", () => {
    const target = writePlugin({
      id: "capability-target",
      registration: `if (api.registrationMode === "discovery") {
        api.registerProvider({ id: "capability-target", label: "Target", auth: [] });
      }
      if (api.registrationMode === "full") {
        api.registerProvider({ id: "full-only", label: "Full only", auth: [] });
      }`,
    });
    const unscoped = writePlugin({
      id: "capability-unscoped",
      body: `module.exports = {
        id: "capability-unscoped",
        register() { throw new Error("unscoped plugin loaded"); },
      };`,
    });
    const active = createEmptyPluginRegistry();
    setActivePluginRegistry(active, "existing-registry");
    const activeSnapshotBefore = captureActivePluginRegistrySnapshot();
    const registrationContextBefore = getPluginRegistrationContext();

    const registry = loadBundledCapabilityRuntimeRegistry({
      pluginIds: [target.id],
      discovery: discoveryFor(target, unscoped),
    });

    expect(registry.plugins.map((plugin) => plugin.id)).toEqual([target.id]);
    expect(registry.plugins[0]?.status).toBe("loaded");
    expect(registry.providers.map((entry) => entry.provider.id)).toEqual([target.id]);
    expect(getActivePluginRegistry()).toBe(active);
    expect(captureActivePluginRegistrySnapshot()).toEqual(activeSnapshotBefore);
    expect(getPluginRegistrationContext()).toBe(registrationContextBefore);
    expect(listImportedRuntimePluginIds()).toContain(target.id);
  });

  it.each([
    {
      name: "explicitly disabled",
      plugins: { entries: { "blocked-capability": { enabled: false } } },
    },
    { name: "denylisted", plugins: { deny: ["blocked-capability"] } },
    { name: "outside the restrictive allowlist", plugins: { allow: ["allowed-capability"] } },
    { name: "blocked by global plugin disablement", plugins: { enabled: false } },
  ])("never imports a $name plugin through bundled capability capture", ({ plugins }) => {
    const blocked = writePlugin({
      id: "blocked-capability",
      registration: `api.registerProvider({ id: "blocked-capability", label: "Blocked", auth: [] });`,
    });

    const registry = loadBundledCapabilityRuntimeRegistry({
      pluginIds: [blocked.id],
      config: { plugins },
      discovery: discoveryFor(blocked),
    });

    expect(registry.providers).toEqual([]);
    expect(listImportedRuntimePluginIds()).not.toContain(blocked.id);
  });

  it("registers channel capabilities during discovery without replacing the active registry", () => {
    const target = writeChannelCapabilityPlugin("capability-channel");
    const active = createEmptyPluginRegistry();
    setActivePluginRegistry(active, "existing-channel-registry");
    const registry = loadBundledCapabilityRuntimeRegistry({
      pluginIds: [target.id],
      discovery: discoveryFor(target),
    });

    const plugin = registry.plugins.find((entry) => entry.id === target.id);
    expect(
      plugin?.status,
      JSON.stringify({ plugin, diagnostics: registry.diagnostics }, null, 2),
    ).toBe("loaded");
    expect(plugin?.transcriptSourceProviderIds).toEqual([`${target.id}-voice`]);
    expect(registry.transcriptSourceProviders.map((entry) => entry.provider.id)).toEqual([
      `${target.id}-voice`,
    ]);
    expect(registry.typedHooks).toEqual([]);
    expect(getActivePluginRegistry()).toBe(active);
  });
});