@aspruyt/xfg 8.3.2 → 8.4.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.
@@ -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, { "x-api-key": this.apiKey, "anthropic-version": "2023-06-01" }, body));
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
  }
@@ -13,4 +13,5 @@ export declare class AiChangeDescriber implements IChangeDescriber {
13
13
  constructor(clientFactory: AiClientFactory, log: DebugWarnLog);
14
14
  describe(input: DescribeInput): Promise<ChangeDescription | null>;
15
15
  private generate;
16
+ private attempt;
16
17
  }
@@ -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,28 @@ export class AiChangeDescriber {
130
139
  this.log = log;
131
140
  }
132
141
  async describe(input) {
133
- const { options } = input;
134
- const system = options.prompt
135
- ? `${SYSTEM_PROMPT}\n\n${options.prompt}`
136
- : SYSTEM_PROMPT;
137
- const user = buildUserPrompt(input.files, options.maxDiffChars ?? DEFAULT_MAX_DIFF_CHARS);
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
- options.provider,
141
- options.model,
142
- options.baseUrl,
143
- system,
144
- user,
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.system,
154
+ a.user,
155
+ ]
156
+ : null)))
146
157
  .digest("hex");
147
158
  let pending = this.cache.get(key);
148
159
  if (pending) {
149
160
  this.log.debug("Reusing cached AI commit message");
150
161
  }
151
162
  else {
152
- pending = this.generate(input, system, user);
163
+ pending = this.generate(primary, fallbackAttempt, input.retries);
153
164
  this.cache.set(key, pending);
154
165
  }
155
166
  try {
@@ -161,12 +172,21 @@ export class AiChangeDescriber {
161
172
  return null;
162
173
  }
163
174
  }
164
- async generate(input, system, user) {
165
- const client = this.clientFactory(input.options);
166
- const raw = await withRetry(() => client.complete(system, user, RESPONSE_SCHEMA), {
167
- retries: input.retries,
168
- permanentErrorPatterns: AI_PERMANENT_ERROR_PATTERNS,
169
- });
175
+ async generate(primary, fallback, retries) {
176
+ if (!fallback)
177
+ return this.attempt(primary, retries);
178
+ try {
179
+ // The fallback is the retry, so a down primary does not stall the sync.
180
+ return await this.attempt(primary, 0);
181
+ }
182
+ catch (error) {
183
+ this.log.warn(`AI provider failed, trying prOptions.ai.fallback: ${toErrorMessage(error)}`);
184
+ return this.attempt(fallback, retries);
185
+ }
186
+ }
187
+ async attempt(attempt, retries) {
188
+ const client = this.clientFactory(attempt.options, attempt.path);
189
+ const raw = await withRetry(() => client.complete(attempt.system, attempt.user, RESPONSE_SCHEMA), { retries, permanentErrorPatterns: AI_PERMANENT_ERROR_PATTERNS });
170
190
  return parseDescription(raw);
171
191
  }
172
192
  }
