@kud/ai-conventional-commit-cli 2.0.1 → 2.0.3

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.
@@ -0,0 +1,120 @@
1
+ // src/config.ts
2
+ import { cosmiconfig } from "cosmiconfig";
3
+ import { resolve, dirname, join } from "path";
4
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
5
+ import { homedir } from "os";
6
+ var DEFAULTS = {
7
+ model: process.env.AICC_MODEL || "github-copilot/gpt-4.1",
8
+ privacy: process.env.AICC_PRIVACY || "low",
9
+ style: process.env.AICC_STYLE || "standard",
10
+ styleSamples: parseInt(process.env.AICC_STYLE_SAMPLES || "120", 10),
11
+ maxTokens: parseInt(process.env.AICC_MAX_TOKENS || "512", 10),
12
+ maxFileLines: parseInt(process.env.AICC_MAX_FILE_LINES || "1000", 10),
13
+ skipFilePatterns: [
14
+ "**/package-lock.json",
15
+ "**/yarn.lock",
16
+ "**/pnpm-lock.yaml",
17
+ "**/bun.lockb",
18
+ "**/composer.lock",
19
+ "**/Gemfile.lock",
20
+ "**/Cargo.lock",
21
+ "**/poetry.lock",
22
+ "**/*.d.ts",
23
+ "**/dist/**",
24
+ "**/build/**",
25
+ "**/.next/**",
26
+ "**/out/**",
27
+ "**/coverage/**",
28
+ "**/*.min.js",
29
+ "**/*.min.css",
30
+ "**/*.map"
31
+ ],
32
+ cacheDir: ".git/.aicc-cache",
33
+ plugins: [],
34
+ verbose: process.env.AICC_VERBOSE === "true"
35
+ };
36
+ function getGlobalConfigPath() {
37
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
38
+ return resolve(base, "ai-conventional-commit-cli", "aicc.json");
39
+ }
40
+ function saveGlobalConfig(partial) {
41
+ const filePath = getGlobalConfigPath();
42
+ const dir = dirname(filePath);
43
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
44
+ let existing = {};
45
+ if (existsSync(filePath)) {
46
+ try {
47
+ existing = JSON.parse(readFileSync(filePath, "utf8")) || {};
48
+ } catch (e) {
49
+ if (process.env.AICC_VERBOSE === "true") {
50
+ console.error("[ai-cc] Failed to parse existing global config, overwriting.");
51
+ }
52
+ }
53
+ }
54
+ const merged = { ...existing, ...partial };
55
+ writeFileSync(filePath, JSON.stringify(merged, null, 2) + "\n", "utf8");
56
+ return filePath;
57
+ }
58
+ async function loadConfig(cwd = process.cwd()) {
59
+ return (await loadConfigDetailed(cwd)).config;
60
+ }
61
+ async function loadConfigDetailed(cwd = process.cwd()) {
62
+ let globalCfg = {};
63
+ const globalPath = getGlobalConfigPath();
64
+ if (existsSync(globalPath)) {
65
+ try {
66
+ globalCfg = JSON.parse(readFileSync(globalPath, "utf8")) || {};
67
+ } catch (e) {
68
+ if (process.env.AICC_VERBOSE === "true") {
69
+ console.error("[ai-cc] Failed to parse global config, ignoring.");
70
+ }
71
+ }
72
+ }
73
+ const explorer = cosmiconfig("aicc");
74
+ const result = await explorer.search(cwd);
75
+ const projectCfg = result?.config || {};
76
+ const envCfg = {};
77
+ if (process.env.AICC_MODEL) envCfg.model = process.env.AICC_MODEL;
78
+ if (process.env.AICC_PRIVACY) envCfg.privacy = process.env.AICC_PRIVACY;
79
+ if (process.env.AICC_STYLE) envCfg.style = process.env.AICC_STYLE;
80
+ if (process.env.AICC_STYLE_SAMPLES)
81
+ envCfg.styleSamples = parseInt(process.env.AICC_STYLE_SAMPLES, 10);
82
+ if (process.env.AICC_MAX_TOKENS) envCfg.maxTokens = parseInt(process.env.AICC_MAX_TOKENS, 10);
83
+ if (process.env.AICC_MAX_FILE_LINES)
84
+ envCfg.maxFileLines = parseInt(process.env.AICC_MAX_FILE_LINES, 10);
85
+ if (process.env.AICC_VERBOSE) envCfg.verbose = process.env.AICC_VERBOSE === "true";
86
+ const merged = {
87
+ ...DEFAULTS,
88
+ ...globalCfg,
89
+ ...projectCfg,
90
+ ...envCfg
91
+ };
92
+ merged.plugins = (merged.plugins || []).filter((p) => {
93
+ const abs = resolve(cwd, p);
94
+ return existsSync(abs);
95
+ });
96
+ if (!merged.skipFilePatterns) {
97
+ merged.skipFilePatterns = DEFAULTS.skipFilePatterns;
98
+ }
99
+ const sources = Object.keys(merged).reduce((acc, key) => {
100
+ const k = key;
101
+ let src = "default";
102
+ if (k in globalCfg) src = "global";
103
+ if (k in projectCfg) src = "project";
104
+ if (k in envCfg) src = "env";
105
+ acc[k] = src;
106
+ return acc;
107
+ }, {});
108
+ const withMeta = Object.assign(merged, { _sources: sources });
109
+ return {
110
+ config: withMeta,
111
+ raw: { defaults: DEFAULTS, global: globalCfg, project: projectCfg, env: envCfg }
112
+ };
113
+ }
114
+
115
+ export {
116
+ getGlobalConfigPath,
117
+ saveGlobalConfig,
118
+ loadConfig,
119
+ loadConfigDetailed
120
+ };
@@ -171,7 +171,18 @@ Refine now.`
171
171
 
172
172
  // src/model/provider.ts
173
173
  import { z } from "zod";
174
+ import { createServer } from "net";
174
175
  import { createOpencode } from "@opencode-ai/sdk";
176
+ function findFreePort() {
177
+ return new Promise((resolve, reject) => {
178
+ const server = createServer();
179
+ server.on("error", reject);
180
+ server.listen(0, "127.0.0.1", () => {
181
+ const port = server.address().port;
182
+ server.close(() => resolve(port));
183
+ });
184
+ });
185
+ }
175
186
  var OpenCodeProvider = class {
176
187
  constructor(model = "github-copilot/gpt-4.1") {
177
188
  this.model = model;
@@ -210,11 +221,16 @@ ${userAggregate}`;
210
221
  const start = Date.now();
