File size: 9,251 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
import { configureAiTransportHost, getAiTransportHost } from "@openclaw/ai";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import { AsyncWorkScope } from "../../shared/async-work-scope.js";
import { withPluginRuntimePluginScope } from "./gateway-request-scope.js";
import { createRuntimeLlm } from "./runtime-llm.runtime.js";

const mocks = vi.hoisted(() => ({
  acquireSimpleCompletionModelForAgent:
    vi.fn<
      typeof import("../../agents/simple-completion-runtime.js").acquireSimpleCompletionModelForAgent
    >(),
  resolveSimpleCompletionSelectionForAgent: vi.fn(),
}));

vi.mock("../../agents/simple-completion-runtime.js", async (importOriginal) => ({
  ...(await importOriginal<typeof import("../../agents/simple-completion-runtime.js")>()),
  acquireSimpleCompletionModelForAgent: mocks.acquireSimpleCompletionModelForAgent,
  resolveSimpleCompletionSelectionForAgent: mocks.resolveSimpleCompletionSelectionForAgent,
}));

const modelId = "gpt-5.6-luna";
const responseModel = "gpt-5.6-luna-2026-08-01";
const authToken = (() => {
  const header = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url");
  const body = Buffer.from(
    JSON.stringify({
      "https://api.openai.com/auth": { chatgpt_account_id: "acct-runtime-model-test" },
    }),
  ).toString("base64url");
  return `${header}.${body}.signature`;
})();

const cfg = {
  agents: { defaults: { model: `openai/${modelId}` } },
} satisfies OpenClawConfig;

const pluginCfg = {
  ...cfg,
  plugins: {
    entries: {
      "trusted-plugin": {
        llm: {
          allowModelOverride: true,
          allowedModels: [`openai/${modelId}`],
        },
      },
    },
  },
} satisfies OpenClawConfig;

function preparedOauthModel(
  profileId = "openai:test-oauth",
): Extract<
  Awaited<ReturnType<typeof mocks.acquireSimpleCompletionModelForAgent>>,
  { model: unknown }
> {
  return {
    [Symbol.asyncDispose]: vi.fn(async () => {}),
    selection: {
      provider: "openai",
      modelId,
      profileId,
      agentDir: "/tmp/openclaw-agent",
    },
    model: {
      provider: "openai",
      id: modelId,
      name: modelId,
      api: "openai-chatgpt-responses",
      baseUrl: "https://chatgpt.com/backend-api/codex",
      input: ["text"],
      reasoning: true,
      contextWindow: 128_000,
      maxTokens: 4_096,
      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
    },
    auth: {
      apiKey: authToken,
      source: "test",
      mode: "oauth",
      profileId,
    },
  };
}

function completedResponse(): Response {
  const response = {
    id: "resp_runtime_model",
    object: "response",
    status: "completed",
    output: [
      {
        id: "msg_runtime_model",
        type: "message",
        role: "assistant",
        status: "completed",
        content: [
          {
            type: "output_text",
            text: '{"classification":"safe","reason":"fixture"}',
            annotations: [],
          },
        ],
      },
    ],
    usage: { input_tokens: 5, output_tokens: 3, total_tokens: 8 },
  };
  const events = [
    { type: "response.created", response: { ...response, output: [], status: "in_progress" } },
    { type: "response.completed", response },
  ];
  return new Response(
    `${events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("")}data: [DONE]\n\n`,
    {
      status: 200,
      headers: {
        "content-type": "text/event-stream",
        "openai-model": responseModel,
      },
    },
  );
}

let previousHost: ReturnType<typeof getAiTransportHost>;
let completionWork: AsyncWorkScope;
const modelFetch = vi.fn<typeof fetch>();

beforeEach(async () => {
  completionWork = new AsyncWorkScope();
  // Initialize the lazily loaded agent host before installing the fixture override;
  // otherwise the first completion replaces this host and selects native WebSocket.
  await import("../../agents/ai-transport-runtime-host.js");
  previousHost = getAiTransportHost();
  modelFetch.mockReset();
  modelFetch.mockImplementation(async () => completedResponse());
  configureAiTransportHost({
    ...previousHost,
    buildModelFetch: () => modelFetch,
    plugin: {
      ...previousHost.plugin,
      resolveProviderStream: () => undefined,
      resolveTransportTurnState: () => undefined,
      wrapSimpleCompletionStream: () => undefined,
    },
  });
  mocks.resolveSimpleCompletionSelectionForAgent.mockReset();
  mocks.resolveSimpleCompletionSelectionForAgent.mockReturnValue({
    provider: "openai",
    modelId,
    agentDir: "/tmp/openclaw-agent",
  });
  mocks.acquireSimpleCompletionModelForAgent.mockReset();
  mocks.acquireSimpleCompletionModelForAgent.mockResolvedValue(preparedOauthModel());
});

