Skip to content

Commit e82311f

Browse files
committed
fix(plugins): Bedrock ARN region routing, stop-reason detail, and Copilot device-flow pacing
1 parent 251b8b8 commit e82311f

8 files changed

Lines changed: 304 additions & 36 deletions

File tree

‎extensions/amazon-bedrock/stream.runtime.test.ts‎

Lines changed: 93 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
// Amazon Bedrock tests cover stream plugin behavior.
2-
import { BedrockRuntimeClient, ConversationRole } from "@aws-sdk/client-bedrock-runtime";
2+
import {
3+
BedrockRuntimeClient,
4+
ConversationRole,
5+
StopReason as BedrockStopReason,
6+
} from "@aws-sdk/client-bedrock-runtime";
37
import { onLlmRequestActivity } from "openclaw/plugin-sdk/provider-stream-shared";
48
import { afterEach, describe, expect, it, vi } from "vitest";
59
import { streamBedrock, streamSimpleBedrock } from "./stream.runtime.js";
@@ -48,7 +52,30 @@ async function* streamEvents(events: unknown[]) {
4852
}
4953
}
5054

55+
async function captureClientRegion(
56+
model: Parameters<typeof streamBedrock>[0],
57+
options: Parameters<typeof streamBedrock>[2] = {},
58+
): Promise<string> {
59+
const send = vi.spyOn(BedrockRuntimeClient.prototype, "send").mockResolvedValue({
60+
$metadata: { httpStatusCode: 200 },
61+
stream: streamEvents([
62+
{ messageStart: { role: ConversationRole.ASSISTANT } },
63+
{ messageStop: { stopReason: BedrockStopReason.END_TURN } },
64+
]),
65+
} as never);
66+
67+
await streamBedrock(
68+
model,
69+
{ messages: [{ role: "user", content: "Hello", timestamp: 0 }] } as never,
70+
options,
71+
).result();
72+
73+
const client = send.mock.contexts[0] as BedrockRuntimeClient;
74+
return client.config.region();
75+
}
76+
5177
afterEach(() => {
78+
vi.unstubAllEnvs();
5279
vi.restoreAllMocks();
5380
});
5481

@@ -203,6 +230,71 @@ describe("Bedrock profile endpoint resolution", () => {
203230
),
204231
).toBe(false);
205232
});
233+
234+
it.each([
235+
{
236+
name: "plain model id",
237+
modelId: "amazon.nova-micro-v1:0",
238+
ambientRegion: "eu-west-1",
239+
expectedRegion: "eu-west-1",
240+
},
241+
{
242+
name: "application inference-profile ARN",
243+
modelId: "arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/profile-abc",
244+
ambientRegion: "us-east-1",
245+
expectedRegion: "us-west-2",
246+
},
247+
{
248+
name: "GovCloud inference-profile ARN",
249+
modelId:
250+
"arn:aws-us-gov:bedrock:us-gov-west-1:123456789012:application-inference-profile/profile-abc",
251+
ambientRegion: "us-east-1",
252+
expectedRegion: "us-gov-west-1",
253+
},
254+
{
255+
name: "ARN with explicit region option",
256+
modelId: "arn:aws:bedrock:us-west-2:123456789012:application-inference-profile/profile-abc",
257+
ambientRegion: "us-east-1",
258+
explicitRegion: "ap-southeast-2",
259+
expectedRegion: "ap-southeast-2",
260+
},
261+
])(
262+
"resolves $name to $expectedRegion",
263+
async ({ modelId, ambientRegion, explicitRegion, expectedRegion }) => {
264+
vi.stubEnv("AWS_REGION", ambientRegion);
265+
266+
await expect(
267+
captureClientRegion(
268+
bedrockModel({ id: modelId }),
269+
explicitRegion ? { region: explicitRegion } : {},
270+
),
271+
).resolves.toBe(expectedRegion);
272+
},
273+
);
274+
});
275+
276+
describe("Bedrock stop reasons", () => {
277+
it.each([
278+
BedrockStopReason.CONTENT_FILTERED,
279+
BedrockStopReason.GUARDRAIL_INTERVENED,
280+
BedrockStopReason.MALFORMED_MODEL_OUTPUT,
281+
BedrockStopReason.MALFORMED_TOOL_USE,
282+
])("reports the provider stop reason %s", async (stopReason) => {
283+
vi.spyOn(BedrockRuntimeClient.prototype, "send").mockResolvedValue({
284+
$metadata: { httpStatusCode: 200 },
285+
stream: streamEvents([
286+
{ messageStart: { role: ConversationRole.ASSISTANT } },
287+
{ messageStop: { stopReason } },
288+
]),
289+
} as never);
290+
291+
const result = await streamBedrock(bedrockModel({}), {
292+
messages: [{ role: "user", content: "Hello", timestamp: 0 }],
293+
} as never).result();
294+
295+
expect(result.stopReason).toBe("error");
296+
expect(result.errorMessage).toBe(stopReason);
297+
});
206298
});
207299

