File size: 22,166 Bytes
4c76b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// Plugin runtime index tests cover runtime entrypoint exports and registry setup.
import { beforeEach, describe, expect, it, vi } from "vitest";
import { resolveAuthProfileOrder } from "../../agents/auth-profiles/order.js";
import { listProfilesForProvider } from "../../agents/auth-profiles/profile-list.js";
import { ensureAuthProfileStore } from "../../agents/auth-profiles/store-runtime.js";
import { DEFAULT_MODEL, DEFAULT_PROVIDER } from "../../agents/defaults.js";
import { resolveDefaultModelForAgent } from "../../agents/model-selection-config.js";
import { resolveAllowedModelRefCore } from "../../agents/model-selection-resolve.js";
import { resolveProviderIdForAuth } from "../../agents/provider-auth-aliases.js";
import {
  resetConfigRuntimeState,
  setRuntimeConfigSnapshot,
  type OpenClawConfig,
} from "../../config/config.js";
import { onAgentEvent } from "../../infra/agent-events.js";
import { requestHeartbeat, setHeartbeatWakeHandler } from "../../infra/heartbeat-wake.js";
import * as execModule from "../../process/exec.js";
import { onSessionTranscriptUpdate } from "../../sessions/transcript-events.js";
import { VERSION } from "../../version.js";
import { isProviderApiKeyConfigured } from "../provider-auth-availability.js";

const runtimeModelAuthMocks = vi.hoisted(() => ({
  getApiKeyForModel: vi.fn(),
  getRuntimeAuthForModelCore: vi.fn(),
  resolveProviderRuntimeApiKey: vi.fn(),
}));
const heartbeatRunnerMocks = vi.hoisted(() => ({ loads: 0, runHeartbeatOnce: vi.fn() }));
vi.mock("../../infra/heartbeat-runner.js", () => {
  heartbeatRunnerMocks.loads++;
  return { runHeartbeatOnce: heartbeatRunnerMocks.runHeartbeatOnce };
});

const sandboxContextMocks = vi.hoisted(() => ({
  resolveSandboxContext: vi.fn(),
}));

vi.mock("./runtime-model-auth.runtime.js", () => ({
  getApiKeyForModel: runtimeModelAuthMocks.getApiKeyForModel,
  getRuntimeAuthForModelCore: runtimeModelAuthMocks.getRuntimeAuthForModelCore,
  resolveProviderRuntimeApiKey: runtimeModelAuthMocks.resolveProviderRuntimeApiKey,
}));
vi.mock("../../agents/sandbox/context.js", () => sandboxContextMocks);

import { createPluginRuntime } from "./index.js";

function createCommandResult() {
  return {
    pid: 12345,
    stdout: "hello\n",
    stderr: "",
    code: 0,
    signal: null,
    killed: false,
    noOutputTimedOut: false,
    termination: "exit" as const,
  };
}

function createGatewaySubagentRuntime() {
  return {
    complete: vi.fn(),
    run: vi.fn(),
    waitForRun: vi.fn(),
    getSessionMessages: vi.fn(),
    deleteSession: vi.fn(),
  };
}

function expectRuntimeShape(
  assertRuntime: (runtime: ReturnType<typeof createPluginRuntime>) => void,
) {
  const runtime = createPluginRuntime();
  assertRuntime(runtime);
}

function expectGatewaySubagentRunFailure(
  runtime: ReturnType<typeof createPluginRuntime>,
  params: { sessionKey: string; message: string },
) {
  expect(() => runtime.subagent.run(params)).toThrow(
    "Plugin runtime subagent methods are only available during a gateway request.",
  );
}

function expectRuntimeValue<T>(
  readValue: (runtime: ReturnType<typeof createPluginRuntime>) => T,
  expected: T,
) {
  expect(readValue(createPluginRuntime())).toBe(expected);
}