afterEach(async () => {
  // Caller results settle before transport drainage and the acquired model release.
  await completionWork.drain();
  configureAiTransportHost(previousHost);
  vi.restoreAllMocks();
});

describe("runtime.llm.complete managed ChatGPT OAuth model identity", () => {
  it("returns the concrete response model from the managed transport", async () => {
    const llm = createRuntimeLlm({
      getConfig: () => cfg,
      authority: { caller: { kind: "host", id: "reef" }, allowComplete: true },
    });

    const result = await completionWork.track(() =>
      llm.complete({
        messages: [{ role: "user", content: "Classify this fixture." }],
        requiredAuthMode: "oauth",
        signal: AbortSignal.timeout(30_000),
        responseFormat: {
          type: "json_schema",
          json_schema: {
            name: "reef_guard_verdict",
            strict: true,
            schema: { type: "object", additionalProperties: false },
          },
        },
      }),
    );

    expect(result).toMatchObject({
      text: '{"classification":"safe","reason":"fixture"}',
      provider: "openai",
      model: modelId,
      responseModel,
      stopReason: "stop",
    });
    expect(modelFetch).toHaveBeenCalledTimes(1);
  });

  it("requires the selected credential to use the requested OAuth mode", async () => {
    const prepared = preparedOauthModel();
    mocks.acquireSimpleCompletionModelForAgent.mockResolvedValueOnce({
      ...prepared,
      auth: { apiKey: "test-api-key", source: "test", mode: "api-key" },
    });
    const llm = createRuntimeLlm({
      getConfig: () => cfg,
      authority: { caller: { kind: "host", id: "runtime-test" }, allowComplete: true },
    });

    await expect(
      completionWork.track(() =>
        llm.complete({
          messages: [{ role: "user", content: "Ping" }],
          requiredAuthMode: "oauth",
        }),
      ),
    ).rejects.toThrow("selected a credential with the wrong authentication mode");
    await completionWork.drain();
    expect(modelFetch).not.toHaveBeenCalled();
    expect(prepared[Symbol.asyncDispose]).toHaveBeenCalledTimes(1);
  });

  it("binds a direct model override to its selected OAuth profile", async () => {
    const profileId = "openai:work";
    mocks.resolveSimpleCompletionSelectionForAgent.mockReturnValueOnce({
      provider: "openai",
      modelId,
      profileId,
      agentDir: "/tmp/openclaw-agent",
    });
    mocks.acquireSimpleCompletionModelForAgent.mockResolvedValueOnce(preparedOauthModel(profileId));
    const llm = createRuntimeLlm({
      getConfig: () => pluginCfg,
      authority: { allowComplete: true },
    });

    await expect(
      completionWork.track(() =>
        withPluginRuntimePluginScope({ pluginId: "trusted-plugin" }, () =>
          llm.complete({
            model: `openai/${modelId}@${profileId}`,
            messages: [{ role: "user", content: "Ping" }],
            requiredAuthMode: "oauth",
          }),
        ),
      ),
    ).resolves.toMatchObject({ text: '{"classification":"safe","reason":"fixture"}' });
    expect(mocks.acquireSimpleCompletionModelForAgent).toHaveBeenCalledWith(
      expect.objectContaining({
        modelRef: `openai/${modelId}@${profileId}`,
        bindAuthOwner: true,
      }),
    );
  });

  it("rejects a direct model override resolved to another OAuth profile", async () => {
    const profileId = "openai:work";
    mocks.resolveSimpleCompletionSelectionForAgent.mockReturnValueOnce({
      provider: "openai",
      modelId,
      profileId,
      agentDir: "/tmp/openclaw-agent",
    });
    const prepared = preparedOauthModel("openai:other");
    mocks.acquireSimpleCompletionModelForAgent.mockResolvedValueOnce(prepared);
    const llm = createRuntimeLlm({
      getConfig: () => pluginCfg,
      authority: { allowComplete: true },
    });

    await expect(
      completionWork.track(() =>
        withPluginRuntimePluginScope({ pluginId: "trusted-plugin" }, () =>
          llm.complete({
            model: `openai/${modelId}@${profileId}`,
            messages: [{ role: "user", content: "Ping" }],
            requiredAuthMode: "oauth",
          }),
        ),
      ),
    ).rejects.toThrow("selected a different authentication profile");
    await completionWork.drain();
    expect(modelFetch).not.toHaveBeenCalled();
    expect(prepared[Symbol.asyncDispose]).toHaveBeenCalledTimes(1);
  });
});