@aspruyt/xfg 7.2.1 → 7.3.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/PR.md +2 -0
- package/dist/ai/anthropic-client.d.ts +16 -0
- package/dist/ai/anthropic-client.js +35 -0
- package/dist/ai/change-describer.d.ts +16 -0
- package/dist/ai/change-describer.js +170 -0
- package/dist/ai/client-factory.d.ts +2 -0
- package/dist/ai/client-factory.js +33 -0
- package/dist/ai/http.d.ts +3 -0
- package/dist/ai/http.js +33 -0
- package/dist/ai/index.d.ts +5 -0
- package/dist/ai/index.js +4 -0
- package/dist/ai/openai-compatible-client.d.ts +16 -0
- package/dist/ai/openai-compatible-client.js +36 -0
- package/dist/ai/types.d.ts +22 -0
- package/dist/ai/types.js +1 -0
- package/dist/cli/program.d.ts +7 -0
- package/dist/cli/program.js +15 -11
- package/dist/cli/repo-sync-runner.js +1 -0
- package/dist/cli/secrets-command.js +1 -0
- package/dist/cli/sync-command.js +2 -0
- package/dist/cli/types.d.ts +1 -0
- package/dist/cli/unified-summary.d.ts +3 -1
- package/dist/cli/unified-summary.js +14 -26
- package/dist/config/index.d.ts +1 -1
- package/dist/config/index.js +0 -2
- package/dist/config/normalizer.js +17 -24
- package/dist/config/types.d.ts +17 -1
- package/dist/config/validator.js +2 -4
- package/dist/config/validators/ai-validator.d.ts +1 -0
- package/dist/config/validators/ai-validator.js +39 -0
- package/dist/config/validators/group-validator.js +3 -0
- package/dist/config/validators/repo-entry-validator.js +2 -0
- package/dist/lifecycle/formatter.d.ts +0 -4
- package/dist/lifecycle/formatter.js +2 -6
- package/dist/output/github-summary.d.ts +4 -3
- package/dist/output/github-summary.js +22 -5
- package/dist/output/lifecycle-report.d.ts +3 -2
- package/dist/output/lifecycle-report.js +20 -26
- package/dist/output/settings-report.d.ts +3 -2
- package/dist/output/settings-report.js +36 -47
- package/dist/output/summary-budget.d.ts +12 -0
- package/dist/output/summary-budget.js +125 -0
- package/dist/output/sync-report.d.ts +6 -3
- package/dist/output/sync-report.js +33 -34
- package/dist/settings/labels/formatter.d.ts +0 -3
- package/dist/settings/labels/formatter.js +10 -17
- package/dist/settings/rulesets/formatter.d.ts +0 -6
- package/dist/settings/rulesets/formatter.js +4 -32
- package/dist/settings/secrets/formatter.js +4 -3
- package/dist/settings/variables/formatter.js +6 -5
- package/dist/shared/markdown-fence.d.ts +3 -0
- package/dist/shared/markdown-fence.js +32 -0
- package/dist/shared/string-utils.d.ts +1 -3
- package/dist/shared/string-utils.js +5 -4
- package/dist/sync/commit-push-manager.js +2 -2
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/pr-merge-handler.js +3 -1
- package/dist/sync/repository-processor.d.ts +5 -0
- package/dist/sync/repository-processor.js +4 -1
- package/dist/sync/sync-workflow.d.ts +4 -1
- package/dist/sync/sync-workflow.js +29 -2
- package/dist/sync/types.d.ts +14 -3
- package/dist/vcs/ado-pr-strategy.js +43 -1
- package/dist/vcs/git-commit-strategy.js +3 -5
- package/dist/vcs/graphql-commit-strategy.js +3 -6
- package/dist/vcs/pr-creator.d.ts +5 -10
- package/dist/vcs/pr-creator.js +34 -20
- package/dist/vcs/types.d.ts +1 -0
- package/package.json +3 -2
package/PR.md
CHANGED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { FetchFn, IAiClient, JsonSchema } from "./types.js";
|
|
2
|
+
export declare const DEFAULT_ANTHROPIC_MODEL = "claude-haiku-4-5";
|
|
3
|
+
export interface AnthropicClientOptions {
|
|
4
|
+
apiKey: string;
|
|
5
|
+
model: string;
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
fetch: FetchFn;
|
|
8
|
+
}
|
|
9
|
+
export declare class AnthropicClient implements IAiClient {
|
|
10
|
+
readonly model: string;
|
|
11
|
+
private readonly apiKey;
|
|
12
|
+
private readonly url;
|
|
13
|
+
private readonly fetch;
|
|
14
|
+
constructor(options: AnthropicClientOptions);
|
|
15
|
+
complete(system: string, user: string, schema?: JsonSchema): Promise<string>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { postJson, trimTrailingSlash } from "./http.js";
|
|
2
|
+
export const DEFAULT_ANTHROPIC_MODEL = "claude-haiku-4-5";
|
|
3
|
+
const DEFAULT_BASE_URL = "https://api.anthropic.com";
|
|
4
|
+
const MAX_TOKENS = 2048;
|
|
5
|
+
export class AnthropicClient {
|
|
6
|
+
model;
|
|
7
|
+
apiKey;
|
|
8
|
+
url;
|
|
9
|
+
fetch;
|
|
10
|
+
constructor(options) {
|
|
11
|
+
this.model = options.model;
|
|
12
|
+
this.apiKey = options.apiKey;
|
|
13
|
+
this.url = `${trimTrailingSlash(options.baseUrl ?? DEFAULT_BASE_URL)}/v1/messages`;
|
|
14
|
+
this.fetch = options.fetch;
|
|
15
|
+
}
|
|
16
|
+
async complete(system, user, schema) {
|
|
17
|
+
const body = {
|
|
18
|
+
model: this.model,
|
|
19
|
+
max_tokens: MAX_TOKENS,
|
|
20
|
+
system,
|
|
21
|
+
messages: [{ role: "user", content: user }],
|
|
22
|
+
};
|
|
23
|
+
if (schema) {
|
|
24
|
+
body.output_config = { format: { type: "json_schema", schema } };
|
|
25
|
+
}
|
|
26
|
+
const response = (await postJson(this.fetch, "Anthropic API", this.url, { "x-api-key": this.apiKey, "anthropic-version": "2023-06-01" }, body));
|
|
27
|
+
if (response.stop_reason === "refusal") {
|
|
28
|
+
throw new Error("Anthropic API refused the request");
|
|
29
|
+
}
|
|
30
|
+
return (response.content ?? [])
|
|
31
|
+
.filter((block) => block.type === "text")
|
|
32
|
+
.map((block) => block.text ?? "")
|
|
33
|
+
.join("");
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { DebugWarnLog } from "../shared/logger.js";
|
|
2
|
+
import type { FileChangeDetail } from "../sync/types.js";
|
|
3
|
+
import type { AiClientFactory, ChangeDescription, DescribeInput, IChangeDescriber } from "./types.js";
|
|
4
|
+
export declare const DEFAULT_MAX_DIFF_CHARS = 20000;
|
|
5
|
+
export declare function neutralizeReferences(text: string): string;
|
|
6
|
+
export declare function isConventionalSubject(subject: string): boolean;
|
|
7
|
+
export declare function parseDescription(raw: string): ChangeDescription;
|
|
8
|
+
export declare function buildUserPrompt(files: FileChangeDetail[], maxDiffChars: number): string;
|
|
9
|
+
export declare class AiChangeDescriber implements IChangeDescriber {
|
|
10
|
+
private readonly clientFactory;
|
|
11
|
+
private readonly log;
|
|
12
|
+
private readonly cache;
|
|
13
|
+
constructor(clientFactory: AiClientFactory, log: DebugWarnLog);
|
|
14
|
+
describe(input: DescribeInput): Promise<ChangeDescription | null>;
|
|
15
|
+
private generate;
|
|
16
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { isPlainObject, toErrorMessage } from "../shared/type-guards.js";
|
|
3
|
+
import { CORE_PERMANENT_ERROR_PATTERNS, withRetry, } from "../shared/retry-utils.js";
|
|
4
|
+
export const DEFAULT_MAX_DIFF_CHARS = 20_000;
|
|
5
|
+
const MAX_SUBJECT_LENGTH = 72;
|
|
6
|
+
const CONVENTIONAL_TYPES = [
|
|
7
|
+
"feat",
|
|
8
|
+
"fix",
|
|
9
|
+
"chore",
|
|
10
|
+
"ci",
|
|
11
|
+
"build",
|
|
12
|
+
"docs",
|
|
13
|
+
"style",
|
|
14
|
+
"refactor",
|
|
15
|
+
"perf",
|
|
16
|
+
"test",
|
|
17
|
+
"revert",
|
|
18
|
+
];
|
|
19
|
+
const CONVENTIONAL_SUBJECT = new RegExp(`^(${CONVENTIONAL_TYPES.join("|")})(\\([a-z0-9._/-]+\\))?!?: \\S.*$`);
|
|
20
|
+
const SYSTEM_PROMPT = `You write git commit messages and pull request summaries for automated configuration sync changes.
|
|
21
|
+
You receive the list of changed files with unified diffs. Reply with a JSON object with exactly these keys:
|
|
22
|
+
- "subject": a Conventional Commits subject line, at most ${MAX_SUBJECT_LENGTH} characters, format "type(scope): description". type is one of: ${CONVENTIONAL_TYPES.join(", ")}. scope is optional, lowercase, and names the area changed (e.g. workflows, devcontainer, eslint). description is imperative, lowercase, no trailing period, and says what actually changed (e.g. "pin actions/checkout to v5"), never just "sync files".
|
|
23
|
+
- "body": an optional commit body (plain text, wrap at 72 columns) explaining the notable changes. Use an empty string if the subject says it all.
|
|
24
|
+
- "prSummary": a short markdown summary for a pull request description (a sentence or a few bullet points). No headings.
|
|
25
|
+
Pick the type from the effect of the change: ci for CI config, build for build tooling and dev environments, style for formatter/linter config, docs for documentation, chore otherwise.
|
|
26
|
+
Only describe what is in the diffs. Do not invent reasons.`;
|
|
27
|
+
const RESPONSE_SCHEMA = {
|
|
28
|
+
type: "object",
|
|
29
|
+
properties: {
|
|
30
|
+
subject: { type: "string" },
|
|
31
|
+
body: { type: "string" },
|
|
32
|
+
prSummary: { type: "string" },
|
|
33
|
+
},
|
|
34
|
+
required: ["subject", "body", "prSummary"],
|
|
35
|
+
additionalProperties: false,
|
|
36
|
+
};
|
|
37
|
+
const AI_PERMANENT_ERROR_PATTERNS = [
|
|
38
|
+
...CORE_PERMANENT_ERROR_PATTERNS,
|
|
39
|
+
/\b400\b/,
|
|
40
|
+
];
|
|
41
|
+
// GitHub and GitLab close issues on these keywords; the text is model output shaped by repo content.
|
|
42
|
+
const CLOSING_KEYWORD = /\b(?:clos(?:e[sd]?|ing)|fix(?:e[sd]|ing)?|resolv(?:e[sd]?|ing)|implement(?:s|ed|ing)?)\b(?=:?\s+(?:[\w.-]+\/[\w.-]+)?#\d|:?\s+https?:\/\/)/gi;
|
|
43
|
+
const MENTION = /(^|[^\w`/.@-])@([a-z0-9][a-z0-9-]*(?:\/[\w-]+)?)/gi;
|
|
44
|
+
export function neutralizeReferences(text) {
|
|
45
|
+
return text
|
|
46
|
+
.replace(CLOSING_KEYWORD, (word) => (/^[A-Z]/.test(word) ? "Refs" : "refs"))
|
|
47
|
+
.replace(MENTION, "$1`@$2`");
|
|
48
|
+
}
|
|
49
|
+
export function isConventionalSubject(subject) {
|
|
50
|
+
return (subject.length <= MAX_SUBJECT_LENGTH && CONVENTIONAL_SUBJECT.test(subject));
|
|
51
|
+
}
|
|
52
|
+
export function parseDescription(raw) {
|
|
53
|
+
const json = raw
|
|
54
|
+
.trim()
|
|
55
|
+
.replace(/^```(?:json)?\s*/i, "")
|
|
56
|
+
.replace(/\s*```$/, "");
|
|
57
|
+
const parsed = JSON.parse(json);
|
|
58
|
+
if (!isPlainObject(parsed)) {
|
|
59
|
+
throw new Error("AI response is not a JSON object");
|
|
60
|
+
}
|
|
61
|
+
const text = (value) => typeof value === "string" ? neutralizeReferences(value.trim()) : "";
|
|
62
|
+
const subject = text(parsed.subject);
|
|
63
|
+
if (!isConventionalSubject(subject)) {
|
|
64
|
+
throw new Error(`AI subject is not a valid conventional commit: "${subject}"`);
|
|
65
|
+
}
|
|
66
|
+
const prSummary = text(parsed.prSummary);
|
|
67
|
+
if (!prSummary) {
|
|
68
|
+
throw new Error("AI response is missing prSummary");
|
|
69
|
+
}
|
|
70
|
+
const body = text(parsed.body);
|
|
71
|
+
return { subject, ...(body ? { body } : {}), prSummary };
|
|
72
|
+
}
|
|
73
|
+
function truncationNote(droppedLines, midLine) {
|
|
74
|
+
const lines = `${droppedLines} more lines`;
|
|
75
|
+
if (!midLine)
|
|
76
|
+
return `\n... (truncated ${lines})`;
|
|
77
|
+
return droppedLines > 0
|
|
78
|
+
? `\n... (truncated mid-line and ${lines})`
|
|
79
|
+
: "\n... (truncated mid-line)";
|
|
80
|
+
}
|
|
81
|
+
function truncateDiff(text, limit) {
|
|
82
|
+
if (text.length <= limit)
|
|
83
|
+
return text;
|
|
84
|
+
const totalLines = text.split("\n").length;
|
|
85
|
+
// Reserve room for the longest note this diff could need.
|
|
86
|
+
const room = limit - truncationNote(totalLines, true).length;
|
|
87
|
+
if (room <= 0)
|
|
88
|
+
return "(diff omitted)";
|
|
89
|
+
const cut = text.lastIndexOf("\n", room);
|
|
90
|
+
if (cut === -1) {
|
|
91
|
+
return `${text.slice(0, room)}${truncationNote(totalLines - 1, true)}`;
|
|
92
|
+
}
|
|
93
|
+
const kept = text.slice(0, cut);
|
|
94
|
+
const keptLines = kept.split("\n").length;
|
|
95
|
+
return `${kept}${truncationNote(totalLines - keptLines, false)}`;
|
|
96
|
+
}
|
|
97
|
+
// Water-filling split: small diffs keep everything, large ones share what is left evenly.
|
|
98
|
+
function allocateBudgets(lengths, budget) {
|
|
99
|
+
const order = lengths
|
|
100
|
+
.map((length, index) => ({ length, index }))
|
|
101
|
+
.sort((a, b) => a.length - b.length);
|
|
102
|
+
const budgets = new Array(lengths.length).fill(0);
|
|
103
|
+
let remaining = budget;
|
|
104
|
+
order.forEach(({ length, index }, position) => {
|
|
105
|
+
const share = Math.floor(remaining / (order.length - position));
|
|
106
|
+
budgets[index] = Math.min(length, share);
|
|
107
|
+
remaining -= budgets[index];
|
|
108
|
+
});
|
|
109
|
+
return budgets;
|
|
110
|
+
}
|
|
111
|
+
export function buildUserPrompt(files, maxDiffChars) {
|
|
112
|
+
const diffs = files.map((f) => (f.diffLines ?? []).join("\n"));
|
|
113
|
+
const budgets = allocateBudgets(diffs.map((d) => d.length), maxDiffChars);
|
|
114
|
+
const sections = files.map((file, i) => {
|
|
115
|
+
const header = `### ${file.action} ${file.path}`;
|
|
116
|
+
if (!diffs[i])
|
|
117
|
+
return `${header}\n(no text diff)`;
|
|
118
|
+
return `${header}\n${truncateDiff(diffs[i], budgets[i])}`;
|
|
119
|
+
});
|
|
120
|
+
return `Changed files:\n\n${sections.join("\n\n")}`;
|
|
121
|
+
}
|
|
122
|
+
export class AiChangeDescriber {
|
|
123
|
+
clientFactory;
|
|
124
|
+
log;
|
|
125
|
+
cache = new Map();
|
|
126
|
+
constructor(clientFactory, log) {
|
|
127
|
+
this.clientFactory = clientFactory;
|
|
128
|
+
this.log = log;
|
|
129
|
+
}
|
|
130
|
+
async describe(input) {
|
|
131
|
+
const { options } = input;
|
|
132
|
+
const system = options.prompt
|
|
133
|
+
? `${SYSTEM_PROMPT}\n\n${options.prompt}`
|
|
134
|
+
: SYSTEM_PROMPT;
|
|
135
|
+
const user = buildUserPrompt(input.files, options.maxDiffChars ?? DEFAULT_MAX_DIFF_CHARS);
|
|
136
|
+
const key = createHash("sha256")
|
|
137
|
+
.update(JSON.stringify([
|
|
138
|
+
options.provider,
|
|
139
|
+
options.model,
|
|
140
|
+
options.baseUrl,
|
|
141
|
+
system,
|
|
142
|
+
user,
|
|
143
|
+
]))
|
|
144
|
+
.digest("hex");
|
|
145
|
+
let pending = this.cache.get(key);
|
|
146
|
+
if (pending) {
|
|
147
|
+
this.log.debug("Reusing cached AI commit message");
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
pending = this.generate(input, system, user);
|
|
151
|
+
this.cache.set(key, pending);
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
return await pending;
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
this.cache.delete(key);
|
|
158
|
+
this.log.warn(`AI commit message generation failed, using default message: ${toErrorMessage(error)}`);
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async generate(input, system, user) {
|
|
163
|
+
const client = this.clientFactory(input.options);
|
|
164
|
+
const raw = await withRetry(() => client.complete(system, user, RESPONSE_SCHEMA), {
|
|
165
|
+
retries: input.retries,
|
|
166
|
+
permanentErrorPatterns: AI_PERMANENT_ERROR_PATTERNS,
|
|
167
|
+
});
|
|
168
|
+
return parseDescription(raw);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ValidationError } from "../shared/errors.js";
|
|
2
|
+
import { AnthropicClient, DEFAULT_ANTHROPIC_MODEL, } from "./anthropic-client.js";
|
|
3
|
+
import { DEFAULT_OPENAI_BASE_URL, OpenAICompatibleClient, } from "./openai-compatible-client.js";
|
|
4
|
+
export function createAiClient(options, env, fetch) {
|
|
5
|
+
if (options.provider === "anthropic") {
|
|
6
|
+
const keyEnv = options.apiKeyEnv ?? "ANTHROPIC_API_KEY";
|
|
7
|
+
const apiKey = env[keyEnv];
|
|
8
|
+
if (!apiKey) {
|
|
9
|
+
throw new ValidationError(`${keyEnv} is not set (required for prOptions.ai provider 'anthropic')`);
|
|
10
|
+
}
|
|
11
|
+
return new AnthropicClient({
|
|
12
|
+
apiKey,
|
|
13
|
+
model: options.model ?? DEFAULT_ANTHROPIC_MODEL,
|
|
14
|
+
baseUrl: options.baseUrl,
|
|
15
|
+
fetch,
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
if (!options.model) {
|
|
19
|
+
throw new ValidationError("prOptions.ai.model is required when provider is 'openai'");
|
|
20
|
+
}
|
|
21
|
+
const keyEnv = options.apiKeyEnv ?? "OPENAI_API_KEY";
|
|
22
|
+
const apiKey = env[keyEnv];
|
|
23
|
+
// A custom baseUrl (Ollama, local LiteLLM) often needs no key at all.
|
|
24
|
+
if (!apiKey && !options.baseUrl) {
|
|
25
|
+
throw new ValidationError(`${keyEnv} is not set (required for prOptions.ai provider 'openai' without baseUrl)`);
|
|
26
|
+
}
|
|
27
|
+
return new OpenAICompatibleClient({
|
|
28
|
+
apiKey,
|
|
29
|
+
model: options.model,
|
|
30
|
+
baseUrl: options.baseUrl ?? DEFAULT_OPENAI_BASE_URL,
|
|
31
|
+
fetch,
|
|
32
|
+
});
|
|
33
|
+
}
|
package/dist/ai/http.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { parseApiJson } from "../shared/json-utils.js";
|
|
2
|
+
const REQUEST_TIMEOUT_MS = 60_000;
|
|
3
|
+
const MAX_ERROR_BODY_CHARS = 500;
|
|
4
|
+
export function trimTrailingSlash(url) {
|
|
5
|
+
return url.replace(/\/+$/, "");
|
|
6
|
+
}
|
|
7
|
+
function httpError(label, response, text) {
|
|
8
|
+
const detail = text.slice(0, MAX_ERROR_BODY_CHARS);
|
|
9
|
+
if (response.status !== 429) {
|
|
10
|
+
// Status code in the message lets withRetry classify 5xx as transient.
|
|
11
|
+
return new Error(`${label} ${response.status}: ${detail}`);
|
|
12
|
+
}
|
|
13
|
+
// "rate limit" in the message routes this to withRetry's rate-limit backoff.
|
|
14
|
+
const error = new Error(`${label} 429 (rate limit): ${detail}`);
|
|
15
|
+
const retryAfter = response.headers.get("retry-after");
|
|
16
|
+
if (retryAfter && /^\d+$/.test(retryAfter.trim())) {
|
|
17
|
+
error.retryAfter = parseInt(retryAfter, 10);
|
|
18
|
+
}
|
|
19
|
+
return error;
|
|
20
|
+
}
|
|
21
|
+
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
|
+
});
|
|
28
|
+
const text = await response.text();
|
|
29
|
+
if (!response.ok) {
|
|
30
|
+
throw httpError(label, response, text);
|
|
31
|
+
}
|
|
32
|
+
return parseApiJson(text, `${label} response`);
|
|
33
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type { AiOptions, AiClientFactory, ChangeDescription, DescribeInput, FetchFn, IAiClient, IChangeDescriber, JsonSchema, } from "./types.js";
|
|
2
|
+
export { AnthropicClient, DEFAULT_ANTHROPIC_MODEL, } from "./anthropic-client.js";
|
|
3
|
+
export { OpenAICompatibleClient, DEFAULT_OPENAI_BASE_URL, } from "./openai-compatible-client.js";
|
|
4
|
+
export { createAiClient } from "./client-factory.js";
|
|
5
|
+
export { AiChangeDescriber, DEFAULT_MAX_DIFF_CHARS, isConventionalSubject, } from "./change-describer.js";
|
package/dist/ai/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { AnthropicClient, DEFAULT_ANTHROPIC_MODEL, } from "./anthropic-client.js";
|
|
2
|
+
export { OpenAICompatibleClient, DEFAULT_OPENAI_BASE_URL, } from "./openai-compatible-client.js";
|
|
3
|
+
export { createAiClient } from "./client-factory.js";
|
|
4
|
+
export { AiChangeDescriber, DEFAULT_MAX_DIFF_CHARS, isConventionalSubject, } from "./change-describer.js";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { FetchFn, IAiClient, JsonSchema } from "./types.js";
|
|
2
|
+
export declare const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
|
|
3
|
+
export interface OpenAICompatibleClientOptions {
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
model: string;
|
|
6
|
+
baseUrl: string;
|
|
7
|
+
fetch: FetchFn;
|
|
8
|
+
}
|
|
9
|
+
export declare class OpenAICompatibleClient implements IAiClient {
|
|
10
|
+
readonly baseUrl: string;
|
|
11
|
+
private readonly model;
|
|
12
|
+
private readonly apiKey?;
|
|
13
|
+
private readonly fetch;
|
|
14
|
+
constructor(options: OpenAICompatibleClientOptions);
|
|
15
|
+
complete(system: string, user: string, schema?: JsonSchema): Promise<string>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { postJson, trimTrailingSlash } from "./http.js";
|
|
2
|
+
export const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
|
|
3
|
+
export class OpenAICompatibleClient {
|
|
4
|
+
baseUrl;
|
|
5
|
+
model;
|
|
6
|
+
apiKey;
|
|
7
|
+
fetch;
|
|
8
|
+
constructor(options) {
|
|
9
|
+
this.baseUrl = trimTrailingSlash(options.baseUrl);
|
|
10
|
+
this.model = options.model;
|
|
11
|
+
this.apiKey = options.apiKey;
|
|
12
|
+
this.fetch = options.fetch;
|
|
13
|
+
}
|
|
14
|
+
async complete(system, user, schema) {
|
|
15
|
+
const body = {
|
|
16
|
+
model: this.model,
|
|
17
|
+
messages: [
|
|
18
|
+
{ role: "system", content: system },
|
|
19
|
+
{ role: "user", content: user },
|
|
20
|
+
],
|
|
21
|
+
};
|
|
22
|
+
// json_object (not json_schema) - the widest-supported mode across Ollama, LiteLLM, Azure.
|
|
23
|
+
if (schema) {
|
|
24
|
+
body.response_format = { type: "json_object" };
|
|
25
|
+
}
|
|
26
|
+
const headers = this.apiKey
|
|
27
|
+
? { authorization: `Bearer ${this.apiKey}` }
|
|
28
|
+
: {};
|
|
29
|
+
const response = (await postJson(this.fetch, "OpenAI-compatible API", `${this.baseUrl}/chat/completions`, headers, body));
|
|
30
|
+
const content = response.choices?.[0]?.message?.content;
|
|
31
|
+
if (!content) {
|
|
32
|
+
throw new Error("OpenAI-compatible API returned no content");
|
|
33
|
+
}
|
|
34
|
+
return content;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ResolvedAiConfig } from "../config/index.js";
|
|
2
|
+
import type { FileChangeDetail } from "../sync/types.js";
|
|
3
|
+
export type AiOptions = ResolvedAiConfig;
|
|
4
|
+
export type FetchFn = (url: string, init: RequestInit) => Promise<Response>;
|
|
5
|
+
export type JsonSchema = Record<string, unknown>;
|
|
6
|
+
export interface IAiClient {
|
|
7
|
+
complete(system: string, user: string, schema?: JsonSchema): Promise<string>;
|
|
8
|
+
}
|
|
9
|
+
export type AiClientFactory = (options: AiOptions) => IAiClient;
|
|
10
|
+
export interface DescribeInput {
|
|
11
|
+
files: FileChangeDetail[];
|
|
12
|
+
options: AiOptions;
|
|
13
|
+
retries: number;
|
|
14
|
+
}
|
|
15
|
+
export interface ChangeDescription {
|
|
16
|
+
subject: string;
|
|
17
|
+
body?: string;
|
|
18
|
+
prSummary: string;
|
|
19
|
+
}
|
|
20
|
+
export interface IChangeDescriber {
|
|
21
|
+
describe(input: DescribeInput): Promise<ChangeDescription | null>;
|
|
22
|
+
}
|
package/dist/ai/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/cli/program.d.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { program } from "commander";
|
|
2
2
|
import { MergeMode, MergeStrategy } from "../config/index.js";
|
|
3
|
+
import type { SyncOptions } from "./sync-command.js";
|
|
4
|
+
import { type SecretsSyncOptions } from "./secrets-command.js";
|
|
3
5
|
declare function getVersion(): string;
|
|
4
6
|
export declare function parseMergeMode(value: string): MergeMode;
|
|
5
7
|
export declare function parseMergeStrategy(value: string): MergeStrategy;
|
|
8
|
+
type CommanderOptions = Record<string, unknown> & {
|
|
9
|
+
config: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function toSyncOptions(opts: CommanderOptions): SyncOptions;
|
|
12
|
+
export declare function toSecretsSyncOptions(opts: CommanderOptions): SecretsSyncOptions;
|
|
6
13
|
export { program, getVersion };
|
package/dist/cli/program.js
CHANGED
|
@@ -52,26 +52,34 @@ export function parseMergeStrategy(value) {
|
|
|
52
52
|
}
|
|
53
53
|
return value;
|
|
54
54
|
}
|
|
55
|
+
// Commander stores --no-x as x: false; map to the noX fields the runners expect.
|
|
56
|
+
function withoutNegations(opts) {
|
|
57
|
+
const { delete: del, ai, ...rest } = opts;
|
|
58
|
+
return { ...rest, noDelete: del === false, noAi: ai === false };
|
|
59
|
+
}
|
|
60
|
+
export function toSyncOptions(opts) {
|
|
61
|
+
return withoutNegations(opts);
|
|
62
|
+
}
|
|
63
|
+
export function toSecretsSyncOptions(opts) {
|
|
64
|
+
const { noAi: _noAi, ...options } = withoutNegations(opts);
|
|
65
|
+
return options;
|
|
66
|
+
}
|
|
55
67
|
// =============================================================================
|
|
56
68
|
// CLI Program
|
|
57
69
|
// =============================================================================
|
|
58
70
|
program
|
|
59
71
|
.name("xfg")
|
|
60
72
|
.description("Manage files, settings, and repositories across GitHub, Azure DevOps, and GitLab");
|
|
61
|
-
// Sync command (file synchronization)
|
|
62
73
|
const syncCommand = new Command("sync")
|
|
63
74
|
.description("Sync configuration files across repositories")
|
|
64
75
|
.option("-b, --branch <name>", "Override the branch name (default: chore/sync-{filename} or chore/sync-config)")
|
|
65
76
|
.option("-m, --merge <mode>", "PR merge mode: manual, auto (default, merge when checks pass), force (bypass requirements), direct (push to default branch, no PR)", parseMergeMode)
|
|
66
77
|
.option("--merge-strategy <strategy>", "Merge strategy: merge, squash (default), rebase", parseMergeStrategy)
|
|
67
78
|
.option("--delete-branch", "Delete source branch after merge")
|
|
79
|
+
.option("--no-ai", "Disable AI-generated commit messages and PR descriptions even if prOptions.ai is configured")
|
|
68
80
|
.action(async (opts) => {
|
|
69
81
|
try {
|
|
70
|
-
|
|
71
|
-
...opts,
|
|
72
|
-
noDelete: opts.delete === false,
|
|
73
|
-
};
|
|
74
|
-
await runSync(options);
|
|
82
|
+
await runSync(toSyncOptions(opts));
|
|
75
83
|
}
|
|
76
84
|
catch (error) {
|
|
77
85
|
console.error("Fatal error:", error);
|
|
@@ -95,11 +103,7 @@ const secretsSyncCommand = new Command("sync")
|
|
|
95
103
|
}, 3)
|
|
96
104
|
.action(async (opts) => {
|
|
97
105
|
try {
|
|
98
|
-
|
|
99
|
-
...opts,
|
|
100
|
-
noDelete: opts.delete === false,
|
|
101
|
-
};
|
|
102
|
-
await runSecretsSync(options);
|
|
106
|
+
await runSecretsSync(toSecretsSyncOptions(opts));
|
|
103
107
|
}
|
|
104
108
|
catch (error) {
|
|
105
109
|
console.error("Fatal error:", error);
|
|
@@ -66,6 +66,7 @@ async function runFileSyncPhase(repo, ctx) {
|
|
|
66
66
|
executor: ctx.executor,
|
|
67
67
|
prTemplate: ctx.config.prTemplate,
|
|
68
68
|
noDelete: ctx.options.noDelete,
|
|
69
|
+
noAi: ctx.options.noAi,
|
|
69
70
|
token: repo.token,
|
|
70
71
|
hasAppCredentials: isGitHubRepo(repo.repoInfo) && ctx.tokenManager !== null,
|
|
71
72
|
});
|
|
@@ -120,6 +120,7 @@ export async function runSecretsSync(options, deps = {}) {
|
|
|
120
120
|
settings: buildSettingsReport(reportResults),
|
|
121
121
|
dryRun: dryRun ?? false,
|
|
122
122
|
summaryPath: process.env.GITHUB_STEP_SUMMARY,
|
|
123
|
+
log: logger,
|
|
123
124
|
});
|
|
124
125
|
if (hasErrors) {
|
|
125
126
|
throw new Error("One or more repositories failed secrets sync.");
|
package/dist/cli/sync-command.js
CHANGED
|
@@ -48,6 +48,7 @@ function displayReports(logger, reportResults, lifecycleReportInputs, settingsCo
|
|
|
48
48
|
settings: settingsReport,
|
|
49
49
|
dryRun,
|
|
50
50
|
summaryPath: process.env.GITHUB_STEP_SUMMARY,
|
|
51
|
+
log: logger,
|
|
51
52
|
});
|
|
52
53
|
}
|
|
53
54
|
export async function runSync(options, deps = {}) {
|
|
@@ -86,6 +87,7 @@ export async function runSync(options, deps = {}) {
|
|
|
86
87
|
: new RepositoryProcessor(undefined, logger, {
|
|
87
88
|
tokenManager,
|
|
88
89
|
envToken: process.env.GH_TOKEN,
|
|
90
|
+
aiEnv: process.env,
|
|
89
91
|
});
|
|
90
92
|
const ctx = {
|
|
91
93
|
config,
|
package/dist/cli/types.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { type LifecycleReport, type SyncReport, type SettingsReport } from "../output/index.js";
|
|
2
|
+
import type { DebugLog } from "../shared/logger.js";
|
|
2
3
|
interface UnifiedSummaryInput {
|
|
3
4
|
lifecycle?: LifecycleReport;
|
|
4
5
|
sync?: SyncReport;
|
|
5
6
|
settings?: SettingsReport;
|
|
6
7
|
dryRun: boolean;
|
|
7
8
|
summaryPath?: string | undefined;
|
|
9
|
+
log?: DebugLog;
|
|
8
10
|
}
|
|
9
|
-
export declare function formatUnifiedSummaryMarkdown(input: UnifiedSummaryInput): string;
|
|
11
|
+
export declare function formatUnifiedSummaryMarkdown(input: UnifiedSummaryInput, maxBytes?: number): string;
|
|
10
12
|
export declare function writeUnifiedSummary(input: UnifiedSummaryInput): void;
|
|
11
13
|
export {};
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { STEP_SUMMARY_MAX_BYTES } from "../output/github-summary.js";
|
|
2
|
+
import { fitSummary, summaryHeader, } from "../output/summary-budget.js";
|
|
1
3
|
import { hasLifecycleChanges, writeGitHubStepSummary, renderSyncLines, renderRepoSettingsDiffLines, formatCountEntry, formatSettingsCountEntries, hasRepoSettingsChanges, } from "../output/index.js";
|
|
2
4
|
import { formatActionCountEntry } from "../shared/count-format.js";
|
|
5
|
+
import { quoted } from "../shared/string-utils.js";
|
|
3
6
|
function selectLabel(dry, pastLabel, futureLabel) {
|
|
4
7
|
return dry ? futureLabel : pastLabel;
|
|
5
8
|
}
|
|
@@ -61,23 +64,14 @@ function renderLifecycleLines(lcAction, diffLines) {
|
|
|
61
64
|
diffLines.push(`+ visibility: ${lcAction.settings.visibility}`);
|
|
62
65
|
}
|
|
63
66
|
if (lcAction.settings.description) {
|
|
64
|
-
diffLines.push(`+ description:
|
|
67
|
+
diffLines.push(`+ description: ${quoted(lcAction.settings.description)}`);
|
|
65
68
|
}
|
|
66
69
|
}
|
|
67
70
|
}
|
|
68
|
-
export function formatUnifiedSummaryMarkdown(input) {
|
|
71
|
+
export function formatUnifiedSummaryMarkdown(input, maxBytes = STEP_SUMMARY_MAX_BYTES) {
|
|
69
72
|
if (!hasAnyChanges(input)) {
|
|
70
73
|
return "";
|
|
71
74
|
}
|
|
72
|
-
const lines = [];
|
|
73
|
-
const title = input.dryRun ? "## xfg Plan" : "## xfg Apply";
|
|
74
|
-
lines.push(title);
|
|
75
|
-
lines.push("");
|
|
76
|
-
if (input.dryRun) {
|
|
77
|
-
lines.push("> [!WARNING]");
|
|
78
|
-
lines.push("> This was a dry run — no changes were applied");
|
|
79
|
-
lines.push("");
|
|
80
|
-
}
|
|
81
75
|
const lifecycleByRepo = new Map((input.lifecycle?.actions ?? []).map((a) => [a.repoName, a]));
|
|
82
76
|
const syncByRepo = new Map((input.sync?.repos ?? []).map((r) => [r.repoName, r]));
|
|
83
77
|
// The same repo can appear more than once (e.g. listed twice in config); keep every entry.
|
|
@@ -99,6 +93,7 @@ export function formatUnifiedSummaryMarkdown(input) {
|
|
|
99
93
|
addRepo(r.repoName);
|
|
100
94
|
for (const r of input.settings?.repos ?? [])
|
|
101
95
|
addRepo(r.repoName);
|
|
96
|
+
const blocks = [];
|
|
102
97
|
for (const repoName of allRepos) {
|
|
103
98
|
const lcAction = lifecycleByRepo.get(repoName);
|
|
104
99
|
const syncRepo = syncByRepo.get(repoName);
|
|
@@ -108,15 +103,13 @@ export function formatUnifiedSummaryMarkdown(input) {
|
|
|
108
103
|
const repoHasSettingsChanges = settingsRepos.length > 0;
|
|
109
104
|
if (!hasLcChange && !hasSyncChanges && !repoHasSettingsChanges)
|
|
110
105
|
continue;
|
|
111
|
-
lines.push(`### ${repoName}`);
|
|
112
|
-
lines.push("");
|
|
113
106
|
const diffLines = [];
|
|
114
107
|
if (lcAction)
|
|
115
108
|
renderLifecycleLines(lcAction, diffLines);
|
|
116
109
|
if (hasLcChange && hasSyncChanges)
|
|
117
110
|
diffLines.push("");
|
|
118
111
|
if (syncRepo)
|
|
119
|
-
|
|
112
|
+
renderSyncLines(syncRepo, diffLines);
|
|
120
113
|
if (hasSyncChanges && repoHasSettingsChanges)
|
|
121
114
|
diffLines.push("");
|
|
122
115
|
settingsRepos.forEach((settingsRepo, i) => {
|
|
@@ -124,19 +117,14 @@ export function formatUnifiedSummaryMarkdown(input) {
|
|
|
124
117
|
diffLines.push("");
|
|
125
118
|
renderRepoSettingsDiffLines(settingsRepo, diffLines);
|
|
126
119
|
});
|
|
127
|
-
|
|
128
|
-
lines.push("```diff");
|
|
129
|
-
lines.push(...diffLines);
|
|
130
|
-
lines.push("```");
|
|
131
|
-
lines.push("");
|
|
132
|
-
}
|
|
120
|
+
blocks.push({ heading: `### ${repoName}`, diffLines, repos: [repoName] });
|
|
133
121
|
}
|
|
134
|
-
|
|
135
|
-
|
|
122
|
+
return fitSummary({
|
|
123
|
+
header: summaryHeader(input.dryRun),
|
|
124
|
+
blocks,
|
|
125
|
+
footer: `**${formatCombinedSummary(input)}**`,
|
|
126
|
+
}, maxBytes);
|
|
136
127
|
}
|
|
137
128
|
export function writeUnifiedSummary(input) {
|
|
138
|
-
|
|
139
|
-
if (!markdown)
|
|
140
|
-
return;
|
|
141
|
-
writeGitHubStepSummary(markdown, input.summaryPath);
|
|
129
|
+
writeGitHubStepSummary((maxBytes) => formatUnifiedSummaryMarkdown(input, maxBytes), input.summaryPath, input.log);
|
|
142
130
|
}
|
package/dist/config/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { PRMergeOptions, MergeMode, MergeStrategy, BypassActor, BypassMode, StatusCheckConfig, CodeScanningTool, PullRequestRuleParameters, RulesetRule, Ruleset, GitHubRepoSettings, RepoVisibility, SquashMergeCommitTitle, SquashMergeCommitMessage, MergeCommitTitle, MergeCommitMessage, Label, CodeScanningSettings, CodeScanningState, CodeScanningQuerySuite, CodeScanningLanguage, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, SecretsConfig, RawRootSettings, RawRepoSettings, RawRepoConfig, RawConfig, RawConditionalGroupWhen, RawConditionalGroupConfig, RepoConfig, Config, FileContent, ContentValue, } from "./types.js";
|
|
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, RepoSettings, RawFileConfig, RawRepoFileOverride, RawGroupConfig, SecretConfig, 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";
|
package/dist/config/index.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
// Re-export values (non-type exports)
|
|
2
1
|
export { RULESET_COMPARABLE_FIELDS } from "./types.js";
|
|
3
|
-
// Re-export loading functions
|
|
4
2
|
export { loadRawConfig, loadConfig, normalizeConfig } from "./loader.js";
|
|
5
3
|
// Config formatting
|
|
6
4
|
export { convertContentToString } from "./formatter.js";
|