Files
adolf/extensions/github-copilot/connection-bound-ids.live.test.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

235 lines
7.0 KiB
TypeScript

// Github Copilot tests cover connection bound ids plugin behavior.
import { stream as streamModel, type AssistantMessage, type Model } from "openclaw/plugin-sdk/llm";
import { describe, expect, it } from "vitest";
import { resolveFirstGithubToken } from "./auth.js";
import { buildCopilotDynamicHeaders } from "./stream.js";
import { wrapCopilotOpenAIResponsesStream } from "./stream.js";
import { resolveCopilotApiToken } from "./token.js";
const LIVE =
process.env.OPENCLAW_LIVE_TEST === "1" ||
process.env.LIVE === "1" ||
process.env.GITHUB_COPILOT_LIVE_TEST === "1";
const ENV_GITHUB_TOKEN =
process.env.OPENCLAW_LIVE_GITHUB_COPILOT_TOKEN ??
process.env.COPILOT_GITHUB_TOKEN ??
process.env.GH_TOKEN ??
process.env.GITHUB_TOKEN ??
"";
const LIVE_MODEL_ID = process.env.OPENCLAW_LIVE_GITHUB_COPILOT_MODEL?.trim() || "gpt-5.4";
const describeLive = LIVE ? describe : describe.skip;
type CopilotApiToken = {
token: string;
expiresAt: number;
source: string;
baseUrl: string;
};
const ZERO_USAGE = {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
} as const;
function logProgress(message: string): void {
process.stderr.write(`[github-copilot-live] ${message}\n`);
}
async function withTimeout<T>(label: string, promise: Promise<T>, timeoutMs: number): Promise<T> {
let timer: NodeJS.Timeout | undefined;
try {
return await Promise.race([
promise,
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),
timeoutMs,
);
timer.unref?.();
}),
]);
} finally {
if (timer) {
clearTimeout(timer);
}
}
}
const fetchWithTimeout: typeof fetch = async (input, init) => {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10_000);
timer.unref?.();
try {
return await fetch(input, {
...init,
signal: controller.signal,
});
} finally {
clearTimeout(timer);
}
};
function buildModel(baseUrl: string): Model<"openai-responses"> {
return {
id: LIVE_MODEL_ID,
name: LIVE_MODEL_ID,
provider: "github-copilot",
api: "openai-responses",
baseUrl,
headers: {},
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 128_000,
maxTokens: 256,
};
}
function buildReplayAssistantMessage(connectionBoundId: string): AssistantMessage {
return {
role: "assistant",
api: "openai-responses",
provider: "github-copilot",
model: LIVE_MODEL_ID,
usage: ZERO_USAGE,
stopReason: "stop",
timestamp: Date.now() - 1,
content: [
{
type: "text",
text: "Earlier assistant text.",
textSignature: JSON.stringify({ v: 1, id: connectionBoundId }),
},
],
};
}
async function resolveGithubTokenCandidates(): Promise<Array<{ source: string; token: string }>> {
const candidates: Array<{ source: string; token: string }> = [];
const envToken = ENV_GITHUB_TOKEN.trim();
if (envToken) {
candidates.push({ source: "env", token: envToken });
}
const profileEnv = {
...process.env,
COPILOT_GITHUB_TOKEN: "",
GH_TOKEN: "",
GITHUB_TOKEN: "",
};
const profile = await resolveFirstGithubToken({ env: profileEnv });
const profileToken = profile.githubToken.trim();
if (profileToken && !candidates.some((candidate) => candidate.token === profileToken)) {
candidates.push({ source: "auth-profile", token: profileToken });
}
return candidates;
}
function extractText(response: unknown): string {
const content = (response as { content?: Array<{ type?: string; text?: string }> }).content;
if (!Array.isArray(content)) {
return "";
}
const text: string[] = [];
for (const block of content) {
if (block.type === "text") {
const trimmed = block.text?.trim() ?? "";
if (trimmed.length > 0) {
text.push(trimmed);
}
}
}
return text.join(" ");
}
describeLive("github-copilot connection-bound Responses IDs live", () => {
it("rewrites replayed connection-bound item IDs before sending to Copilot", async () => {
logProgress("start");
const candidates = await resolveGithubTokenCandidates();
if (candidates.length === 0) {
logProgress("skip (no GitHub Copilot token found in env or auth profile)");
return;
}
let token: CopilotApiToken | undefined;
const failures: string[] = [];
for (const candidate of candidates) {
try {
logProgress(`exchanging ${candidate.source} GitHub token for Copilot token`);
token = await withTimeout(
"Copilot token exchange",
resolveCopilotApiToken({
githubToken: candidate.token,
fetchImpl: fetchWithTimeout,
}),
15_000,
);
logProgress(
`token ok via ${candidate.source} (${token.source.startsWith("cache:") ? "cache" : "fetched"})`,
);
break;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
failures.push(`${candidate.source}: ${message}`);
logProgress(`token exchange failed via ${candidate.source} (${message})`);
}
}
if (!token) {
throw new Error(`Copilot token exchange failed for all candidates: ${failures.join("; ")}`);
}
const model = buildModel(token.baseUrl);
const staleId = Buffer.from(`copilot-${"x".repeat(24)}`).toString("base64");
const context = {
messages: [
buildReplayAssistantMessage(staleId),
{
role: "user" as const,
content: "Reply with exactly: COPILOT_LIVE_OK",
timestamp: Date.now(),
},
],
};
let capturedPayload: Record<string, unknown> | undefined;
const wrappedStream = wrapCopilotOpenAIResponsesStream(streamModel as never);
if (!wrappedStream) {
throw new Error("expected Copilot Responses stream wrapper");
}
const stream = wrappedStream(
model as never,
context as never,
{
apiKey: token.token,
headers: buildCopilotDynamicHeaders({
messages: context.messages,
hasImages: false,
}),
maxTokens: 32,
onPayload: (payload: unknown) => {
capturedPayload = payload as Record<string, unknown>;
},
} as never,
) as { result(): Promise<unknown> };
logProgress("sending Responses request");
const result = await stream.result();
logProgress("Responses request completed");
const input = Array.isArray(capturedPayload?.input) ? capturedPayload.input : [];
const replayedAssistant = input.find(
(item): item is Record<string, unknown> =>
Boolean(item) &&
typeof item === "object" &&
(item as Record<string, unknown>).type === "message",
);
expect(replayedAssistant?.id).toMatch(/^msg_[a-f0-9]{16}$/);
expect(replayedAssistant?.id).not.toBe(staleId);
expect(extractText(result)).toMatch(/^COPILOT_LIVE_OK[.!]?$/i);
}, 60_000);
});