@@ -1,2 +1,2 @@
1
- import type { AiOptions, FetchFn, IAiClient } from "./types.js";
2
- export declare function createAiClient(options: AiOptions, env: Record<string, string | undefined>, fetch: FetchFn): IAiClient;
1
+ import type { AiProviderOptions, FetchFn, IAiClient } from "./types.js";
2
+ export declare function createAiClient(options: 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 { 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,68 @@ function keyEnvFor(options) {
10
10
  ? defaultAiKeyEnv(options.provider)
11
11
  : undefined;
12
12
  }
13
- export function createAiClient(options, env, fetch) {
14
- assertAiKeyEnvAllowed(options.provider, options.apiKeyEnv, options.baseUrl);
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 resolveHeaders(options, env, path) {
29
+ const headers = {};
30
+ for (const [name, envName] of Object.entries(options.headersEnv ?? {})) {
31
+ const value = readEnv(env, envName);
32
+ if (!value) {
33
+ throw new ValidationError(`${envName} is not set (required for ${path}.headersEnv '${name}')`);
34
+ }
35
+ if (!isValidHeaderValue(value)) {
36
+ throw new ValidationError(`${envName} holds an invalid header value (used for ${path}.headersEnv '${name}')`);
37
+ }
38
+ headers[name] = value;
39
+ }
40
+ return headers;
41
+ }
42
+ export function createAiClient(options, env, fetch, path = "prOptions.ai") {
43
+ assertAiKeyEnvAllowed(options.provider, options.apiKeyEnv, options.baseUrl, path);
44
+ assertAiHeadersEnvAllowed(options.headersEnv, path);
15
45
  const keyEnv = keyEnvFor(options);
16
46
  if (options.provider === "anthropic") {
17
47
  if (keyEnv === undefined) {
18
- throw new ValidationError("prOptions.ai.apiKeyEnv is required for provider 'anthropic' with a custom baseUrl");
48
+ throw new ValidationError(`${path}.apiKeyEnv is required for provider 'anthropic' with a custom baseUrl`);
19
49
  }
20
- const apiKey = env[keyEnv];
50
+ const apiKey = readApiKey(env, keyEnv);
21
51
  if (!apiKey) {
22
- throw new ValidationError(`${keyEnv} is not set (required for prOptions.ai provider 'anthropic')`);
52
+ throw new ValidationError(`${keyEnv} is not set (required for ${path} provider 'anthropic')`);
23
53
  }
24
54
  return new AnthropicClient({
25
55
  apiKey,
26
56
  model: options.model ?? DEFAULT_ANTHROPIC_MODEL,
27
57
  baseUrl: options.baseUrl,
58
+ headers: resolveHeaders(options, env, path),
28
59
  fetch,
29
60
  });
30
61
  }
31
62
  if (!options.model) {
32
- throw new ValidationError("prOptions.ai.model is required when provider is 'openai'");
63
+ throw new ValidationError(`${path}.model is required when provider is 'openai'`);
33
64
  }
34
- const apiKey = keyEnv === undefined ? undefined : env[keyEnv];
65
+ const apiKey = keyEnv === undefined ? undefined : readApiKey(env, keyEnv);
35
66
  // A custom baseUrl (Ollama, local LiteLLM) often needs no key at all.
36
67
  if (!apiKey && !options.baseUrl) {
37
- throw new ValidationError(`${keyEnv} is not set (required for prOptions.ai provider 'openai' without baseUrl)`);
68
+ throw new ValidationError(`${keyEnv} is not set (required for ${path} provider 'openai' without baseUrl)`);
38
69
  }
39
70
  return new OpenAICompatibleClient({
40
71
  apiKey,
41
72
  model: options.model,
42
73
  baseUrl: options.baseUrl ?? DEFAULT_OPENAI_BASE_URL,
74
+ headers: resolveHeaders(options, env, path),
43
75
  fetch,
44
76
  });
45
77
  }
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
- const response = await fetch(url, {
23
- method: "POST",
24
- headers: { "content-type": "application/json", ...headers },
25
- body: JSON.stringify(body),
26
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
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);
@@ -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 = this.apiKey
27
- ? { authorization: `Bearer ${this.apiKey}` }
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) {
@@ -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: AiOptions) => IAiClient;
10
+ export type AiClientFactory = (options: AiProviderOptions, path?: string) => IAiClient;
10
11
  export interface DescribeInput {
11
12
  files: FileChangeDetail[];
12
13
  options: AiOptions;
@@ -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
- return { ...rest, ai: { ...ai, provider: ai.provider ?? "anthropic" } };
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) {
@@ -2,17 +2,26 @@ 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 AiConfig {
5
+ export interface AiProviderConfig {
6
6
  provider?: AiProvider;
7
7
  model?: string;
8
8
  baseUrl?: string;
9
9
  apiKeyEnv?: string;
10
+ /** Extra request headers: header name to the env var that holds its value */
11
+ headersEnv?: Record<string, string>;
10
12
  prompt?: string;
11
13
  maxDiffChars?: number;
12
14
  }
13
- export type ResolvedAiConfig = AiConfig & {
15
+ export interface AiConfig extends AiProviderConfig {
16
+ /** Tried when the primary provider fails; one level only */
17
+ fallback?: AiProviderConfig;
18
+ }
19
+ export type ResolvedAiProviderConfig = AiProviderConfig & {
14
20
  provider: AiProvider;
15
21
  };
22
+ export type ResolvedAiConfig = ResolvedAiProviderConfig & {
23
+ fallback?: ResolvedAiProviderConfig;
24
+ };
16
25
  export interface PRMergeOptions {
17
26
  merge?: MergeMode;
18
27
  mergeStrategy?: MergeStrategy;
@@ -1,41 +1,54 @@
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 { 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 KNOWN_KEYS = new Set([
6
+ const PROVIDER_KEYS = [
7
7
  "provider",
8
8
  "maxDiffChars",
9
+ "headersEnv",
9
10
  ...STRING_FIELDS,
10
- ]);
11
+ ];
12
+ const PRIMARY_KEYS = new Set([...PROVIDER_KEYS, "fallback"]);
13
+ const FALLBACK_KEYS = new Set(PROVIDER_KEYS);
11
14
  export function validateAiOption(ai) {
12
15
  if (ai === undefined || typeof ai === "boolean")
13
16
  return;
14
17
  if (!isPlainObject(ai)) {
15
18
  throw new ValidationError("prOptions.ai must be a boolean or an object");
16
19
  }
17
- const unknown = Object.keys(ai).find((key) => !KNOWN_KEYS.has(key));
20
+ validateProvider(ai, "prOptions.ai", PRIMARY_KEYS);
21
+ if (ai.fallback !== undefined) {
22
+ if (!isPlainObject(ai.fallback)) {
23
+ throw new ValidationError("prOptions.ai.fallback must be an object");
24
+ }
25
+ validateProvider(ai.fallback, "prOptions.ai.fallback", FALLBACK_KEYS);
26
+ }
27
+ }
28
+ function validateProvider(ai, path, knownKeys) {
29
+ const unknown = Object.keys(ai).find((key) => !knownKeys.has(key));
18
30
  if (unknown !== undefined) {
19
- throw new ValidationError(`prOptions.ai has unknown key '${unknown}'`);
31
+ throw new ValidationError(`${path} has unknown key '${unknown}'`);
20
32
  }
21
33
  const provider = ai.provider;
22
34
  if (provider !== undefined &&
23
35
  !VALID_PROVIDERS.includes(provider)) {
24
- throw new ValidationError(`prOptions.ai.provider must be one of: ${VALID_PROVIDERS.join(", ")}`);
36
+ throw new ValidationError(`${path}.provider must be one of: ${VALID_PROVIDERS.join(", ")}`);
25
37
  }
26
38
  for (const field of STRING_FIELDS) {
27
39
  const value = ai[field];
28
40
  if (value !== undefined && (typeof value !== "string" || value === "")) {
29
- throw new ValidationError(`prOptions.ai.${field} must be a non-empty string`);
41
+ throw new ValidationError(`${path}.${field} must be a non-empty string`);
30
42
  }
31
43
  }
32
- assertAiKeyEnvAllowed(provider ?? "anthropic", ai.apiKeyEnv, ai.baseUrl);
44
+ assertAiKeyEnvAllowed(provider ?? "anthropic", ai.apiKeyEnv, ai.baseUrl, path);
45
+ assertAiHeadersEnvAllowed(ai.headersEnv, path);
33
46
  if (provider === "openai" && ai.model === undefined) {
34
- throw new ValidationError("prOptions.ai.model is required when provider is 'openai'");
47
+ throw new ValidationError(`${path}.model is required when provider is 'openai'`);
35
48
  }
36
49
  const max = ai.maxDiffChars;
37
50
  if (max !== undefined &&
38
51
  (typeof max !== "number" || !Number.isInteger(max) || max <= 0)) {
39
- throw new ValidationError("prOptions.ai.maxDiffChars must be a positive integer");
52
+ throw new ValidationError(`${path}.maxDiffChars must be a positive integer`);
40
53
  }
41
54
  }
@@ -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 setting sent without its title, and vice versa
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,9 @@ 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): 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;
@@ -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,54 @@ 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") {
43
44
  if (apiKeyEnv === undefined || !isCredentialEnvName(apiKeyEnv))
44
45
  return;
45
46
  const ownKey = apiKeyEnv.toUpperCase() === defaultAiKeyEnv(provider);
46
47
  if (ownKey && isDefaultAiBaseUrl(provider, baseUrl))
47
48
  return;
48
- throw new ValidationError(`prOptions.ai.apiKeyEnv '${apiKeyEnv}' is a credential xfg uses elsewhere; ` +
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
+ }
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aspruyt/xfg",
3
- "version": "8.3.2",
3
+ "version": "8.4.0",
4
4
  "description": "Manage files, settings, and repositories across GitHub, Azure DevOps, and GitLab — declaratively, from a single YAML config",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",