@aspruyt/xfg 8.3.2 → 8.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/anthropic-client.d.ts +2 -0
- package/dist/ai/anthropic-client.js +7 -1
- package/dist/ai/change-describer.d.ts +1 -0
- package/dist/ai/change-describer.js +40 -19
- package/dist/ai/client-factory.d.ts +2 -2
- package/dist/ai/client-factory.js +105 -9
- package/dist/ai/http.js +23 -6
- package/dist/ai/index.d.ts +1 -1
- package/dist/ai/openai-compatible-client.d.ts +2 -0
- package/dist/ai/openai-compatible-client.js +6 -3
- package/dist/ai/types.d.ts +3 -2
- package/dist/config/index.d.ts +1 -1
- package/dist/config/normalizer.js +18 -2
- package/dist/config/types.d.ts +13 -2
- package/dist/config/validators/ai-validator.js +27 -10
- package/dist/settings/repo-settings/processor.js +1 -1
- package/dist/shared/credential-env.d.ts +12 -1
- package/dist/shared/credential-env.js +65 -3
- package/dist/sync/repository-processor.js +1 -1
- package/package.json +1 -1
|
@@ -4,12 +4,14 @@ export interface AnthropicClientOptions {
|
|
|
4
4
|
apiKey: string;
|
|
5
5
|
model: string;
|
|
6
6
|
baseUrl?: string;
|
|
7
|
+
headers?: Record<string, string>;
|
|
7
8
|
fetch: FetchFn;
|
|
8
9
|
}
|
|
9
10
|
export declare class AnthropicClient implements IAiClient {
|
|
10
11
|
readonly model: string;
|
|
11
12
|
private readonly apiKey;
|
|
12
13
|
private readonly url;
|
|
14
|
+
private readonly headers;
|
|
13
15
|
private readonly fetch;
|
|
14
16
|
constructor(options: AnthropicClientOptions);
|
|
15
17
|
complete(system: string, user: string, schema?: JsonSchema): Promise<string>;
|
|
@@ -6,11 +6,13 @@ export class AnthropicClient {
|
|
|
6
6
|
model;
|
|
7
7
|
apiKey;
|
|
8
8
|
url;
|
|
9
|
+
headers;
|
|
9
10
|
fetch;
|
|
10
11
|
constructor(options) {
|
|
11
12
|
this.model = options.model;
|
|
12
13
|
this.apiKey = options.apiKey;
|
|
13
14
|
this.url = `${trimTrailingSlash(options.baseUrl ?? DEFAULT_BASE_URL)}/v1/messages`;
|
|
15
|
+
this.headers = options.headers ?? {};
|
|
14
16
|
this.fetch = options.fetch;
|
|
15
17
|
}
|
|
16
18
|
async complete(system, user, schema) {
|
|
@@ -23,7 +25,11 @@ export class AnthropicClient {
|
|
|
23
25
|
if (schema) {
|
|
24
26
|
body.output_config = { format: { type: "json_schema", schema } };
|
|
25
27
|
}
|
|
26
|
-
const response = (await postJson(this.fetch, "Anthropic API", this.url, {
|
|
28
|
+
const response = (await postJson(this.fetch, "Anthropic API", this.url, {
|
|
29
|
+
...this.headers,
|
|
30
|
+
"x-api-key": this.apiKey,
|
|
31
|
+
"anthropic-version": "2023-06-01",
|
|
32
|
+
}, body));
|
|
27
33
|
if (response.stop_reason === "refusal") {
|
|
28
34
|
throw new Error("Anthropic API refused the request");
|
|
29
35
|
}
|
|
@@ -121,6 +121,15 @@ export function buildUserPrompt(files, maxDiffChars) {
|
|
|
121
121
|
});
|
|
122
122
|
return `Changed files:\n\n${sections.join("\n\n")}`;
|
|
123
123
|
}
|
|
124
|
+
function buildAttempt(files, options, path, inherited) {
|
|
125
|
+
const prompt = options.prompt ?? inherited?.prompt;
|
|
126
|
+
return {
|
|
127
|
+
options,
|
|
128
|
+
path,
|
|
129
|
+
system: prompt ? `${SYSTEM_PROMPT}\n\n${prompt}` : SYSTEM_PROMPT,
|
|
130
|
+
user: buildUserPrompt(files, options.maxDiffChars ?? inherited?.maxDiffChars ?? DEFAULT_MAX_DIFF_CHARS),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
124
133
|
export class AiChangeDescriber {
|
|
125
134
|
clientFactory;
|
|
126
135
|
log;
|
|
@@ -130,26 +139,29 @@ export class AiChangeDescriber {
|
|
|
130
139
|
this.log = log;
|
|
131
140
|
}
|
|
132
141
|
async describe(input) {
|
|
133
|
-
const {
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
142
|
+
const { fallback, ...primaryOptions } = input.options;
|
|
143
|
+
const primary = buildAttempt(input.files, primaryOptions, "prOptions.ai");
|
|
144
|
+
const fallbackAttempt = fallback
|
|
145
|
+
? buildAttempt(input.files, fallback, "prOptions.ai.fallback", primaryOptions)
|
|
146
|
+
: undefined;
|
|
138
147
|
const key = createHash("sha256")
|
|
139
|
-
.update(JSON.stringify([
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
148
|
+
.update(JSON.stringify([primary, fallbackAttempt].map((a) => a
|
|
149
|
+
? [
|
|
150
|
+
a.options.provider,
|
|
151
|
+
a.options.model,
|
|
152
|
+
a.options.baseUrl,
|
|
153
|
+
a.options.baseUrlEnv,
|
|
154
|
+
a.system,
|
|
155
|
+
a.user,
|
|
156
|
+
]
|
|
157
|
+
: null)))
|
|
146
158
|
.digest("hex");
|
|
147
159
|
let pending = this.cache.get(key);
|
|
148
160
|
if (pending) {
|
|
149
161
|
this.log.debug("Reusing cached AI commit message");
|
|
150
162
|
}
|
|
151
163
|
else {
|
|
152
|
-
pending = this.generate(
|
|
164
|
+
pending = this.generate(primary, fallbackAttempt, input.retries);
|
|
153
165
|
this.cache.set(key, pending);
|
|
154
166
|
}
|
|
155
167
|
try {
|
|
@@ -161,12 +173,21 @@ export class AiChangeDescriber {
|
|
|
161
173
|
return null;
|
|
162
174
|
}
|
|
163
175
|
}
|
|
164
|
-
async generate(
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
176
|
+
async generate(primary, fallback, retries) {
|
|
177
|
+
if (!fallback)
|
|
178
|
+
return this.attempt(primary, retries);
|
|
179
|
+
try {
|
|
180
|
+
// The fallback is the retry, so a down primary does not stall the sync.
|
|
181
|
+
return await this.attempt(primary, 0);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
this.log.warn(`AI provider failed, trying prOptions.ai.fallback: ${toErrorMessage(error)}`);
|
|
185
|
+
return this.attempt(fallback, retries);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
async attempt(attempt, retries) {
|
|
189
|
+
const client = this.clientFactory(attempt.options, attempt.path);
|
|
190
|
+
const raw = await withRetry(() => client.complete(attempt.system, attempt.user, RESPONSE_SCHEMA), { retries, permanentErrorPatterns: AI_PERMANENT_ERROR_PATTERNS });
|
|
170
191
|
return parseDescription(raw);
|
|
171
192
|
}
|
|
172
193
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
export declare function createAiClient(
|
|
1
|
+
import type { AiProviderOptions, FetchFn, IAiClient } from "./types.js";
|
|
2
|
+
export declare function createAiClient(configured: AiProviderOptions, env: Record<string, string | undefined>, fetch: FetchFn, path?: string): IAiClient;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ValidationError } from "../shared/errors.js";
|
|
2
|
-
import { assertAiKeyEnvAllowed, defaultAiKeyEnv, isDefaultAiBaseUrl, } from "../shared/credential-env.js";
|
|
2
|
+
import { assertAiBaseUrlEnvAllowed, assertAiHeadersEnvAllowed, assertAiKeyEnvAllowed, defaultAiKeyEnv, isDefaultAiBaseUrl, } from "../shared/credential-env.js";
|
|
3
3
|
import { AnthropicClient, DEFAULT_ANTHROPIC_MODEL, } from "./anthropic-client.js";
|
|
4
4
|
import { DEFAULT_OPENAI_BASE_URL, OpenAICompatibleClient, } from "./openai-compatible-client.js";
|
|
5
5
|
/** The default key env only applies to the provider's own API. */
|
|
@@ -10,36 +10,132 @@ function keyEnvFor(options) {
|
|
|
10
10
|
? defaultAiKeyEnv(options.provider)
|
|
11
11
|
: undefined;
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
// undici refuses CR, LF, NUL and non-Latin-1 in header values and echoes the value in its error.
|
|
14
|
+
function isValidHeaderValue(value) {
|
|
15
|
+
return !/[\n\r\u0100-\uffff]/.test(value) && !value.includes("\0");
|
|
16
|
+
}
|
|
17
|
+
// undici trims surrounding whitespace before sending, so a trailing newline is harmless.
|
|
18
|
+
function readEnv(env, name) {
|
|
19
|
+
return env[name]?.trim();
|
|
20
|
+
}
|
|
21
|
+
function readApiKey(env, keyEnv) {
|
|
22
|
+
const value = readEnv(env, keyEnv);
|
|
23
|
+
if (value && !isValidHeaderValue(value)) {
|
|
24
|
+
throw new ValidationError(`${keyEnv} holds an invalid API key value`);
|
|
25
|
+
}
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
function resolveBaseUrl(options, env, path) {
|
|
29
|
+
assertAiBaseUrlEnvAllowed(options.baseUrlEnv, options.baseUrl, path);
|
|
30
|
+
if (options.baseUrlEnv === undefined)
|
|
31
|
+
return options.baseUrl;
|
|
32
|
+
const value = readEnv(env, options.baseUrlEnv);
|
|
33
|
+
if (!value) {
|
|
34
|
+
throw new ValidationError(`${options.baseUrlEnv} is not set (required for ${path}.baseUrlEnv)`);
|
|
35
|
+
}
|
|
36
|
+
if (!isHttpUrl(value)) {
|
|
37
|
+
throw new ValidationError(`${options.baseUrlEnv} does not hold an http(s) URL (used for ${path}.baseUrlEnv)`);
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
// Userinfo is refused because undici rejects it and echoes the whole URL in its error.
|
|
42
|
+
function isHttpUrl(value) {
|
|
43
|
+
try {
|
|
44
|
+
const { protocol, username, password } = new URL(value);
|
|
45
|
+
if (username || password)
|
|
46
|
+
return false;
|
|
47
|
+
return protocol === "https:" || protocol === "http:";
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function escapeRegExp(value) {
|
|
54
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, String.raw `\$&`);
|
|
55
|
+
}
|
|
56
|
+
/** Replaces the resolved host in error text with the env var name that supplied it. */
|
|
57
|
+
class HostRedactingClient {
|
|
58
|
+
inner;
|
|
59
|
+
envName;
|
|
60
|
+
pattern;
|
|
61
|
+
constructor(inner, baseUrl, envName) {
|
|
62
|
+
this.inner = inner;
|
|
63
|
+
this.envName = envName;
|
|
64
|
+
const { host, hostname } = new URL(baseUrl);
|
|
65
|
+
const hosts = [...new Set([host, hostname])].sort((a, b) => b.length - a.length);
|
|
66
|
+
this.pattern = new RegExp(hosts.map(escapeRegExp).join("|"), "gi");
|
|
67
|
+
}
|
|
68
|
+
async complete(system, user, schema) {
|
|
69
|
+
try {
|
|
70
|
+
return await this.inner.complete(system, user, schema);
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (!(error instanceof Error))
|
|
74
|
+
throw error;
|
|
75
|
+
const redacted = new Error(error.message.replace(this.pattern, () => this.envName));
|
|
76
|
+
// Keep fields such as retryAfter that withRetry reads.
|
|
77
|
+
throw Object.assign(redacted, { ...error });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function resolveHeaders(options, env, path) {
|
|
82
|
+
const headers = {};
|
|
83
|
+
for (const [name, envName] of Object.entries(options.headersEnv ?? {})) {
|
|
84
|
+
const value = readEnv(env, envName);
|
|
85
|
+
if (!value) {
|
|
86
|
+
throw new ValidationError(`${envName} is not set (required for ${path}.headersEnv '${name}')`);
|
|
87
|
+
}
|
|
88
|
+
if (!isValidHeaderValue(value)) {
|
|
89
|
+
throw new ValidationError(`${envName} holds an invalid header value (used for ${path}.headersEnv '${name}')`);
|
|
90
|
+
}
|
|
91
|
+
headers[name] = value;
|
|
92
|
+
}
|
|
93
|
+
return headers;
|
|
94
|
+
}
|
|
95
|
+
function buildClient(options, env, fetch, path) {
|
|
96
|
+
assertAiKeyEnvAllowed(options.provider, options.apiKeyEnv, options.baseUrl, path);
|
|
97
|
+
assertAiHeadersEnvAllowed(options.headersEnv, path);
|
|
15
98
|
const keyEnv = keyEnvFor(options);
|
|
16
99
|
if (options.provider === "anthropic") {
|
|
17
100
|
if (keyEnv === undefined) {
|
|
18
|
-
throw new ValidationError(
|
|
101
|
+
throw new ValidationError(`${path}.apiKeyEnv is required for provider 'anthropic' with a custom baseUrl`);
|
|
19
102
|
}
|
|
20
|
-
const apiKey = env
|
|
103
|
+
const apiKey = readApiKey(env, keyEnv);
|
|
21
104
|
if (!apiKey) {
|
|
22
|
-
throw new ValidationError(`${keyEnv} is not set (required for
|
|
105
|
+
throw new ValidationError(`${keyEnv} is not set (required for ${path} provider 'anthropic')`);
|
|
23
106
|
}
|
|
24
107
|
return new AnthropicClient({
|
|
25
108
|
apiKey,
|
|
26
109
|
model: options.model ?? DEFAULT_ANTHROPIC_MODEL,
|
|
27
110
|
baseUrl: options.baseUrl,
|
|
111
|
+
headers: resolveHeaders(options, env, path),
|
|
28
112
|
fetch,
|
|
29
113
|
});
|
|
30
114
|
}
|
|
31
115
|
if (!options.model) {
|
|
32
|
-
throw new ValidationError(
|
|
116
|
+
throw new ValidationError(`${path}.model is required when provider is 'openai'`);
|
|
33
117
|
}
|
|
34
|
-
const apiKey = keyEnv === undefined ? undefined : env
|
|
118
|
+
const apiKey = keyEnv === undefined ? undefined : readApiKey(env, keyEnv);
|
|
35
119
|
// A custom baseUrl (Ollama, local LiteLLM) often needs no key at all.
|
|
36
120
|
if (!apiKey && !options.baseUrl) {
|
|
37
|
-
throw new ValidationError(`${keyEnv} is not set (required for
|
|
121
|
+
throw new ValidationError(`${keyEnv} is not set (required for ${path} provider 'openai' without baseUrl)`);
|
|
38
122
|
}
|
|
39
123
|
return new OpenAICompatibleClient({
|
|
40
124
|
apiKey,
|
|
41
125
|
model: options.model,
|
|
42
126
|
baseUrl: options.baseUrl ?? DEFAULT_OPENAI_BASE_URL,
|
|
127
|
+
headers: resolveHeaders(options, env, path),
|
|
43
128
|
fetch,
|
|
44
129
|
});
|
|
45
130
|
}
|
|
131
|
+
export function createAiClient(configured, env, fetch, path = "prOptions.ai") {
|
|
132
|
+
const options = {
|
|
133
|
+
...configured,
|
|
134
|
+
baseUrl: resolveBaseUrl(configured, env, path),
|
|
135
|
+
};
|
|
136
|
+
const client = buildClient(options, env, fetch, path);
|
|
137
|
+
if (options.baseUrlEnv === undefined || options.baseUrl === undefined) {
|
|
138
|
+
return client;
|
|
139
|
+
}
|
|
140
|
+
return new HostRedactingClient(client, options.baseUrl, options.baseUrlEnv);
|
|
141
|
+
}
|
package/dist/ai/http.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseApiJson } from "../shared/json-utils.js";
|
|
2
|
+
import { isPlainObject, toErrorMessage } from "../shared/type-guards.js";
|
|
2
3
|
const REQUEST_TIMEOUT_MS = 60_000;
|
|
3
4
|
const MAX_ERROR_BODY_CHARS = 500;
|
|
4
5
|
export function trimTrailingSlash(url) {
|
|
@@ -18,13 +19,29 @@ function httpError(label, response, text) {
|
|
|
18
19
|
}
|
|
19
20
|
return error;
|
|
20
21
|
}
|
|
22
|
+
// fetch hides the reason (refused, DNS, connect timeout) in `cause`.
|
|
23
|
+
function networkError(label, error) {
|
|
24
|
+
const message = toErrorMessage(error);
|
|
25
|
+
const cause = error instanceof Error ? error.cause : undefined;
|
|
26
|
+
const code = isPlainObject(cause) ? cause.code : undefined;
|
|
27
|
+
const detail = typeof code === "string" ? `${message} (${code})` : message;
|
|
28
|
+
return new Error(`${label} request failed: ${detail}`);
|
|
29
|
+
}
|
|
21
30
|
export async function postJson(fetch, label, url, headers, body) {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
31
|
+
let response;
|
|
32
|
+
try {
|
|
33
|
+
response = await fetch(url, {
|
|
34
|
+
method: "POST",
|
|
35
|
+
headers: { "content-type": "application/json", ...headers },
|
|
36
|
+
body: JSON.stringify(body),
|
|
37
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
38
|
+
// Custom headers would follow a cross-origin redirect.
|
|
39
|
+
redirect: "error",
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
throw networkError(label, error);
|
|
44
|
+
}
|
|
28
45
|
const text = await response.text();
|
|
29
46
|
if (!response.ok) {
|
|
30
47
|
throw httpError(label, response, text);
|
package/dist/ai/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { AiOptions, AiClientFactory, ChangeDescription, DescribeInput, FetchFn, IAiClient, IChangeDescriber, JsonSchema, } from "./types.js";
|
|
1
|
+
export type { AiOptions, AiProviderOptions, AiClientFactory, ChangeDescription, DescribeInput, FetchFn, IAiClient, IChangeDescriber, JsonSchema, } from "./types.js";
|
|
2
2
|
export { AnthropicClient, DEFAULT_ANTHROPIC_MODEL, } from "./anthropic-client.js";
|
|
3
3
|
export { OpenAICompatibleClient, DEFAULT_OPENAI_BASE_URL, } from "./openai-compatible-client.js";
|
|
4
4
|
export { createAiClient } from "./client-factory.js";
|
|
@@ -4,12 +4,14 @@ export interface OpenAICompatibleClientOptions {
|
|
|
4
4
|
apiKey?: string;
|
|
5
5
|
model: string;
|
|
6
6
|
baseUrl: string;
|
|
7
|
+
headers?: Record<string, string>;
|
|
7
8
|
fetch: FetchFn;
|
|
8
9
|
}
|
|
9
10
|
export declare class OpenAICompatibleClient implements IAiClient {
|
|
10
11
|
readonly baseUrl: string;
|
|
11
12
|
private readonly model;
|
|
12
13
|
private readonly apiKey?;
|
|
14
|
+
private readonly headers;
|
|
13
15
|
private readonly fetch;
|
|
14
16
|
constructor(options: OpenAICompatibleClientOptions);
|
|
15
17
|
complete(system: string, user: string, schema?: JsonSchema): Promise<string>;
|
|
@@ -4,11 +4,13 @@ export class OpenAICompatibleClient {
|
|
|
4
4
|
baseUrl;
|
|
5
5
|
model;
|
|
6
6
|
apiKey;
|
|
7
|
+
headers;
|
|
7
8
|
fetch;
|
|
8
9
|
constructor(options) {
|
|
9
10
|
this.baseUrl = trimTrailingSlash(options.baseUrl);
|
|
10
11
|
this.model = options.model;
|
|
11
12
|
this.apiKey = options.apiKey;
|
|
13
|
+
this.headers = options.headers ?? {};
|
|
12
14
|
this.fetch = options.fetch;
|
|
13
15
|
}
|
|
14
16
|
async complete(system, user, schema) {
|
|
@@ -23,9 +25,10 @@ export class OpenAICompatibleClient {
|
|
|
23
25
|
if (schema) {
|
|
24
26
|
body.response_format = { type: "json_object" };
|
|
25
27
|
}
|
|
26
|
-
const headers =
|
|
27
|
-
|
|
28
|
-
: {}
|
|
28
|
+
const headers = {
|
|
29
|
+
...this.headers,
|
|
30
|
+
...(this.apiKey ? { authorization: `Bearer ${this.apiKey}` } : {}),
|
|
31
|
+
};
|
|
29
32
|
const response = (await postJson(this.fetch, "OpenAI-compatible API", `${this.baseUrl}/chat/completions`, headers, body));
|
|
30
33
|
const content = response.choices?.[0]?.message?.content;
|
|
31
34
|
if (!content) {
|
package/dist/ai/types.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import type { ResolvedAiConfig } from "../config/index.js";
|
|
1
|
+
import type { ResolvedAiConfig, ResolvedAiProviderConfig } from "../config/index.js";
|
|
2
2
|
import type { FileChangeDetail } from "../sync/types.js";
|
|
3
3
|
export type AiOptions = ResolvedAiConfig;
|
|
4
|
+
export type AiProviderOptions = ResolvedAiProviderConfig;
|
|
4
5
|
export type FetchFn = (url: string, init: RequestInit) => Promise<Response>;
|
|
5
6
|
export type JsonSchema = Record<string, unknown>;
|
|
6
7
|
export interface IAiClient {
|
|
7
8
|
complete(system: string, user: string, schema?: JsonSchema): Promise<string>;
|
|
8
9
|
}
|
|
9
|
-
export type AiClientFactory = (options:
|
|
10
|
+
export type AiClientFactory = (options: AiProviderOptions, path?: string) => IAiClient;
|
|
10
11
|
export interface DescribeInput {
|
|
11
12
|
files: FileChangeDetail[];
|
|
12
13
|
options: AiOptions;
|
package/dist/config/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { PRMergeOptions, RepoPROptions, AiConfig, AiProvider, ResolvedAiConfig, MergeMode, MergeStrategy, BypassActor, BypassMode, StatusCheckConfig, CodeScanningTool, PullRequestRuleParameters, RulesetRule, Ruleset, GitHubRepoSettings, RepoVisibility, SquashMergeCommitTitle, SquashMergeCommitMessage, MergeCommitTitle, MergeCommitMessage, Label, CodeScanningSettings, CodeScanningState, CodeScanningQuerySuite, CodeScanningLanguage, DeploymentBranchPatternType, DeploymentBranchPattern, DeploymentBranchPolicy, EnvironmentConfig, EnvironmentsConfig, RawEnvironmentConfig, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, CollaboratorsConfig, RawCollaboratorsConfig, SecretsConfig, RawRootSettings, RawRepoSettings, RawRepoConfig, RawConfig, RawConditionalGroupWhen, RawConditionalGroupConfig, RepoConfig, Config, FileContent, ContentValue, } from "./types.js";
|
|
1
|
+
export type { PRMergeOptions, RepoPROptions, AiConfig, AiProvider, ResolvedAiConfig, AiProviderConfig, ResolvedAiProviderConfig, MergeMode, MergeStrategy, BypassActor, BypassMode, StatusCheckConfig, CodeScanningTool, PullRequestRuleParameters, RulesetRule, Ruleset, GitHubRepoSettings, RepoVisibility, SquashMergeCommitTitle, SquashMergeCommitMessage, MergeCommitTitle, MergeCommitMessage, Label, CodeScanningSettings, CodeScanningState, CodeScanningQuerySuite, CodeScanningLanguage, DeploymentBranchPatternType, DeploymentBranchPattern, DeploymentBranchPolicy, EnvironmentConfig, EnvironmentsConfig, RawEnvironmentConfig, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, CollaboratorsConfig, RawCollaboratorsConfig, SecretsConfig, RawRootSettings, RawRepoSettings, RawRepoConfig, RawConfig, RawConditionalGroupWhen, RawConditionalGroupConfig, RepoConfig, Config, FileContent, ContentValue, } from "./types.js";
|
|
2
2
|
export { RULESET_COMPARABLE_FIELDS } from "./types.js";
|
|
3
3
|
export { loadRawConfig, loadConfig, normalizeConfig } from "./loader.js";
|
|
4
4
|
export { convertContentToString } from "./formatter.js";
|
|
@@ -91,8 +91,24 @@ function normalizeAiOption(prOptions) {
|
|
|
91
91
|
const { ai, lastAi: _lastAi, ...rest } = prOptions;
|
|
92
92
|
if (ai === true)
|
|
93
93
|
return { ...rest, ai: { provider: "anthropic" } };
|
|
94
|
-
if (ai)
|
|
95
|
-
|
|
94
|
+
if (ai) {
|
|
95
|
+
const { fallback, ...primary } = ai;
|
|
96
|
+
return {
|
|
97
|
+
...rest,
|
|
98
|
+
ai: {
|
|
99
|
+
...primary,
|
|
100
|
+
provider: primary.provider ?? "anthropic",
|
|
101
|
+
...(fallback
|
|
102
|
+
? {
|
|
103
|
+
fallback: {
|
|
104
|
+
...fallback,
|
|
105
|
+
provider: fallback.provider ?? "anthropic",
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
: {}),
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
96
112
|
return Object.keys(rest).length > 0 ? rest : undefined;
|
|
97
113
|
}
|
|
98
114
|
function rulesetLocation(name) {
|
package/dist/config/types.d.ts
CHANGED
|
@@ -2,17 +2,28 @@ import type { ArrayMergeStrategy } from "./merge.js";
|
|
|
2
2
|
export type MergeMode = "manual" | "auto" | "force" | "direct";
|
|
3
3
|
export type MergeStrategy = "merge" | "squash" | "rebase";
|
|
4
4
|
export type AiProvider = "anthropic" | "openai";
|
|
5
|
-
export interface
|
|
5
|
+
export interface AiProviderConfig {
|
|
6
6
|
provider?: AiProvider;
|
|
7
7
|
model?: string;
|
|
8
8
|
baseUrl?: string;
|
|
9
|
+
/** Name of the env var that holds the base URL; exclusive with `baseUrl` */
|
|
10
|
+
baseUrlEnv?: string;
|
|
9
11
|
apiKeyEnv?: string;
|
|
12
|
+
/** Extra request headers: header name to the env var that holds its value */
|
|
13
|
+
headersEnv?: Record<string, string>;
|
|
10
14
|
prompt?: string;
|
|
11
15
|
maxDiffChars?: number;
|
|
12
16
|
}
|
|
13
|
-
export
|
|
17
|
+
export interface AiConfig extends AiProviderConfig {
|
|
18
|
+
/** Tried when the primary provider fails; one level only */
|
|
19
|
+
fallback?: AiProviderConfig;
|
|
20
|
+
}
|
|
21
|
+
export type ResolvedAiProviderConfig = AiProviderConfig & {
|
|
14
22
|
provider: AiProvider;
|
|
15
23
|
};
|
|
24
|
+
export type ResolvedAiConfig = ResolvedAiProviderConfig & {
|
|
25
|
+
fallback?: ResolvedAiProviderConfig;
|
|
26
|
+
};
|
|
16
27
|
export interface PRMergeOptions {
|
|
17
28
|
merge?: MergeMode;
|
|
18
29
|
mergeStrategy?: MergeStrategy;
|
|
@@ -1,41 +1,58 @@
|
|
|
1
1
|
import { isPlainObject } from "../../shared/type-guards.js";
|
|
2
2
|
import { ValidationError } from "../../shared/errors.js";
|
|
3
|
-
import { assertAiKeyEnvAllowed } from "../../shared/credential-env.js";
|
|
3
|
+
import { assertAiBaseUrlEnvAllowed, assertAiHeadersEnvAllowed, assertAiKeyEnvAllowed, } from "../../shared/credential-env.js";
|
|
4
4
|
const VALID_PROVIDERS = ["anthropic", "openai"];
|
|
5
5
|
const STRING_FIELDS = ["model", "baseUrl", "apiKeyEnv", "prompt"];
|
|
6
|
-
const
|
|
6
|
+
const PROVIDER_KEYS = [
|
|
7
7
|
"provider",
|
|
8
8
|
"maxDiffChars",
|
|
9
|
+
"headersEnv",
|
|
10
|
+
"baseUrlEnv",
|
|
9
11
|
...STRING_FIELDS,
|
|
10
|
-
]
|
|
12
|
+
];
|
|
13
|
+
const PRIMARY_KEYS = new Set([...PROVIDER_KEYS, "fallback"]);
|
|
14
|
+
const FALLBACK_KEYS = new Set(PROVIDER_KEYS);
|
|
11
15
|
export function validateAiOption(ai) {
|
|
12
16
|
if (ai === undefined || typeof ai === "boolean")
|
|
13
17
|
return;
|
|
14
18
|
if (!isPlainObject(ai)) {
|
|
15
19
|
throw new ValidationError("prOptions.ai must be a boolean or an object");
|
|
16
20
|
}
|
|
17
|
-
|
|
21
|
+
validateProvider(ai, "prOptions.ai", PRIMARY_KEYS);
|
|
22
|
+
if (ai.fallback !== undefined) {
|
|
23
|
+
if (!isPlainObject(ai.fallback)) {
|
|
24
|
+
throw new ValidationError("prOptions.ai.fallback must be an object");
|
|
25
|
+
}
|
|
26
|
+
validateProvider(ai.fallback, "prOptions.ai.fallback", FALLBACK_KEYS);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function validateProvider(ai, path, knownKeys) {
|
|
30
|
+
const unknown = Object.keys(ai).find((key) => !knownKeys.has(key));
|
|
18
31
|
if (unknown !== undefined) {
|
|
19
|
-
throw new ValidationError(
|
|
32
|
+
throw new ValidationError(`${path} has unknown key '${unknown}'`);
|
|
20
33
|
}
|
|
21
34
|
const provider = ai.provider;
|
|
22
35
|
if (provider !== undefined &&
|
|
23
36
|
!VALID_PROVIDERS.includes(provider)) {
|
|
24
|
-
throw new ValidationError(
|
|
37
|
+
throw new ValidationError(`${path}.provider must be one of: ${VALID_PROVIDERS.join(", ")}`);
|
|
25
38
|
}
|
|
26
39
|
for (const field of STRING_FIELDS) {
|
|
27
40
|
const value = ai[field];
|
|
28
41
|
if (value !== undefined && (typeof value !== "string" || value === "")) {
|
|
29
|
-
throw new ValidationError(
|
|
42
|
+
throw new ValidationError(`${path}.${field} must be a non-empty string`);
|
|
30
43
|
}
|
|
31
44
|
}
|
|
32
|
-
|
|
45
|
+
assertAiBaseUrlEnvAllowed(ai.baseUrlEnv, ai.baseUrl, path);
|
|
46
|
+
assertAiKeyEnvAllowed(provider ?? "anthropic", ai.apiKeyEnv, ai.baseUrl, path,
|
|
47
|
+
// A URL read from the env is unknown here, so it never counts as the provider's own API.
|
|
48
|
+
ai.baseUrlEnv !== undefined);
|
|
49
|
+
assertAiHeadersEnvAllowed(ai.headersEnv, path);
|
|
33
50
|
if (provider === "openai" && ai.model === undefined) {
|
|
34
|
-
throw new ValidationError(
|
|
51
|
+
throw new ValidationError(`${path}.model is required when provider is 'openai'`);
|
|
35
52
|
}
|
|
36
53
|
const max = ai.maxDiffChars;
|
|
37
54
|
if (max !== undefined &&
|
|
38
55
|
(typeof max !== "number" || !Number.isInteger(max) || max <= 0)) {
|
|
39
|
-
throw new ValidationError(
|
|
56
|
+
throw new ValidationError(`${path}.maxDiffChars must be a positive integer`);
|
|
40
57
|
}
|
|
41
58
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { diffRepoSettings, getCurrentValue, hasRepoSettingsChanges, } from "./diff.js";
|
|
2
2
|
import { formatRepoSettingsPlan, } from "./formatter.js";
|
|
3
3
|
import { withGitHubGuards, buildDryRunResult, buildApplyResult, } from "../base-processor.js";
|
|
4
|
-
// GitHub rejects a commit message
|
|
4
|
+
// GitHub rejects a commit message sent without its title
|
|
5
5
|
const PAIRED_SETTINGS = [
|
|
6
6
|
["squashMergeCommitTitle", "squashMergeCommitMessage"],
|
|
7
7
|
["mergeCommitTitle", "mergeCommitMessage"],
|
|
@@ -7,4 +7,15 @@ export declare function isDefaultAiBaseUrl(provider: string, baseUrl: string | u
|
|
|
7
7
|
* A credential name may only feed `prOptions.ai` when it is the provider's
|
|
8
8
|
* own key going to the provider's own API.
|
|
9
9
|
*/
|
|
10
|
-
export declare function assertAiKeyEnvAllowed(provider: string, apiKeyEnv: string | undefined, baseUrl: string | undefined): void;
|
|
10
|
+
export declare function assertAiKeyEnvAllowed(provider: string, apiKeyEnv: string | undefined, baseUrl: string | undefined, path?: string, baseUrlFromEnv?: boolean): void;
|
|
11
|
+
/**
|
|
12
|
+
* `headersEnv` maps header names to env var names. A value is never accepted
|
|
13
|
+
* inline, and the env var may not be a credential xfg uses elsewhere.
|
|
14
|
+
*/
|
|
15
|
+
export declare function assertAiHeadersEnvAllowed(headersEnv: unknown, path?: string): void;
|
|
16
|
+
/**
|
|
17
|
+
* `baseUrlEnv` names the env var that holds the base URL. A URL is never
|
|
18
|
+
* accepted inline, the two forms are exclusive, and the env var may not be a
|
|
19
|
+
* credential xfg uses elsewhere.
|
|
20
|
+
*/
|
|
21
|
+
export declare function assertAiBaseUrlEnvAllowed(baseUrlEnv: unknown, baseUrl: unknown, path?: string): void;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ValidationError } from "./errors.js";
|
|
2
|
+
import { isPlainObject } from "./type-guards.js";
|
|
2
3
|
/** Credentials xfg itself reads; config must never route them anywhere else. */
|
|
3
4
|
export const CREDENTIAL_ENV_VARS = new Set([
|
|
4
5
|
"XFG_GITHUB_APP_PRIVATE_KEY",
|
|
@@ -39,12 +40,73 @@ export function isDefaultAiBaseUrl(provider, baseUrl) {
|
|
|
39
40
|
* A credential name may only feed `prOptions.ai` when it is the provider's
|
|
40
41
|
* own key going to the provider's own API.
|
|
41
42
|
*/
|
|
42
|
-
export function assertAiKeyEnvAllowed(provider, apiKeyEnv, baseUrl) {
|
|
43
|
+
export function assertAiKeyEnvAllowed(provider, apiKeyEnv, baseUrl, path = "prOptions.ai", baseUrlFromEnv = false) {
|
|
43
44
|
if (apiKeyEnv === undefined || !isCredentialEnvName(apiKeyEnv))
|
|
44
45
|
return;
|
|
45
46
|
const ownKey = apiKeyEnv.toUpperCase() === defaultAiKeyEnv(provider);
|
|
46
|
-
if (ownKey && isDefaultAiBaseUrl(provider, baseUrl))
|
|
47
|
+
if (ownKey && !baseUrlFromEnv && isDefaultAiBaseUrl(provider, baseUrl))
|
|
47
48
|
return;
|
|
48
|
-
throw new ValidationError(
|
|
49
|
+
throw new ValidationError(`${path}.apiKeyEnv '${apiKeyEnv}' is a credential xfg uses elsewhere; ` +
|
|
49
50
|
`export the key under a dedicated name for this provider and baseUrl.`);
|
|
50
51
|
}
|
|
52
|
+
const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
53
|
+
const ENV_NAME = /^[A-Za-z_]\w*$/;
|
|
54
|
+
const RESERVED_AI_HEADERS = new Set([
|
|
55
|
+
"authorization",
|
|
56
|
+
"x-api-key",
|
|
57
|
+
"anthropic-version",
|
|
58
|
+
"content-type",
|
|
59
|
+
"content-length",
|
|
60
|
+
"host",
|
|
61
|
+
]);
|
|
62
|
+
/**
|
|
63
|
+
* `headersEnv` maps header names to env var names. A value is never accepted
|
|
64
|
+
* inline, and the env var may not be a credential xfg uses elsewhere.
|
|
65
|
+
*/
|
|
66
|
+
export function assertAiHeadersEnvAllowed(headersEnv, path = "prOptions.ai") {
|
|
67
|
+
if (headersEnv === undefined)
|
|
68
|
+
return;
|
|
69
|
+
if (!isPlainObject(headersEnv)) {
|
|
70
|
+
throw new ValidationError(`${path}.headersEnv must be an object of header name to env var name`);
|
|
71
|
+
}
|
|
72
|
+
const seen = new Set();
|
|
73
|
+
for (const [name, envName] of Object.entries(headersEnv)) {
|
|
74
|
+
if (!HEADER_NAME.test(name)) {
|
|
75
|
+
throw new ValidationError(`${path}.headersEnv key '${name}' is not a valid HTTP header name`);
|
|
76
|
+
}
|
|
77
|
+
const lower = name.toLowerCase();
|
|
78
|
+
if (RESERVED_AI_HEADERS.has(lower)) {
|
|
79
|
+
throw new ValidationError(`${path}.headersEnv header '${name}' is reserved; xfg sets it itself`);
|
|
80
|
+
}
|
|
81
|
+
if (seen.has(lower)) {
|
|
82
|
+
throw new ValidationError(`${path}.headersEnv names header '${name}' more than once`);
|
|
83
|
+
}
|
|
84
|
+
seen.add(lower);
|
|
85
|
+
if (typeof envName !== "string" || !ENV_NAME.test(envName)) {
|
|
86
|
+
throw new ValidationError(`${path}.headersEnv['${name}'] must be an env var name, not a value`);
|
|
87
|
+
}
|
|
88
|
+
if (isCredentialEnvName(envName)) {
|
|
89
|
+
throw new ValidationError(`${path}.headersEnv['${name}'] '${envName}' is a credential xfg uses elsewhere; ` +
|
|
90
|
+
`export the value under a dedicated name for this header.`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* `baseUrlEnv` names the env var that holds the base URL. A URL is never
|
|
96
|
+
* accepted inline, the two forms are exclusive, and the env var may not be a
|
|
97
|
+
* credential xfg uses elsewhere.
|
|
98
|
+
*/
|
|
99
|
+
export function assertAiBaseUrlEnvAllowed(baseUrlEnv, baseUrl, path = "prOptions.ai") {
|
|
100
|
+
if (baseUrlEnv === undefined)
|
|
101
|
+
return;
|
|
102
|
+
if (baseUrl !== undefined) {
|
|
103
|
+
throw new ValidationError(`${path}: baseUrl and baseUrlEnv are mutually exclusive`);
|
|
104
|
+
}
|
|
105
|
+
if (typeof baseUrlEnv !== "string" || !ENV_NAME.test(baseUrlEnv)) {
|
|
106
|
+
throw new ValidationError(`${path}.baseUrlEnv must be an env var name, not a value`);
|
|
107
|
+
}
|
|
108
|
+
if (isCredentialEnvName(baseUrlEnv)) {
|
|
109
|
+
throw new ValidationError(`${path}.baseUrlEnv '${baseUrlEnv}' is a credential xfg uses elsewhere; ` +
|
|
110
|
+
`export the URL under a dedicated name.`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -40,7 +40,7 @@ export class RepositoryProcessor {
|
|
|
40
40
|
const commitPushManager = components?.commitPushManager ?? new CommitPushManager(log);
|
|
41
41
|
const prMergeHandler = components?.prMergeHandler ?? new PRMergeHandler(log);
|
|
42
42
|
const changeDescriber = components?.changeDescriber ??
|
|
43
|
-
new AiChangeDescriber((opts) => createAiClient(opts, components?.aiEnv ?? {}, components?.fetch ?? globalThis.fetch), log);
|
|
43
|
+
new AiChangeDescriber((opts, path) => createAiClient(opts, components?.aiEnv ?? {}, components?.fetch ?? globalThis.fetch, path), log);
|
|
44
44
|
this.fileSyncOrchestrator =
|
|
45
45
|
components?.fileSyncOrchestrator ??
|
|
46
46
|
new FileSyncOrchestrator(fileWriter, manifestManager, log, components?.renderWriter ?? new RenderWriter());
|
package/package.json
CHANGED