208300
describe("Bedrock thinking effort mapping", () => {

‎extensions/amazon-bedrock/stream.runtime.ts‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -166,11 +166,12 @@ export const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOpt
166166
profile: options.profile,
167167
};
168168
const configuredRegion = getConfiguredBedrockRegion(options);
169+
const requestRegion = options.region || getBedrockModelArnRegion(model.id) || configuredRegion;
169170
const hasConfiguredProfile = hasConfiguredBedrockProfile(options);
170171
const endpointRegion = getStandardBedrockEndpointRegion(model.baseUrl);
171172
const useExplicitEndpoint = shouldUseExplicitBedrockEndpoint(
172173
model.baseUrl,
173-
configuredRegion,
174+
requestRegion,
174175
hasConfiguredProfile,
175176
);
176177

@@ -187,11 +188,10 @@ export const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOpt
187188

188189
// in Node.js/Bun environment only
189190
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
190-
// Region resolution: explicit option > env vars > SDK default chain.
191-
// When AWS_PROFILE is set, we leave region undefined so the SDK can
192-
// resovle it from aws profile configs. Otherwise fall back to us-east-1.
193-
if (configuredRegion) {
194-
config.region = configuredRegion;
191+
// Region resolution: explicit option > model ARN > env vars > SDK default chain.
192+
// When AWS_PROFILE is set, leave region undefined so the SDK can resolve it.
193+
if (requestRegion) {
194+
config.region = requestRegion;
195195
} else if (endpointRegion && useExplicitEndpoint) {
196196
config.region = endpointRegion;
197197
} else if (!hasConfiguredProfile) {
@@ -220,7 +220,7 @@ export const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOpt
220220
// Non-Node environment (browser): fall back to us-east-1 since
221221
// there's no config file resolution available.
222222
config.region =
223-
configuredRegion ||
223+
requestRegion ||
224224
(endpointRegion && useExplicitEndpoint ? endpointRegion : undefined) ||
225225
"us-east-1";
226226
}
@@ -303,7 +303,11 @@ export const streamBedrock: StreamFunction<"bedrock-converse-stream", BedrockOpt
303303
model.provider,
304304
);
305305
} else {
306-
output.stopReason = mapStopReason(item.messageStop.stopReason);
306+
const mappedStop = mapStopReason(item.messageStop.stopReason);
307+
output.stopReason = mappedStop.stopReason;
308+
if (mappedStop.errorMessage) {
309+
output.errorMessage = mappedStop.errorMessage;
310+
}
307311
}
308312
} else if (item.metadata) {
309313
handleMetadata(item.metadata, model, output);
@@ -1002,21 +1006,33 @@ function convertToolConfig(
10021006
return { tools: bedrockTools, toolChoice: bedrockToolChoice };
10031007
}
10041008

1005-
function mapStopReason(reason: string | undefined): StopReason {
1009+
function mapStopReason(reason: string | undefined): {
1010+
stopReason: StopReason;
1011+
errorMessage?: string;
1012+
} {
10061013
switch (reason) {
10071014
case BedrockStopReason.END_TURN:
10081015
case BedrockStopReason.STOP_SEQUENCE:
1009-
return "stop";
1016+
return { stopReason: "stop" };
10101017
case BedrockStopReason.MAX_TOKENS:
10111018
case BedrockStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED:
1012-
return "length";
1019+
return { stopReason: "length" };
10131020
case BedrockStopReason.TOOL_USE:
1014-
return "toolUse";
1021+
return { stopReason: "toolUse" };
1022+
case BedrockStopReason.CONTENT_FILTERED:
1023+
case BedrockStopReason.GUARDRAIL_INTERVENED:
1024+
case BedrockStopReason.MALFORMED_MODEL_OUTPUT:
1025+
case BedrockStopReason.MALFORMED_TOOL_USE:
1026+
return { stopReason: "error", errorMessage: reason };
10151027
default:
1016-
return "error";
1028+
return reason ? { stopReason: "error", errorMessage: reason } : { stopReason: "error" };
10171029
}
10181030
}
10191031

1032+
function getBedrockModelArnRegion(modelId: string): string | undefined {
1033+
return /^arn:aws(?:-[a-z0-9-]+)?:bedrock:([a-z0-9-]+):/.exec(modelId)?.[1];
1034+
}
1035+
10201036
function getConfiguredBedrockRegion(options: BedrockOptions): string | undefined {
10211037
if (typeof process === "undefined") {
10221038
return options.region;

‎extensions/github-copilot/login.test.ts‎

Lines changed: 112 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,20 @@ function guardResponse(body: unknown, status = 200, url = DEVICE_CODE_URL) {
4040
afterEach(() => {
4141
mocks.fetchWithSsrFGuard.mockReset();
4242
vi.restoreAllMocks();
43+
vi.useRealTimers();
4344
});
4445

46+
function runDeviceFlowAfterFirstPoll(
47+
io: Parameters<typeof runGitHubCopilotDeviceFlow>[0],
48+
domain?: string,
49+
) {
50+
vi.useFakeTimers();
51+
const result = runGitHubCopilotDeviceFlow(io, domain);
52+
return Promise.all([result, vi.advanceTimersByTimeAsync(5_000)]).then(
53+
([flowResult]) => flowResult,
54+
);
55+
}
56+
4557
describe("runGitHubCopilotDeviceFlow — normal flow", () => {
4658
it("bounds requests and returns authorized status and access token on successful flow", async () => {
4759
let callIdx = 0;
@@ -64,7 +76,7 @@ describe("runGitHubCopilotDeviceFlow — normal flow", () => {
6476
});
6577

6678
const showCode = vi.fn(async () => {});
67-
const result = await runGitHubCopilotDeviceFlow({ showCode, signal: controller.signal });
79+
const result = await runDeviceFlowAfterFirstPoll({ showCode, signal: controller.signal });
6880

6981
expect(result).toEqual({ status: "authorized", accessToken: "ghu_tok_xyz" });
7082
expect(showCode).toHaveBeenCalledWith({
@@ -86,7 +98,7 @@ describe("runGitHubCopilotDeviceFlow — normal flow", () => {
8698
return guardResponse({ error: "access_denied" }, 200, ACCESS_TOKEN_URL);
8799
});
88100

89-
const result = await runGitHubCopilotDeviceFlow({
101+
const result = await runDeviceFlowAfterFirstPoll({
90102
showCode: vi.fn(async () => {}),
91103
});
92104
expect(result).toEqual({ status: "access_denied" });
@@ -102,7 +114,7 @@ describe("runGitHubCopilotDeviceFlow — normal flow", () => {
102114
return guardResponse({ error: "expired_token" }, 200, ACCESS_TOKEN_URL);
103115
});
104116

105-
const result = await runGitHubCopilotDeviceFlow({
117+
const result = await runDeviceFlowAfterFirstPoll({
106118
showCode: vi.fn(async () => {}),
107119
});
108120
expect(result).toEqual({ status: "expired" });
@@ -128,10 +140,25 @@ describe("runGitHubCopilotDeviceFlow — HTTP error propagation", () => {
128140
return guardResponse({}, 500, ACCESS_TOKEN_URL);
129141
});
130142

131-
await expect(runGitHubCopilotDeviceFlow({ showCode: vi.fn(async () => {}) })).rejects.toThrow(
143+
await expect(runDeviceFlowAfterFirstPoll({ showCode: vi.fn(async () => {}) })).rejects.toThrow(
132144
"GitHub device token failed: HTTP 500",
133145
);
134146
});
147+
148+
it("rejects a malformed access token response", async () => {
149+
let callIdx = 0;
150+
mocks.fetchWithSsrFGuard.mockImplementation(async () => {
151+
callIdx += 1;
152+
if (callIdx === 1) {
153+
return guardResponse(VALID_DEVICE_CODE_BODY);
154+
}
155+
return guardResponse({ access_token: null, token_type: "bearer" }, 200, ACCESS_TOKEN_URL);
156+
});
157+
158+
await expect(runDeviceFlowAfterFirstPoll({ showCode: vi.fn(async () => {}) })).rejects.toThrow(
159+
"GitHub device flow returned an invalid access token",
160+
);
161+
});
135162
});
136163

137164
describe("postGitHubDeviceFlowForm — response size bound", () => {
@@ -208,7 +235,7 @@ describe("postGitHubDeviceFlowForm — response size bound", () => {
208235
};
209236
});
210237

211-
await expect(runGitHubCopilotDeviceFlow({ showCode: vi.fn(async () => {}) })).rejects.toThrow(
238+
await expect(runDeviceFlowAfterFirstPoll({ showCode: vi.fn(async () => {}) })).rejects.toThrow(
212239
"github-copilot.device-flow",
213240
);
214241

@@ -246,7 +273,7 @@ describe("runGitHubCopilotDeviceFlow — data-residency GitHub Enterprise", () =
246273
});
247274

248275
const showCode = vi.fn(async () => {});
249-
const result = await runGitHubCopilotDeviceFlow({ showCode }, GHE_DOMAIN);
276+
const result = await runDeviceFlowAfterFirstPoll({ showCode }, GHE_DOMAIN);
250277

251278
expect(result).toEqual({ status: "authorized", accessToken: "ghu_ghe_tok" });
252279
expect(urls).toEqual([gheDeviceCodeUrl, gheAccessTokenUrl]);
@@ -271,3 +298,82 @@ describe("runGitHubCopilotDeviceFlow — data-residency GitHub Enterprise", () =
271298
).rejects.toThrow("unexpected verification URL");
272299
});
273300
});
301+
302+
describe("runGitHubCopilotDeviceFlow — polling intervals", () => {
303+
it("waits before the first poll and keeps cumulative slow_down increases", async () => {
304+
vi.useFakeTimers();
305+
vi.setSystemTime(new Date("2026-07-16T00:00:00Z"));
306+
const startedAt = Date.now();
307+
const pollTimes: number[] = [];
308+
const pollResponses = [
309+
{ error: "authorization_pending" },
310+
{ error: "slow_down" },
311+
{ error: "slow_down" },
312+
{ access_token: "test-access-token", token_type: "bearer" },
313+
];
314+
mocks.fetchWithSsrFGuard.mockImplementation(async (params) => {
315+
if (params.url === DEVICE_CODE_URL) {
316+
const { interval: _interval, ...withoutInterval } = VALID_DEVICE_CODE_BODY;
317+
return guardResponse(withoutInterval);
318+
}
319+
pollTimes.push(Date.now());
320+
return guardResponse(pollResponses.shift(), 200, ACCESS_TOKEN_URL);
321+
});
322+
323+
const result = runGitHubCopilotDeviceFlow({ showCode: vi.fn(async () => {}) });
324+
325+
await vi.advanceTimersByTimeAsync(4_999);
326+
expect(pollTimes).toEqual([]);
327+
await vi.advanceTimersByTimeAsync(1);
328+
expect(pollTimes).toEqual([startedAt + 5_000]);
329+
330+
await vi.advanceTimersByTimeAsync(5_000);
331+
expect(pollTimes).toEqual([startedAt + 5_000, startedAt + 10_000]);
332+
await vi.advanceTimersByTimeAsync(10_000);
333+
expect(pollTimes).toEqual([startedAt + 5_000, startedAt + 10_000, startedAt + 20_000]);
334+
await vi.advanceTimersByTimeAsync(15_000);
335+
336+
await expect(result).resolves.toEqual({
337+
status: "authorized",
338+
accessToken: "test-access-token",
339+
});
340+
expect(pollTimes).toEqual([
341+
startedAt + 5_000,
342+
startedAt + 10_000,
343+
startedAt + 20_000,
344+
startedAt + 35_000,
345+
]);
346+
});
347+
348+
it("uses the interval returned with slow_down", async () => {
349+
vi.useFakeTimers();
350+
vi.setSystemTime(new Date("2026-07-16T00:00:00Z"));
351+
const startedAt = Date.now();
352+
const pollTimes: number[] = [];
353+
const pollResponses = [
354+
{ error: "slow_down", interval: 7 },
355+
{ access_token: "test-access-token", token_type: "bearer" },
356+
];
357+
mocks.fetchWithSsrFGuard.mockImplementation(async (params) => {
358+
if (params.url === DEVICE_CODE_URL) {
359+
return guardResponse({ ...VALID_DEVICE_CODE_BODY, interval: 2 });
360+
}
361+
pollTimes.push(Date.now());
362+
return guardResponse(pollResponses.shift(), 200, ACCESS_TOKEN_URL);
363+
});
364+
365+
const result = runGitHubCopilotDeviceFlow({ showCode: vi.fn(async () => {}) });
366+
367+
await vi.advanceTimersByTimeAsync(2_000);
368+
expect(pollTimes).toEqual([startedAt + 2_000]);
369+
await vi.advanceTimersByTimeAsync(6_999);
370+
expect(pollTimes).toHaveLength(1);
371+
await vi.advanceTimersByTimeAsync(1);
372+
373+
await expect(result).resolves.toEqual({
374+
status: "authorized",
375+
accessToken: "test-access-token",
376+
});
377+
expect(pollTimes).toEqual([startedAt + 2_000, startedAt + 9_000]);
378+
});
379+
});

0 commit comments

Comments
 (0)