function expectRuntimeSubagentRun(
  runtime: ReturnType<typeof createPluginRuntime>,
  params: { sessionKey: string; message: string },
) {
  return runtime.subagent.run(params);
}

function expectFunctionKeys(value: Record<string, unknown>, keys: readonly string[]) {
  for (const key of keys) {
    expect(typeof value[key]).toBe("function");
  }
}

function expectRunCommandOutcome(params: {
  runtime: ReturnType<typeof createPluginRuntime>;
  expected: "resolve" | "reject";
  commandResult: ReturnType<typeof createCommandResult>;
}) {
  const command = params.runtime.system.runCommandWithTimeout(["echo", "hello"], {
    timeoutMs: 1000,
  });
  if (params.expected === "resolve") {
    return expect(command).resolves.toEqual(params.commandResult);
  }
  return expect(command).rejects.toThrow("boom");
}

describe("plugin runtime command execution", () => {
  beforeEach(() => {
    vi.restoreAllMocks();
    runtimeModelAuthMocks.getApiKeyForModel.mockReset();
    runtimeModelAuthMocks.getRuntimeAuthForModelCore.mockReset();
    runtimeModelAuthMocks.resolveProviderRuntimeApiKey.mockReset();
    sandboxContextMocks.resolveSandboxContext.mockReset();
    resetConfigRuntimeState();
  });

  it.each([
    {
      name: "exposes runtime.system.runCommandWithTimeout by default",
      mockKind: "resolve" as const,
      expected: "resolve" as const,
    },
    {
      name: "forwards runtime.system.runCommandWithTimeout errors",
      mockKind: "reject" as const,
      expected: "reject" as const,
    },
  ] as const)("$name", async ({ mockKind, expected }) => {
    const commandResult = createCommandResult();
    const runCommandWithTimeoutMock = vi.spyOn(execModule, "runCommandWithTimeout");
    if (mockKind === "resolve") {
      runCommandWithTimeoutMock.mockResolvedValue(commandResult);
    } else {
      runCommandWithTimeoutMock.mockRejectedValue(new Error("boom"));
    }

    const runtime = createPluginRuntime();
    await expectRunCommandOutcome({ runtime, expected, commandResult });
    expect(runCommandWithTimeoutMock).toHaveBeenCalledWith(["echo", "hello"], { timeoutMs: 1000 });
  });

  it("defers heartbeat execution and forwards only plugin-safe options", async () => {
    const system = createPluginRuntime().system;
    expect(heartbeatRunnerMocks.loads).toBe(0);
    const result = { status: "skipped", reason: "disabled" };
    heartbeatRunnerMocks.runHeartbeatOnce.mockResolvedValueOnce(result);
    await expect(
      system.runHeartbeatOnce({
        reason: "plugin-event",
        agentId: "main",
        sessionKey: "session",
        heartbeat: { target: "none", every: "1ms" },
        cfg: {},
        deps: {},
      } as Parameters<typeof system.runHeartbeatOnce>[0]),
    ).resolves.toBe(result);
    expect(heartbeatRunnerMocks.loads).toBe(1);
    expect(heartbeatRunnerMocks.runHeartbeatOnce).toHaveBeenCalledWith({
      reason: "plugin-event",
      agentId: "main",
      sessionKey: "session",
      heartbeat: { target: "none" },
    });
    const failure = new Error("heartbeat failed");
    heartbeatRunnerMocks.runHeartbeatOnce.mockRejectedValueOnce(failure);
    await expect(system.runHeartbeatOnce()).rejects.toBe(failure);
    expect(heartbeatRunnerMocks.runHeartbeatOnce).toHaveBeenLastCalledWith({
      reason: undefined,
      agentId: undefined,
      sessionKey: undefined,
      heartbeat: undefined,
    });
    heartbeatRunnerMocks.runHeartbeatOnce.mockReset();
  });

  it.each([
    {
      name: "exposes runtime.events.onAgentEvent",
      readValue: (runtime: ReturnType<typeof createPluginRuntime>) => runtime.events.onAgentEvent,
      expected: onAgentEvent,
    },
    {
      name: "exposes runtime.events.onSessionTranscriptUpdate",
      readValue: (runtime: ReturnType<typeof createPluginRuntime>) =>
        runtime.events.onSessionTranscriptUpdate,
      expected: onSessionTranscriptUpdate,
    },
    {
      name: "exposes runtime.system.requestHeartbeat",
      readValue: (runtime: ReturnType<typeof createPluginRuntime>) =>
        runtime.system.requestHeartbeat,
      expected: requestHeartbeat,
    },
    {
      name: "exposes deprecated runtime.system.requestHeartbeatNow",
      readValue: (runtime: ReturnType<typeof createPluginRuntime>) =>
        typeof runtime.system.requestHeartbeatNow,
      expected: "function",
    },
    {
      name: "exposes runtime.version from the shared VERSION constant",
      readValue: (runtime: ReturnType<typeof createPluginRuntime>) => runtime.version,
      expected: VERSION,
    },
  ] as const)("$name", ({ readValue, expected }) => {
    expectRuntimeValue(readValue, expected);
  });

  it("exposes reset freshness resolver on the host channel runtime", () => {
    const sessionRuntime = createPluginRuntime().channel.session as Record<string, unknown>;
    expect(typeof sessionRuntime.resolveEntryResetFreshness).toBe("function");
  });

  it("maps deprecated runtime.system.requestHeartbeatNow to an immediate compatibility wake", async () => {
    vi.useFakeTimers();
    const handler = vi.fn(async (_request: Parameters<typeof requestHeartbeat>[0]) => ({
      status: "skipped" as const,
      reason: "disabled",
    }));
    const dispose = setHeartbeatWakeHandler(handler);
    try {
      createPluginRuntime().system.requestHeartbeatNow({
        reason: "legacy-plugin",
        coalesceMs: 0,
      });
      await vi.advanceTimersByTimeAsync(1);
      const request = handler.mock.calls[0]?.[0] as
        | { source?: string; intent?: string; reason?: string }
        | undefined;
      expect(request?.source).toBe("other");
      expect(request?.intent).toBe("immediate");
      expect(request?.reason).toBe("legacy-plugin");
    } finally {
      dispose();
      vi.useRealTimers();
    }
  });

  it("resolves thinking policy with configured model compat from runtime config", () => {
    setRuntimeConfigSnapshot({
      models: {
        providers: {
          gmn: {
            baseUrl: "https://gmn.example.com/v1",
            models: [
              {
                id: "gpt-5.4",
                name: "GPT 5.4 via GMN",
                reasoning: true,
                compat: { supportedReasoningEfforts: ["low", "medium", "high", "xhigh"] },
              },
            ],
          },
        },
      },
    } as unknown as OpenClawConfig);

    const runtime = createPluginRuntime();
    const policy = runtime.agent.resolveThinkingPolicy({
      provider: "gmn",
      model: "gpt-5.4",
    });

    expect(policy.levels.map((level) => level.id)).toContain("xhigh");
  });

  it("includes persisted session exec overrides in sandbox authority", () => {
    const runtime = createPluginRuntime();
    const getSessionEntry = vi
      .spyOn(runtime.agent.session, "getSessionEntry")
      .mockReturnValue({ sessionId: "session", updatedAt: 1, execHost: "gateway" });
    const config: OpenClawConfig = {
      agents: {
        defaults: { sandbox: { mode: "all", scope: "session", workspaceAccess: "rw" } },
        list: [{ id: "main", default: true }],
      },
      tools: { elevated: { enabled: false } },
    };

    const result = runtime.sandbox.resolveWorkspaceAuthority({
      config,
      agentId: "main",
      sessionKey: "agent:main:subagent:workboard-card",
    });

    expect(getSessionEntry).toHaveBeenCalledWith({
      agentId: "main",
      sessionKey: "agent:main:subagent:workboard-card",
    });
    expect(result.confinementError).toContain("outside the sandbox");
  });

  it("prepares the live sandbox before returning workspace authority", async () => {
    const runtime = createPluginRuntime();
    vi.spyOn(runtime.agent.session, "getSessionEntry").mockReturnValue(undefined);
    sandboxContextMocks.resolveSandboxContext.mockResolvedValue({ backendId: "docker" });
    const config: OpenClawConfig = {
      agents: {
        defaults: { sandbox: { mode: "all", scope: "session", workspaceAccess: "rw" } },
        list: [{ id: "main", default: true, workspace: "/workspace" }],
      },
      tools: {
        elevated: { enabled: false },
        sandbox: { tools: { allow: ["read"] } },
      },
    };

    await expect(
      runtime.sandbox.prepareWorkspaceAuthority({
        config,
        agentId: "main",
        sessionKey: "agent:main:subagent:workboard-card",
        workspaceDir: "/workspace",
      }),
    ).resolves.toEqual({ sandboxed: true, workspaceAccess: "rw" });
    expect(sandboxContextMocks.resolveSandboxContext).toHaveBeenCalledWith({
      config,
      agentId: "main",
      sessionKey: "agent:main:subagent:workboard-card",
      workspaceDir: "/workspace",
      requireCurrentConfig: true,
    });
  });

  it.each([
    {
      name: "exposes runtime.mediaUnderstanding helpers",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expectFunctionKeys(runtime.mediaUnderstanding as Record<string, unknown>, [
          "resolveAudioInputBudget",
          "runFile",
          "describeImageFile",
          "describeImageFileWithModel",
          "extractStructuredWithModel",
          "describeVideoFile",
        ]);
        expect(runtime.mediaUnderstanding.transcribeAudioFile).toBeTypeOf("function");
      },
    },
    {
      name: "exposes runtime.imageGeneration helpers",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expectFunctionKeys(runtime.imageGeneration as Record<string, unknown>, [
          "generate",
          "listProviders",
        ]);
      },
    },
    {
      name: "exposes runtime.webSearch helpers",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expectFunctionKeys(runtime.webSearch as Record<string, unknown>, [
          "listProviders",
          "search",
        ]);
      },
    },
    {
      name: "exposes canonical runtime.tasks task runtimes",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expectFunctionKeys(runtime.tasks.runs as Record<string, unknown>, [
          "bindSession",
          "fromToolContext",
        ]);
        expectFunctionKeys(runtime.tasks.flows as Record<string, unknown>, [
          "bindSession",
          "fromToolContext",
        ]);
        expectFunctionKeys(runtime.tasks.managedFlows as Record<string, unknown>, [
          "bindSession",
          "fromToolContext",
        ]);
      },
    },
    {
      name: "exposes runtime.agent host helpers",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expect(runtime.agent.defaults).toEqual({
          model: DEFAULT_MODEL,
          provider: DEFAULT_PROVIDER,
        });
        expectFunctionKeys(runtime.agent as Record<string, unknown>, [
          "runCommandFromIngress",
          "runEmbeddedAgent",
          "normalizeThinkingLevel",
          "resolveThinkingPolicy",
          "resolveAgentDir",
        ]);
        expectFunctionKeys(runtime.agent.session as Record<string, unknown>, [
          "createSessionEntry",
          "getSessionEntry",
          "listSessionEntries",
          "patchSessionEntry",
          "upsertSessionEntry",
          "runWithWorkAdmission",
          "updateSessionStoreEntry",
        ]);
      },
    },
    {
      name: "exposes runtime.llm completion and provider-service acquisition",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expectFunctionKeys(runtime.llm as Record<string, unknown>, [
          "complete",
          "acquireLocalService",
        ]);
      },
    },
    {
      name: "exposes runtime.sandbox workspace-authority resolution",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expectFunctionKeys(runtime.sandbox as Record<string, unknown>, [
          "resolveWorkspaceAuthority",
          "prepareWorkspaceAuthority",
        ]);
      },
    },
    {
      name: "exposes runtime.worktrees checkout inspection and lifecycle helpers",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expectFunctionKeys(runtime.worktrees as Record<string, unknown>, [
          "resolveCheckoutRoot",
          "hasSelfContainedCheckoutMetadata",
          "create",
          "release",
          "removeIfLossless",
        ]);
      },
    },
    {
      name: "exposes canonical read-only model selection without injection",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        const modelConfig = runtime.modelConfig;
        expect(modelConfig.resolveDefaultModelForAgent).toBe(resolveDefaultModelForAgent);
        expect(modelConfig.resolveAllowedModelRef).toBe(resolveAllowedModelRefCore);
        expect(modelConfig.resolveDefaultModelForAgent({ cfg: {} })).toEqual({
          provider: DEFAULT_PROVIDER,
          model: DEFAULT_MODEL,
        });
        expect(Object.getOwnPropertyDescriptor(runtime, "modelConfig")).toEqual({
          configurable: true,
          enumerable: true,
          get: expect.any(Function),
          set: undefined,
        });
        expect(Reflect.set(runtime, "modelConfig", {})).toBe(false);
        expect(runtime.modelConfig).toBe(modelConfig);
      },
    },
    {
      name: "exposes runtime.modelAuth with raw and runtime-ready auth helpers",
      assert: (runtime: ReturnType<typeof createPluginRuntime>) => {
        expect(runtime.modelAuth.resolveProviderIdForAuth).toBe(resolveProviderIdForAuth);
        expect(runtime.modelAuth.ensureAuthProfileStore).toBe(ensureAuthProfileStore);
        expect(runtime.modelAuth.resolveAuthProfileOrder).toBe(resolveAuthProfileOrder);
        expect(runtime.modelAuth.listProfilesForProvider).toBe(listProfilesForProvider);
        expect(runtime.modelAuth.isProviderApiKeyConfigured).toBe(isProviderApiKeyConfigured);
        expectFunctionKeys(runtime.modelAuth, [
          "getApiKeyForModel",
          "getRuntimeAuthForModel",
          "resolveApiKeyForProvider",
        ]);
      },
    },
  ] as const)("$name", ({ assert }) => {
    expectRuntimeShape(assert);
  });

  it("modelAuth wrappers strip agentDir and store to prevent credential steering", async () => {
    // The wrappers should not forward agentDir or store from plugin callers.
    // We verify this by checking the wrapper functions exist and are not the
    // raw implementations (they are wrapped, not direct references).
    const { getApiKeyForModelCore: rawGetApiKey } = await import("../../agents/model-auth.js");
    const runtime = createPluginRuntime();
    // Wrappers should NOT be the same reference as the raw functions
    expect(runtime.modelAuth.getApiKeyForModel).not.toBe(rawGetApiKey);
  });

  it("modelAuth wrappers preserve workspace scope while stripping credential steering", async () => {
    const runtime = createPluginRuntime();
    const model = {
      id: "workspace-cloud/model",
      provider: "workspace-cloud",
      api: "openai-responses",
      baseUrl: "https://workspace-cloud.example/v1",
    };
    const cfg = { plugins: { allow: ["workspace-cloud"] } } as OpenClawConfig;
    runtimeModelAuthMocks.getApiKeyForModel.mockResolvedValue({
      apiKey: "model-key",
      source: "workspace cloud credentials",
      mode: "api-key",
    });
    runtimeModelAuthMocks.getRuntimeAuthForModelCore.mockResolvedValue({
      apiKey: "runtime-key",
      source: "workspace cloud runtime credentials",
      mode: "api-key",
    });
    runtimeModelAuthMocks.resolveProviderRuntimeApiKey.mockResolvedValue({
      apiKey: "provider-key",
      source: "workspace cloud credentials",
      mode: "api-key",
    });

    const modelAuth = await runtime.modelAuth.getApiKeyForModel({
      model: model as never,
      cfg,
      workspaceDir: "/tmp/workspace",
      agentDir: "/tmp/agent",
      store: { version: 1, profiles: {} },
    } as never);
    expect(modelAuth.apiKey).toBe("model-key");
    const runtimeAuth = await runtime.modelAuth.getRuntimeAuthForModel({
      model: model as never,
      cfg,
      workspaceDir: "/tmp/workspace",
      agentDir: "/tmp/agent",
      store: { version: 1, profiles: {} },
    } as never);
    expect(runtimeAuth.apiKey).toBe("runtime-key");

    const providerAuth = await runtime.modelAuth.resolveApiKeyForProvider({
      provider: "workspace-cloud",
      cfg,
      workspaceDir: "/tmp/workspace",
      agentDir: "/tmp/agent",
      store: { version: 1, profiles: {} },
    } as never);
    expect(providerAuth.apiKey).toBe("provider-key");

    expect(runtimeModelAuthMocks.getApiKeyForModel).toHaveBeenCalledWith({
      model,
      cfg,
      workspaceDir: "/tmp/workspace",
    });
    expect(runtimeModelAuthMocks.getRuntimeAuthForModelCore).toHaveBeenCalledWith({
      model,
      cfg,
      workspaceDir: "/tmp/workspace",
    });
    expect(runtimeModelAuthMocks.resolveProviderRuntimeApiKey).toHaveBeenCalledWith({
      provider: "workspace-cloud",
      cfg,
      workspaceDir: "/tmp/workspace",
    });
  });

  it("keeps subagent unavailable by default", () => {
    const runtime = createPluginRuntime();
    expectGatewaySubagentRunFailure(runtime, { sessionKey: "s-1", message: "hello" });
  });

  it("exposes a node duplex capability even when Gateway access is unavailable", () => {
    const nodes = createPluginRuntime().nodes;
    expect(nodes).toHaveProperty("openDuplex", expect.any(Function));
    expect(() => nodes.openDuplex({ nodeId: "node-1", command: "image.bridge" })).toThrow(
      "only available inside the Gateway",
    );
  });

  it("uses an explicit subagent runtime", async () => {
    const run = vi.fn().mockResolvedValue({ runId: "run-1" });
    const runtime = createPluginRuntime({
      subagent: { ...createGatewaySubagentRuntime(), run },
    });

    await expect(
      expectRuntimeSubagentRun(runtime, { sessionKey: "s-2", message: "hello" }),
    ).resolves.toEqual({
      runId: "run-1",
    });
    expect(run).toHaveBeenCalledWith({ sessionKey: "s-2", message: "hello" });
  });

  it("uses explicit nodes runtime when provided", async () => {
    const nodes = {
      list: vi.fn().mockResolvedValue({ nodes: [] }),
      invoke: vi.fn().mockResolvedValue({ ok: true }),
      openDuplex: vi.fn().mockResolvedValue({ closed: Promise.resolve({ ok: true }) }),
    };
    const runtime = createPluginRuntime({ nodes });

    await expect(runtime.nodes.list({ connected: true })).resolves.toEqual({ nodes: [] });
    await expect(
      runtime.nodes.invoke({ nodeId: "node-1", command: "browser.proxy" }),
    ).resolves.toEqual({ ok: true });
    expect(nodes.list).toHaveBeenCalledWith({ connected: true });
    expect(nodes.invoke).toHaveBeenCalledWith({ nodeId: "node-1", command: "browser.proxy" });
    await expect(
      runtime.nodes.openDuplex({ nodeId: "node-1", command: "image.bridge" }),
    ).resolves.toMatchObject({ closed: expect.any(Promise) });
    expect(nodes.openDuplex).toHaveBeenCalledWith({ nodeId: "node-1", command: "image.bridge" });
  });
});