211
222
  let server;
212
223
  try {
213
- const opencode = await createOpencode({ signal: ac.signal });
224
+ if (debug) console.error("[ai-cc][provider] starting opencode server");
225
+ const port = await findFreePort();
226
+ const opencode = await createOpencode({ signal: ac.signal, port });
214
227
  server = opencode.server;
215
- const { client } = opencode;
228
+ const client = opencode.client;
216
229
  const session = await client.session.create({ body: { title: "aicc" } });
217
- if (!session.data) throw new Error("Failed to create opencode session");
230
+ if (!session.data) {
231
+ const errMsg = session.error?.message ?? JSON.stringify(session.error) ?? "unknown";
232
+ throw new Error(`Failed to create opencode session: ${errMsg}`);
233
+ }
218
234
  const result = await client.session.prompt({
219
235
  path: { id: session.data.id },
220
236
  body: {
@@ -0,0 +1,545 @@
1
+ // src/prompt.ts
2
+ var summarizeDiffForPrompt = (files, privacy) => {
3
+ if (privacy === "high") {
4
+ return files.map((f) => `file: ${f.file} (+${f.additions} -${f.deletions}) hunks:${f.hunks.length}`).join("\n");
5
+ }
6
+ if (privacy === "medium") {
7
+ return files.map(
8
+ (f) => `file: ${f.file}
9
+ ` + f.hunks.map(
10
+ (h) => ` hunk ${h.hash} context:${h.functionContext || ""} +${h.added} -${h.removed}`
11
+ ).join("\n")
12
+ ).join("\n");
13
+ }
14
+ return files.map(
15
+ (f) => `file: ${f.file}
16
+ ` + f.hunks.map(
17
+ (h) => `${h.header}
18
+ ${h.lines.slice(0, 40).join("\n")}${h.lines.length > 40 ? "\n[truncated]" : ""}`
19
+ ).join("\n")
20
+ ).join("\n");
21
+ };
22
+ var buildGenerationMessages = (opts) => {
23
+ const { files, style, config, mode, desiredCommits } = opts;
24
+ const diff = summarizeDiffForPrompt(files, config.privacy);
25
+ const TYPE_MAP = {
26
+ feat: "A new feature or capability added for the user",
27
+ fix: "A bug fix resolving incorrect behavior",
28
+ chore: "Internal change with no user-facing impact",
29
+ docs: "Documentation-only changes",
30
+ refactor: "Code change that neither fixes a bug nor adds a feature",
31
+ test: "Adding or improving tests only",
32
+ ci: "Changes to CI configuration or scripts",
33
+ perf: "Performance improvement",
34
+ style: "Formatting or stylistic change (no logic)",
35
+ build: "Build system or dependency changes",
36
+ revert: "Revert a previous commit",
37
+ merge: "Merge branches (rare; only if truly a merge commit)",
38
+ security: "Security-related change or hardening",
39
+ release: "Version bump or release meta change"
40
+ };
41
+ const specLines = [];
42
+ specLines.push(
43
+ "Purpose: Generate high-quality Conventional Commit messages for the provided git diff."
44
+ );
45
+ specLines.push("Locale: en");
46
+ specLines.push(
47
+ 'Output JSON Schema: { "commits": [ { "title": string, "body": string, "score": 0-100, "reasons": string[], "files"?: string[] } ], "meta": { "splitRecommended": boolean } }'
48
+ );
49
+ specLines.push("Primary Output Field: commits[ ].title");
50
+ specLines.push("Title Format: <type>(<optional-scope>): <subject>");
51
+ specLines.push(
52
+ "Title Length Guidance: Aim for <=50 chars ideal; absolute max 72 (do not exceed)."
53
+ );
54
+ specLines.push("Types (JSON mapping follows on next line)");
55
+ specLines.push("TypeMap: " + JSON.stringify(TYPE_MAP));
56
+ specLines.push("Scope Rules: optional; if present, lowercase kebab-case; omit when unclear.");
57
+ specLines.push(
58
+ "Subject Rules: imperative mood, present tense, no leading capital unless proper noun, no trailing period."
59
+ );
60
+ specLines.push(
61
+ "Length Rule: Keep titles concise; prefer 50 or fewer chars; MUST be <=72 including type/scope."
62
+ );
63
+ specLines.push(
64
+ "Emoji Rule: " + (config.style === "gitmoji" || config.style === "gitmoji-pure" ? "OPTIONAL single leading gitmoji BEFORE the type only if confidently adds clarity; do not invent or stack; omit if unsure." : "Disallow all emojis and gitmoji codes; output must start directly with the type.")
65
+ );
66
+ specLines.push(
67
+ "Forbidden: breaking changes notation, exclamation mark after type unless truly semver-major (avoid unless diff clearly indicates)."
68
+ );
69
+ specLines.push("Fallback Type: use chore when no other type clearly fits.");
70
+ specLines.push("Consistency: prefer existing top prefixes: " + style.topPrefixes.join(", "));
71
+ specLines.push("Provide score (0-100) measuring clarity & specificity (higher is better).");
72
+ specLines.push(
73
+ "Provide reasons array citing concrete diff elements: filenames, functions, tests, metrics."
74
+ );
75
+ specLines.push(
76
+ 'When mode is split, WHERE POSSIBLE add a "files" array per commit listing the most relevant changed file paths (1-6, minimize overlap across commits).'
77
+ );
78
+ specLines.push("Return ONLY the JSON object. No surrounding text or markdown.");
79
+ specLines.push("Do not add fields not listed in schema.");
80
+ specLines.push("Never fabricate content not present or implied by the diff.");
81
+ specLines.push(
82
+ "If mode is split and multiple logical changes exist, set meta.splitRecommended=true."
83
+ );
84
+ return [
85
+ {
86
+ role: "system",
87
+ content: specLines.join("\n")
88
+ },
89
+ {
90
+ role: "user",
91
+ content: `Mode: ${mode}
92
+ RequestedCommitCount: ${desiredCommits || (mode === "split" ? "2-6" : 1)}
93
+ StyleFingerprint: ${JSON.stringify(style)}
94
+ Diff:
95
+ ${diff}
96
+ Generate commit candidates now.`
97
+ }
98
+ ];
99
+ };
100
+ var buildRefineMessages = (opts) => {
101
+ const { originalPlan, index, instructions, config } = opts;
102
+ const target = originalPlan.commits[index];
103
+ const spec = [];
104
+ spec.push("Purpose: Refine a single Conventional Commit message while preserving intent.");
105
+ spec.push("Locale: en");
106
+ spec.push("Input: one existing commit JSON object.");
107
+ spec.push(
108
+ 'Output JSON Schema: { "commits": [ { "title": string, "body": string, "score": 0-100, "reasons": string[] } ] }'
109
+ );
110
+ spec.push("Title Format: <type>(<optional-scope>): <subject> (<=72 chars)");
111
+ spec.push("Subject: imperative, present tense, no trailing period.");
112
+ spec.push(
113
+ "Emoji Rule: " + (config.style === "gitmoji" || config.style === "gitmoji-pure" ? "OPTIONAL single leading gitmoji BEFORE type if it adds clarity; omit if unsure." : "Disallow all emojis; start directly with the type.")
114
+ );
115
+ spec.push("Preserve semantic meaning; only improve clarity, scope, brevity, conformity.");
116
+ spec.push("If instructions request scope or emoji, incorporate only if justified by content.");
117
+ spec.push("Return ONLY JSON (commits array length=1).");
118
+ return [
119
+ { role: "system", content: spec.join("\n") },
120
+ {
121
+ role: "user",
122
+ content: `Current commit object:
123
+ ${JSON.stringify(target, null, 2)}
124
+ Instructions:
125
+ ${instructions.join("\n") || "None"}
126
+ Refine now.`
127
+ }
128
+ ];
129
+ };
130
+
131
+ // src/model/provider.ts
132
+ import { z } from "zod";
133
+ import { execa } from "execa";
134
+ var OpenCodeProvider = class {
135
+ constructor(model = "github-copilot/gpt-4.1") {
136
+ this.model = model;
137
+ }
138
+ name() {
139
+ return "opencode";
140
+ }
141
+ async chat(messages, _opts) {
142
+ const debug = process.env.AICC_DEBUG === "true";
143
+ const mockMode = process.env.AICC_DEBUG_PROVIDER === "mock";
144
+ const timeoutMs = parseInt(process.env.AICC_MODEL_TIMEOUT_MS || "120000", 10);
145
+ const eager = process.env.AICC_EAGER_PARSE !== "false";
146
+ const userAggregate = messages.map((m) => `${m.role.toUpperCase()}: ${m.content}`).join("\n\n");
147
+ const command = `Generate high-quality commit message candidates based on the staged git diff.`;
148
+ const fullPrompt = `${command}
149
+
150
+ Context:
151
+ ${userAggregate}`;
152
+ if (mockMode) {
153
+ if (debug) console.error("[ai-cc][mock] Returning deterministic mock response");
154
+ return JSON.stringify({
155
+ commits: [
156
+ {
157
+ title: "chore: mock commit from provider",
158
+ body: "",
159
+ score: 80,
160
+ reasons: ["mock mode"]
161
+ }
162
+ ],
163
+ meta: { splitRecommended: false }
164
+ });
165
+ }
166
+ const start = Date.now();
167
+ return await new Promise((resolve, reject) => {
168
+ let resolved = false;
169
+ let acc = "";
170
+ const includeLogs = process.env.AICC_PRINT_LOGS === "true";
171
+ const args = ["run", fullPrompt, "--model", this.model];
172
+ if (includeLogs) args.push("--print-logs");
173
+ const subprocess = execa("opencode", args, {
174
+ timeout: timeoutMs,
175
+ input: ""
176
+ // immediately close stdin in case CLI waits for it
177
+ });
178
+ const finish = (value) => {
179
+ if (resolved) return;
180
+ resolved = true;
181
+ const elapsed = Date.now() - start;
182
+ if (debug) {
183
+ console.error(
184
+ `[ai-cc][provider] model=${this.model} elapsedMs=${elapsed} promptChars=${fullPrompt.length} bytesOut=${value.length}`
185
+ );
186
+ }
187
+ resolve(value);
188
+ };
189
+ const tryEager = () => {
190
+ if (!eager) return;
191
+ const first = acc.indexOf("{");
192
+ const last = acc.lastIndexOf("}");
193
+ if (first !== -1 && last !== -1 && last > first) {
194
+ const candidate = acc.slice(first, last + 1).trim();
195
+ try {
196
+ JSON.parse(candidate);
197
+ if (debug) console.error("[ai-cc][provider] eager JSON detected, terminating process");
198
+ subprocess.kill("SIGTERM");
199
+ finish(candidate);
200
+ } catch {
201
+ }
202
+ }
203
+ };
204
+ subprocess.stdout?.on("data", (chunk) => {
205
+ const text = chunk.toString();
206
+ acc += text;
207
+ tryEager();
208
+ });
209
+ subprocess.stderr?.on("data", (chunk) => {
210
+ if (debug) console.error("[ai-cc][provider][stderr]", chunk.toString().trim());
211
+ });
212
+ subprocess.then(({ stdout }) => {
213
+ if (!resolved) finish(stdout);
214
+ }).catch((e) => {
215
+ if (resolved) return;
216
+ const elapsed = Date.now() - start;
217
+ if (e.timedOut) {
218
+ return reject(
219
+ new Error(`Model call timed out after ${timeoutMs}ms (elapsed=${elapsed}ms)`)
220
+ );
221
+ }
222
+ if (debug) console.error("[ai-cc][provider] failure", e.stderr || e.message);
223
+ reject(new Error(e.stderr || e.message || "opencode invocation failed"));
224
+ });
225
+ });
226
+ }
227
+ };
228
+ var CommitSchema = z.object({
229
+ title: z.string().min(5).max(150),
230
+ body: z.string().optional().default(""),
231
+ score: z.number().min(0).max(100),
232
+ reasons: z.array(z.string()).optional().default([]),
233
+ files: z.array(z.string()).optional().default([])
234
+ });
235
+ var PlanSchema = z.object({
236
+ commits: z.array(CommitSchema).min(1),
237
+ meta: z.object({
238
+ splitRecommended: z.boolean().optional()
239
+ }).optional()
240
+ });
241
+ var extractJSON = (raw) => {
242
+ const trimmed = raw.trim();
243
+ let jsonText = null;
244
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
245
+ jsonText = trimmed;
246
+ } else {
247
+ const match = raw.match(/\{[\s\S]*\}$/m);
248
+ if (match) jsonText = match[0];
249
+ }
250
+ if (!jsonText) throw new Error("No JSON object detected.");
251
+ let parsed;
252
+ try {
253
+ parsed = JSON.parse(jsonText);
254
+ } catch (e) {
255
+ throw new Error("Invalid JSON parse");
256
+ }
257
+ return PlanSchema.parse(parsed);
258
+ };
259
+
260
+ // src/guardrails.ts
261
+ var SECRET_PATTERNS = [
262
+ /AWS_[A-Z0-9_]+/i,
263
+ /BEGIN RSA PRIVATE KEY/,
264
+ /-----BEGIN PRIVATE KEY-----/,
265
+ /ssh-rsa AAAA/
266
+ ];
267
+ var CONVENTIONAL_RE = /^(?:([\p{Emoji}\p{So}\p{Sk}]+)\s+(feat|fix|chore|docs|refactor|test|ci|perf|style|build|revert|merge|security|release)(\(.+\))?:\s|([\p{Emoji}\p{So}\p{Sk}]+):\s.*|([\p{Emoji}\p{So}\p{Sk}]+):\s*$|(feat|fix|chore|docs|refactor|test|ci|perf|style|build|revert|merge|security|release)(\(.+\))?:\s)/u;
268
+ var sanitizeTitle = (title, allowEmoji) => {
269
+ let t = title.trim();
270
+ if (allowEmoji) {
271
+ const multi = t.match(/^((?:[\p{Emoji}\p{So}\p{Sk}]+)[\p{Emoji}\p{So}\p{Sk}\s]*)+/u);
272
+ if (multi) {
273
+ const first = Array.from(multi[0].trim())[0];
274
+ t = first + " " + t.slice(multi[0].length).trimStart();
275
+ }
276
+ } else {
277
+ t = t.replace(/^([\p{Emoji}\p{So}\p{Sk}\p{P}]+\s*)+/u, "").trimStart();
278
+ }
279
+ return t;
280
+ };
281
+ var normalizeConventionalTitle = (title) => {
282
+ let original = title.trim();
283
+ let leadingEmoji = "";
284
+ const emojiCluster = original.match(/^[\p{Emoji}\p{So}\p{Sk}]+/u);
285
+ if (emojiCluster) {
286
+ leadingEmoji = Array.from(emojiCluster[0])[0];
287
+ }
288
+ let t = original.replace(/^([\p{Emoji}\p{So}\p{Sk}\p{P}]+\s*)+/u, "").trim();
289
+ const m = t.match(/^(\w+)(\(.+\))?:\s+(.*)$/);
290
+ let result;
291
+ if (m) {
292
+ const type = m[1].toLowerCase();
293
+ const scope = m[2] || "";
294
+ let subject = m[3].trim();
295
+ subject = subject.replace(/\.$/, "");
296
+ subject = subject.charAt(0).toLowerCase() + subject.slice(1);
297
+ result = `${type}${scope}: ${subject}`;
298
+ } else if (!/^\w+\(.+\)?: /.test(t)) {
299
+ t = t.replace(/\.$/, "");
300
+ t = t.charAt(0).toLowerCase() + t.slice(1);
301
+ result = `chore: ${t}`;
302
+ } else {
303
+ result = t;
304
+ }
305
+ if (leadingEmoji) {
306
+ result = `${leadingEmoji} ${result}`;
307
+ }
308
+ return result;
309
+ };
310
+ var checkCandidate = (candidate) => {
311
+ const errs = [];
312
+ if (!CONVENTIONAL_RE.test(candidate.title)) {
313
+ errs.push("Not a valid conventional commit title.");
314
+ }
315
+ if (/^[A-Z]/.test(candidate.title)) {
316
+ }
317
+ const body = candidate.body || "";
318
+ for (const pat of SECRET_PATTERNS) {
319
+ if (pat.test(body)) {
320
+ errs.push("Potential secret detected.");
321
+ break;
322
+ }
323
+ }
324
+ return errs;
325
+ };
326
+
327
+ // src/title-format.ts
328
+ var EMOJI_MAP = {
329
+ feat: "\u2728",
330
+ fix: "\u{1F41B}",
331
+ chore: "\u{1F9F9}",
332
+ docs: "\u{1F4DD}",
333
+ refactor: "\u267B\uFE0F",
334
+ test: "\u2705",
335
+ ci: "\u{1F916}",
336
+ perf: "\u26A1\uFE0F",
337
+ style: "\u{1F3A8}",
338
+ build: "\u{1F3D7}\uFE0F",
339
+ revert: "\u23EA",
340
+ merge: "\u{1F500}",
341
+ security: "\u{1F512}",
342
+ release: "\u{1F3F7}\uFE0F"
343
+ };
344
+ var EMOJI_TYPE_RE = /^([\p{Emoji}\p{So}\p{Sk}])\s+(\w+)(\(.+\))?:\s+(.*)$/u;
345
+ var TYPE_RE = /^(\w+)(\(.+\))?:\s+(.*)$/;
346
+ var formatCommitTitle = (raw, opts) => {
347
+ const { allowGitmoji, mode = "standard" } = opts;
348
+ let norm = normalizeConventionalTitle(sanitizeTitle(raw, allowGitmoji));
349
+ if (!allowGitmoji || mode !== "gitmoji" && mode !== "gitmoji-pure") {
350
+ return norm;
351
+ }
352
+ if (mode === "gitmoji-pure") {
353
+ let m2 = norm.match(EMOJI_TYPE_RE);
354
+ if (m2) {
355
+ const emoji = m2[1];
356
+ const subject = m2[4];
357
+ norm = `${emoji}: ${subject}`;
358
+ } else if (m2 = norm.match(TYPE_RE)) {
359
+ const type = m2[1];
360
+ const subject = m2[3];
361
+ const em = EMOJI_MAP[type] || "\u{1F527}";
362
+ norm = `${em}: ${subject}`;
363
+ } else if (!/^([\p{Emoji}\p{So}\p{Sk}])+:/u.test(norm)) {
364
+ norm = `\u{1F527}: ${norm}`;
365
+ }
366
+ return norm;
367
+ }
368
+ let m = norm.match(EMOJI_TYPE_RE);
369
+ if (m) {
370
+ return norm;
371
+ }
372
+ if (m = norm.match(TYPE_RE)) {
373
+ const type = m[1];
374
+ const scope = m[2] || "";
375
+ const subject = m[3];
376
+ const em = EMOJI_MAP[type] || "\u{1F527}";
377
+ norm = `${em} ${type}${scope}: ${subject}`;
378
+ } else if (!/^([\p{Emoji}\p{So}\p{Sk}])+\s+\w+.*:/u.test(norm)) {
379
+ norm = `\u{1F527} chore: ${norm}`;
380
+ }
381
+ return norm;
382
+ };
383
+
384
+ // src/workflow/ui.ts
385
+ import chalk from "chalk";
386
+ function animateHeaderBase(text = "ai-conventional-commit", modelSegment) {
387
+ const mainText = text;
388
+ const modelSeg = modelSegment ? ` (using ${modelSegment})` : "";
389
+ if (!process.stdout.isTTY || process.env.AICC_NO_ANIMATION) {
390
+ if (modelSeg) console.log("\n\u250C " + chalk.bold(mainText) + chalk.dim(modelSeg));
391
+ else console.log("\n\u250C " + chalk.bold(mainText));
392
+ return Promise.resolve();
393
+ }
394
+ const palette = [
395
+ "#3a0d6d",
396
+ "#5a1ea3",
397
+ "#7a32d6",
398
+ "#9a4dff",
399
+ "#b267ff",
400
+ "#c37dff",
401
+ "#b267ff",
402
+ "#9a4dff",
403
+ "#7a32d6",
404
+ "#5a1ea3"
405
+ ];
406
+ process.stdout.write("\n");
407
+ return palette.reduce(async (p, color) => {
408
+ await p;
409
+ const frame = chalk.bold.hex(color)(mainText);
410
+ if (modelSeg) process.stdout.write("\r\u250C " + frame + chalk.dim(modelSeg));
411
+ else process.stdout.write("\r\u250C " + frame);
412
+ await new Promise((r) => setTimeout(r, 60));
413
+ }, Promise.resolve()).then(() => process.stdout.write("\n"));
414
+ }
415
+ function borderLine(content) {
416
+ if (!content) console.log("\u2502");
417
+ else console.log("\u2502 " + content);
418
+ }
419
+ function sectionTitle(label) {
420
+ console.log("\u2299 " + chalk.bold(label));
421
+ }
422
+ function abortMessage() {
423
+ console.log("\u2514 \u{1F645}\u200D\u2640\uFE0F No commit created.");
424
+ console.log();
425
+ }
426
+ function finalSuccess(opts) {
427
+ const elapsedMs = Date.now() - opts.startedAt;
428
+ const seconds = elapsedMs / 1e3;
429
+ const dur = seconds >= 0.1 ? seconds.toFixed(1) + "s" : elapsedMs + "ms";
430
+ const plural = opts.count !== 1;
431
+ if (plural) console.log(`\u2514 \u2728 ${opts.count} commits created in ${dur}.`);
432
+ else console.log(`\u2514 \u2728 commit created in ${dur}.`);
433
+ console.log();
434
+ }
435
+ function createPhasedSpinner(oraLib) {
436
+ const useAnim = process.stdout.isTTY && !process.env.AICC_NO_ANIMATION && !process.env.AICC_NO_SPINNER_ANIM;
437
+ const palette = [
438
+ "#3a0d6d",
439
+ "#5a1ea3",
440
+ "#7a32d6",
441
+ "#9a4dff",
442
+ "#b267ff",
443
+ "#c37dff",
444
+ "#b267ff",
445
+ "#9a4dff",
446
+ "#7a32d6",
447
+ "#5a1ea3"
448
+ ];
449
+ let label = "Starting";
450
+ let i = 0;
451
+ const spinner = oraLib({ text: chalk.bold(label), spinner: "dots" }).start();
452
+ let interval = null;
453
+ function frame() {
454
+ if (!useAnim) return;
455
+ spinner.text = chalk.bold.hex(palette[i])(label);
456
+ i = (i + 1) % palette.length;
457
+ }
458
+ if (useAnim) {
459
+ frame();
460
+ interval = setInterval(frame, 80);
461
+ }
462
+ function setLabel(next) {
463
+ label = next;
464
+ if (useAnim) {
465
+ i = 0;
466
+ frame();
467
+ } else {
468
+ spinner.text = chalk.bold(label);
469
+ }
470
+ }
471
+ function stopAnim() {
472
+ if (interval) {
473
+ clearInterval(interval);
474
+ interval = null;
475
+ }
476
+ }
477
+ return {
478
+ spinner,
479
+ async step(l, fn) {
480
+ setLabel(l);
481
+ try {
482
+ return await fn();
483
+ } catch (e) {
484
+ stopAnim();
485
+ const msg = `${l} failed: ${e?.message || e}`.replace(/^\s+/, "");
486
+ spinner.fail(msg);
487
+ throw e;
488
+ }
489
+ },
490
+ phase(l) {
491
+ setLabel(l);
492
+ },
493
+ stop() {
494
+ stopAnim();
495
+ spinner.stop();
496
+ }
497
+ };
498
+ }
499
+ function renderCommitBlock(opts) {
500
+ const dim = (s) => chalk.dim(s);
501
+ const white = (s) => chalk.white(s);
502
+ const msgColor = opts.messageLabelColor || dim;
503
+ const descColor = opts.descriptionLabelColor || dim;
504
+ const titleColor = opts.titleColor || white;
505
+ const bodyFirst = opts.bodyFirstLineColor || white;
506
+ const bodyRest = opts.bodyLineColor || white;
507
+ if (opts.fancy) {
508
+ const heading = opts.heading ? chalk.hex("#9a4dff").bold(opts.heading) : void 0;
509
+ if (heading) borderLine(heading);
510
+ borderLine(msgColor("Title:") + " " + titleColor(`${opts.indexPrefix || ""}${opts.title}`));
511
+ } else {
512
+ if (opts.heading) borderLine(chalk.bold(opts.heading));
513
+ if (!opts.hideMessageLabel)
514
+ borderLine(msgColor("Message:") + " " + titleColor(`${opts.indexPrefix || ""}${opts.title}`));
515
+ else
516
+ borderLine(msgColor("Title:") + " " + titleColor(`${opts.indexPrefix || ""}${opts.title}`));
517
+ }
518
+ borderLine();
519
+ if (opts.body) {
520
+ const lines = opts.body.split("\n");
521
+ lines.forEach((line, i) => {
522
+ if (line.trim().length === 0) borderLine();
523
+ else if (i === 0) {
524
+ borderLine(descColor("Description:"));
525
+ borderLine(bodyFirst(line));
526
+ } else borderLine(bodyRest(line));
527
+ });
528
+ }
529
+ }
530
+
531
+ export {
532
+ buildGenerationMessages,
533
+ buildRefineMessages,
534
+ OpenCodeProvider,
535
+ extractJSON,
536
+ checkCandidate,
537
+ formatCommitTitle,
538
+ animateHeaderBase,
539
+ borderLine,
540
+ sectionTitle,
541
+ abortMessage,
542
+ finalSuccess,
543
+ createPhasedSpinner,
544
+ renderCommitBlock
545
+ };