@sayknow-cli/coding-agent 0.7.9 → 0.7.10

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,13 @@
1
+ GitLab CLI tool with a single op-based dispatch. Wraps `glab` (gitlab.com and self-hosted instances that `glab auth login` knows) for merge requests and pipeline status.
2
+
3
+ <instruction>
4
+ Pick the operation via `op`. Each op uses a subset of the parameters. `repo` (OWNER/REPO, GROUP/NAMESPACE/REPO, or project URL) defaults to the current checkout's GitLab remote.
5
+ - `mr_create` — Create a merge request. Provide `title` (and optional `description`) or set `fill: true` to fill both from commits. `fill` also pushes the source branch. Optional `source` (defaults to the current branch), `target` (defaults to the project default branch), `draft`, `push` (push the source branch first; needed when it is not on the remote yet), `reviewer[]`, `assignee[]`, `label[]`, `removeSourceBranch`, `squash`. If an open merge request already exists for the same source (and target), it is returned and nothing is created.
6
+ - `mr_view` — Read one merge request. Optional `mr` (iid, URL, or source branch; defaults to the current branch's MR). Returns state, branches, merge status, conflicts, head pipeline, and description.
7
+ - `mr_list` — List merge requests. Optional `state` (`opened` default, `merged`, `closed`, `all`), `source`, `target`, `label[]`, `limit` (max 50).
8
+ - `ci_status` — Latest pipeline status with its jobs. Optional `branch` (defaults to the current branch) or `mr` (merge request iid). Reports "No pipeline" instead of failing when none exists.
9
+ </instruction>
10
+
11
+ <output>
12
+ Returns a readable summary for the chosen op (merge request metadata, list entries with URLs, or pipeline jobs).
13
+ </output>
@@ -1605,7 +1605,11 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
1605
1605
  const getReservedSubskillToolNames = () => [
1606
1606
  ...new Set([
1607
1607
  ...builtinTools.map(tool => tool.name),
1608
- ...(options.toolNames?.map(name => name.toLowerCase()) ?? []),
1608
+ // Reserve only built-in names from the allowlist: a plugin tool requested
1609
+ // by name must not be quarantined as a collision with its own request.
1610
+ ...(options.toolNames
1611
+ ?.map(name => name.toLowerCase())
1612
+ .filter(name => Object.hasOwn(BUILTIN_TOOLS, name) || Object.hasOwn(HIDDEN_TOOLS, name)) ?? []),
1609
1613
  ...(options.customTools?.map(tool => (isCustomTool(tool) ? tool.name : tool.name)) ?? []),
1610
1614
  ...customTools.map(tool => tool.name),
1611
1615
  ]),
@@ -2218,6 +2222,13 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
2218
2222
  ]
2219
2223
  : toolNamesFromRegistry;
2220
2224
  const normalizedRequested = requestedToolNames.filter(name => toolRegistry.has(name));
2225
+ if (hasExplicitToolNames) {
2226
+ for (const name of requestedToolNames) {
2227
+ if (!toolRegistry.has(name)) {
2228
+ logger.warn("Unknown tool passed to --tools", { tool: name, validTools: toolNamesFromRegistry });
2229
+ }
2230
+ }
2231
+ }
2221
2232
  const explicitRequestedToolNames = hasExplicitToolNames ? normalizedRequested : [];
2222
2233
  const requestedToolNameSet = new Set(normalizedRequested);
2223
2234
  // Normalize the user-facing mcp.discoveryMode alias once at session construction.
@@ -0,0 +1,355 @@
1
+ import type { AgentTool, AgentToolContext, AgentToolResult } from "@sayknow-cli/agent-core";
2
+ import { prompt, untilAborted } from "@sayknow-cli/utils";
3
+ import * as z from "zod/v4";
4
+ import gitlabDescription from "../prompts/tools/gitlab.md" with { type: "text" };
5
+ import * as git from "../utils/git";
6
+ import type { ToolSession } from ".";
7
+ import type { OutputMeta } from "./output-meta";
8
+ import { ToolError } from "./tool-errors";
9
+ import { toolResult } from "./tool-result";
10
+
11
+ const MR_URL_PATTERN = /https?:\/\/\S+\/-\/merge_requests\/(\d+)/;
12
+ const NO_PIPELINE_PATTERN = /No pipeline found/i;
13
+ const MR_STATES = ["opened", "merged", "closed", "all"] as const;
14
+ const DESCRIPTION_LIMIT = 4000;
15
+ const LIST_LIMIT_MAX = 50;
16
+
17
+ const gitlabSchema = z
18
+ .object({
19
+ op: z.enum(["mr_create", "mr_view", "mr_list", "ci_status"] as const).describe("gitlab operation"),
20
+ repo: z.string().describe("OWNER/REPO, GROUP/NAMESPACE/REPO, or project URL").optional(),
21
+ mr: z.string().describe("merge request iid, url, or source branch").optional(),
22
+ title: z.string().describe("mr title").optional(),
23
+ description: z.string().describe("mr description markdown").optional(),
24
+ source: z.string().describe("mr source branch").optional(),
25
+ target: z.string().describe("mr target branch").optional(),
26
+ draft: z.boolean().describe("open mr as draft").optional(),
27
+ fill: z.boolean().describe("fill title/description from commits (also pushes the branch)").optional(),
28
+ push: z.boolean().describe("push the source branch before creating the mr").optional(),
29
+ reviewer: z.array(z.string()).describe("reviewer usernames").optional(),
30
+ assignee: z.array(z.string()).describe("assignee usernames").optional(),
31
+ label: z.array(z.string()).describe("labels").optional(),
32
+ removeSourceBranch: z.boolean().describe("delete source branch on merge").optional(),
33
+ squash: z.boolean().describe("squash commits on merge").optional(),
34
+ state: z.enum(MR_STATES).describe("mr_list state filter").optional(),
35
+ branch: z.string().describe("ci_status branch").optional(),
36
+ limit: z.number().describe("max results").optional(),
37
+ })
38
+ .strict();
39
+
40
+ type GitlabInput = z.infer<typeof gitlabSchema>;
41
+
42
+ export interface GlabUser {
43
+ username?: string;
44
+ name?: string;
45
+ }
46
+
47
+ export interface GlabPipeline {
48
+ id?: number;
49
+ status?: string;
50
+ ref?: string;
51
+ sha?: string;
52
+ web_url?: string;
53
+ created_at?: string;
54
+ updated_at?: string;
55
+ jobs?: GlabJob[];
56
+ }
57
+
58
+ export interface GlabJob {
59
+ name?: string;
60
+ stage?: string;
61
+ status?: string;
62
+ web_url?: string;
63
+ failure_reason?: string;
64
+ allow_failure?: boolean;
65
+ }
66
+
67
+ export interface GlabMergeRequest {
68
+ iid?: number;
69
+ title?: string;
70
+ description?: string | null;
71
+ state?: string;
72
+ draft?: boolean;
73
+ web_url?: string;
74
+ source_branch?: string;
75
+ target_branch?: string;
76
+ author?: GlabUser | null;
77
+ reviewers?: GlabUser[] | null;
78
+ labels?: string[] | null;
79
+ created_at?: string;
80
+ updated_at?: string;
81
+ detailed_merge_status?: string;
82
+ has_conflicts?: boolean;
83
+ head_pipeline?: GlabPipeline | null;
84
+ }
85
+
86
+ export interface GitlabToolDetails {
87
+ meta?: OutputMeta;
88
+ op: GitlabInput["op"];
89
+ url?: string;
90
+ iid?: number;
91
+ created?: boolean;
92
+ }
93
+
94
+ function clean(value: string | null | undefined): string | undefined {
95
+ const trimmed = value?.trim();
96
+ return trimmed ? trimmed : undefined;
97
+ }
98
+
99
+ function cleanList(values: string[] | undefined): string[] {
100
+ return (values ?? []).map(value => value.trim()).filter(value => value.length > 0);
101
+ }
102
+
103
+ function withRepo(args: string[], repo: string | undefined): string[] {
104
+ if (repo) args.push("--repo", repo);
105
+ return args;
106
+ }
107
+
108
+ function line(lines: string[], label: string, value: string | number | boolean | undefined): void {
109
+ if (value === undefined || value === "") return;
110
+ lines.push(`${label}: ${value}`);
111
+ }
112
+
113
+ function formatUser(user: GlabUser | null | undefined): string | undefined {
114
+ if (!user) return undefined;
115
+ if (user.username) return `@${user.username}`;
116
+ return clean(user.name);
117
+ }
118
+
119
+ function truncate(text: string, limit: number): string {
120
+ return text.length > limit ? `${text.slice(0, limit)}\n\n[description truncated at ${limit} chars]` : text;
121
+ }
122
+
123
+ export function formatMergeRequest(mr: GlabMergeRequest, heading: string): string {
124
+ const title = clean(mr.title) ?? "Untitled";
125
+ const lines = [mr.iid !== undefined ? `# ${heading} !${mr.iid}: ${title}` : `# ${heading}: ${title}`, ""];
126
+ line(lines, "URL", mr.web_url);
127
+ line(lines, "State", mr.state);
128
+ line(lines, "Draft", mr.draft);
129
+ if (mr.source_branch || mr.target_branch)
130
+ line(lines, "Branches", `${mr.source_branch ?? "?"} -> ${mr.target_branch ?? "?"}`);
131
+ line(lines, "Author", formatUser(mr.author));
132
+ const reviewers = (mr.reviewers ?? []).map(formatUser).filter((value): value is string => Boolean(value));
133
+ if (reviewers.length > 0) line(lines, "Reviewers", reviewers.join(", "));
134
+ if (mr.labels && mr.labels.length > 0) line(lines, "Labels", mr.labels.join(", "));
135
+ line(lines, "Merge status", mr.detailed_merge_status);
136
+ if (mr.has_conflicts) line(lines, "Conflicts", true);
137
+ if (mr.head_pipeline?.status) {
138
+ line(
139
+ lines,
140
+ "Pipeline",
141
+ `${mr.head_pipeline.status}${mr.head_pipeline.web_url ? ` (${mr.head_pipeline.web_url})` : ""}`,
142
+ );
143
+ }
144
+ line(lines, "Created", mr.created_at);
145
+ line(lines, "Updated", mr.updated_at);
146
+ const description = clean(mr.description ?? undefined);
147
+ if (description) lines.push("", "## Description", "", truncate(description, DESCRIPTION_LIMIT));
148
+ return lines.join("\n").trim();
149
+ }
150
+
151
+ export function formatPipeline(pipeline: GlabPipeline): string {
152
+ const lines = [
153
+ `# Pipeline${pipeline.id !== undefined ? ` #${pipeline.id}` : ""}: ${pipeline.status ?? "unknown"}`,
154
+ "",
155
+ ];
156
+ line(lines, "URL", pipeline.web_url);
157
+ line(lines, "Ref", pipeline.ref);
158
+ line(lines, "SHA", pipeline.sha?.slice(0, 12));
159
+ line(lines, "Updated", pipeline.updated_at ?? pipeline.created_at);
160
+ const jobs = pipeline.jobs ?? [];
161
+ if (jobs.length > 0) {
162
+ lines.push("", "## Jobs", "");
163
+ for (const job of jobs) {
164
+ const reason = job.failure_reason ? ` (${job.failure_reason})` : "";
165
+ const allowed = job.allow_failure && job.status === "failed" ? " [allowed to fail]" : "";
166
+ lines.push(
167
+ `- [${job.status ?? "?"}] ${job.stage ? `${job.stage}/` : ""}${job.name ?? "?"}${reason}${allowed}`,
168
+ );
169
+ }
170
+ }
171
+ return lines.join("\n").trim();
172
+ }
173
+
174
+ function result(text: string, details: GitlabToolDetails): AgentToolResult<GitlabToolDetails> {
175
+ const builder = toolResult<GitlabToolDetails>(details).text(text);
176
+ if (details.url) builder.sourceUrl(details.url);
177
+ return builder.done();
178
+ }
179
+
180
+ export class GitlabTool implements AgentTool<typeof gitlabSchema, GitlabToolDetails> {
181
+ readonly name = "gitlab";
182
+ readonly summary = "Create and inspect GitLab merge requests and pipelines";
183
+ readonly loadMode = "discoverable";
184
+ readonly label = "GitLab";
185
+ readonly description = prompt.render(gitlabDescription);
186
+ readonly parameters = gitlabSchema;
187
+ readonly strict = true;
188
+
189
+ constructor(private readonly session: ToolSession) {}
190
+
191
+ static createIf(session: ToolSession): GitlabTool | null {
192
+ if (!git.gitlab.available()) return null;
193
+ return new GitlabTool(session);
194
+ }
195
+
196
+ async execute(
197
+ _toolCallId: string,
198
+ params: GitlabInput,
199
+ signal?: AbortSignal,
200
+ _onUpdate?: unknown,
201
+ _context?: AgentToolContext,
202
+ ): Promise<AgentToolResult<GitlabToolDetails>> {
203
+ return untilAborted(signal, async () => {
204
+ switch (params.op) {
205
+ case "mr_create":
206
+ return this.#mrCreate(params, signal);
207
+ case "mr_view":
208
+ return this.#mrView(params, signal);
209
+ case "mr_list":
210
+ return this.#mrList(params, signal);
211
+ case "ci_status":
212
+ return this.#ciStatus(params, signal);
213
+ default:
214
+ throw new ToolError(`Unsupported gitlab op: ${String((params as { op: unknown }).op)}`);
215
+ }
216
+ });
217
+ }
218
+
219
+ async #mrCreate(params: GitlabInput, signal: AbortSignal | undefined): Promise<AgentToolResult<GitlabToolDetails>> {
220
+ const cwd = this.session.cwd;
221
+ const repo = clean(params.repo);
222
+ const title = clean(params.title);
223
+ const fill = params.fill ?? false;
224
+ if (!fill && !title) throw new ToolError("title is required unless fill is true");
225
+ if (fill && (title || params.description !== undefined)) {
226
+ throw new ToolError("fill is mutually exclusive with title and description");
227
+ }
228
+ const target = clean(params.target);
229
+ const source = clean(params.source) ?? (await git.branch.current(cwd, signal)) ?? undefined;
230
+ if (!source) throw new ToolError("source branch is required when HEAD is detached");
231
+ if (target && target === source) throw new ToolError(`source and target branch are both ${source}`);
232
+
233
+ // An open MR for the same source (and target, when given) is returned instead of creating a duplicate.
234
+ const listArgs = withRepo(["mr", "list", "--source-branch", source, "--output", "json", "--per-page", "5"], repo);
235
+ if (target) listArgs.push("--target-branch", target);
236
+ const existing = await git.gitlab.json<GlabMergeRequest[]>(cwd, listArgs, signal, {
237
+ repoProvided: Boolean(repo),
238
+ });
239
+ const open = Array.isArray(existing) ? existing.find(mr => mr.state === "opened") : undefined;
240
+ if (open) {
241
+ return result(
242
+ `${formatMergeRequest(open, "Existing Merge Request")}\n\nAn open merge request for ${source} already exists; nothing was created.`,
243
+ { op: "mr_create", url: open.web_url, iid: open.iid, created: false },
244
+ );
245
+ }
246
+
247
+ const args = withRepo(["mr", "create", "--yes", "--source-branch", source], repo);
248
+ if (target) args.push("--target-branch", target);
249
+ if (fill) args.push("--fill");
250
+ else {
251
+ args.push("--title", title as string);
252
+ // An explicit (possibly empty) description keeps glab from prompting for one.
253
+ args.push("--description", params.description ?? "");
254
+ }
255
+ if (params.draft) args.push("--draft");
256
+ if (params.push && !fill) args.push("--push");
257
+ if (params.removeSourceBranch !== undefined) args.push(`--remove-source-branch=${params.removeSourceBranch}`);
258
+ if (params.squash !== undefined) args.push(`--squash-before-merge=${params.squash}`);
259
+ for (const reviewer of cleanList(params.reviewer)) args.push("--reviewer", reviewer);
260
+ for (const assignee of cleanList(params.assignee)) args.push("--assignee", assignee);
261
+ for (const label of cleanList(params.label)) args.push("--label", label);
262
+
263
+ const output = await git.gitlab.text(cwd, args, signal, { repoProvided: Boolean(repo) });
264
+ const match = git.cleanGlabMessage(output).match(MR_URL_PATTERN) ?? output.match(MR_URL_PATTERN);
265
+ if (!match) {
266
+ throw new ToolError(
267
+ `glab mr create did not report a merge request URL: ${git.cleanGlabMessage(output) || "(no output)"}`,
268
+ );
269
+ }
270
+ const url = match[0];
271
+ const iid = Number(match[1]);
272
+ let mr: GlabMergeRequest = {
273
+ iid,
274
+ web_url: url,
275
+ title,
276
+ source_branch: source,
277
+ target_branch: target,
278
+ draft: params.draft,
279
+ };
280
+ try {
281
+ mr = await git.gitlab.json<GlabMergeRequest>(
282
+ cwd,
283
+ withRepo(["mr", "view", String(iid), "--output", "json"], repo),
284
+ signal,
285
+ {
286
+ repoProvided: Boolean(repo),
287
+ },
288
+ );
289
+ } catch {
290
+ // Best-effort summary; the merge request already exists.
291
+ }
292
+ return result(formatMergeRequest(mr, "Created Merge Request"), { op: "mr_create", url, iid, created: true });
293
+ }
294
+
295
+ async #mrView(params: GitlabInput, signal: AbortSignal | undefined): Promise<AgentToolResult<GitlabToolDetails>> {
296
+ const repo = clean(params.repo);
297
+ const args = ["mr", "view"];
298
+ const mr = clean(params.mr);
299
+ if (mr) args.push(mr);
300
+ args.push("--output", "json");
301
+ const data = await git.gitlab.json<GlabMergeRequest>(this.session.cwd, withRepo(args, repo), signal, {
302
+ repoProvided: Boolean(repo),
303
+ });
304
+ return result(formatMergeRequest(data, "Merge Request"), { op: "mr_view", url: data.web_url, iid: data.iid });
305
+ }
306
+
307
+ async #mrList(params: GitlabInput, signal: AbortSignal | undefined): Promise<AgentToolResult<GitlabToolDetails>> {
308
+ const repo = clean(params.repo);
309
+ const limit = Math.min(Math.max(Math.floor(params.limit ?? 10), 1), LIST_LIMIT_MAX);
310
+ const args = withRepo(["mr", "list", "--output", "json", "--per-page", String(limit)], repo);
311
+ const state = params.state ?? "opened";
312
+ if (state === "merged") args.push("--merged");
313
+ else if (state === "closed") args.push("--closed");
314
+ else if (state === "all") args.push("--all");
315
+ const source = clean(params.source);
316
+ const target = clean(params.target);
317
+ if (source) args.push("--source-branch", source);
318
+ if (target) args.push("--target-branch", target);
319
+ for (const label of cleanList(params.label)) args.push("--label", label);
320
+ const items = await git.gitlab.json<GlabMergeRequest[]>(this.session.cwd, args, signal, {
321
+ repoProvided: Boolean(repo),
322
+ });
323
+ const list = Array.isArray(items) ? items : [];
324
+ const lines = [`# GitLab merge requests (${state})`, "", `${list.length} result${list.length === 1 ? "" : "s"}`];
325
+ for (const mr of list) {
326
+ const draft = mr.draft ? " [draft]" : "";
327
+ lines.push(
328
+ `- !${mr.iid ?? "?"}${draft} ${clean(mr.title) ?? "Untitled"} — ${mr.source_branch ?? "?"} -> ${mr.target_branch ?? "?"}, ${formatUser(mr.author) ?? "unknown"}, ${mr.state ?? "?"}`,
329
+ );
330
+ if (mr.web_url) lines.push(` ${mr.web_url}`);
331
+ }
332
+ return result(lines.join("\n"), { op: "mr_list" });
333
+ }
334
+
335
+ async #ciStatus(params: GitlabInput, signal: AbortSignal | undefined): Promise<AgentToolResult<GitlabToolDetails>> {
336
+ const repo = clean(params.repo);
337
+ const args = withRepo(["ci", "get", "--output", "json"], repo);
338
+ const mr = clean(params.mr);
339
+ const branch = clean(params.branch);
340
+ if (mr) {
341
+ if (!/^\d+$/.test(mr)) throw new ToolError("ci_status mr must be a merge request iid");
342
+ args.push("--merge-request", mr);
343
+ } else if (branch) args.push("--branch", branch);
344
+ const run = await git.gitlab.run(this.session.cwd, args, signal);
345
+ if (run.exitCode !== 0) {
346
+ const message = git.cleanGlabMessage(run.stderr || run.stdout);
347
+ if (NO_PIPELINE_PATTERN.test(message)) {
348
+ return result(`# No pipeline\n\n${message}`, { op: "ci_status" });
349
+ }
350
+ throw new ToolError(git.formatGlabFailure(args, run.stdout, run.stderr, { repoProvided: Boolean(repo) }));
351
+ }
352
+ const pipeline = git.parseGlabJson<GlabPipeline>(run.stdout);
353
+ return result(formatPipeline(pipeline), { op: "ci_status", url: pipeline.web_url });
354
+ }
355
+ }
@@ -46,6 +46,7 @@ import { DebugTool } from "./debug";
46
46
  import { EvalTool } from "./eval";
47
47
  import { FindTool } from "./find";
48
48
  import { GithubTool } from "./gh";
49
+ import { GitlabTool } from "./gitlab";
49
50
  import { IrcTool } from "./irc";
50
51
  import { JobTool } from "./job";
51
52
  import { LocateTool } from "./locate";
@@ -87,6 +88,7 @@ export * from "./debug";
87
88
  export * from "./eval";
88
89
  export * from "./find";
89
90
  export * from "./gh";
91
+ export * from "./gitlab";
90
92
  export * from "./image-gen";
91
93
  export * from "./irc";
92
94
  export * from "./job";
@@ -476,6 +478,7 @@ export const BUILTIN_TOOLS: Record<string, ToolFactory> = {
476
478
  calc: s => new CalculatorTool(s),
477
479
  ssh: loadSshTool,
478
480
  github: GithubTool.createIf,
481
+ gitlab: GitlabTool.createIf,
479
482
  find: s => new FindTool(s),
480
483
  search: s => new SearchTool(s),
481
484
  locate: LocateTool.createIf,
@@ -700,6 +703,7 @@ export async function createTools(session: ToolSession, toolNames?: string[]): P
700
703
  if (name === "find") return session.settings.get("find.enabled");
701
704
  if (name === "search") return session.settings.get("search.enabled");
702
705
  if (name === "github") return session.settings.get("github.enabled");
706
+ if (name === "gitlab") return session.settings.get("gitlab.enabled");
703
707
  if (name === "ast_grep") return session.settings.get("astGrep.enabled");
704
708
  if (name === "ast_edit") return session.settings.get("astEdit.enabled");
705
709
  if (name === "render_mermaid") return session.settings.get("renderMermaid.enabled");
package/src/utils/git.ts CHANGED
@@ -1607,3 +1607,131 @@ export const github = {
1607
1607
  return result.stdout;
1608
1608
  },
1609
1609
  };
1610
+
1611
+ // ════════════════════════════════════════════════════════════════════════════
1612
+ // API: gitlab (GitLab CLI)
1613
+ // ════════════════════════════════════════════════════════════════════════════
1614
+
1615
+ export interface GlabCommandOptions {
1616
+ repoProvided?: boolean;
1617
+ }
1618
+
1619
+ /** Collapse glab's boxed, ANSI-colored error banner into one plain line. */
1620
+ export function cleanGlabMessage(text: string): string {
1621
+ return text
1622
+ .replace(/\u001b\[[0-9;?]*[A-Za-z]/g, "")
1623
+ .split("\n")
1624
+ .map(line => line.trim())
1625
+ .filter(
1626
+ line =>
1627
+ line.length > 0 &&
1628
+ line !== "ERROR" &&
1629
+ !line.startsWith("DEPRECATION WARNING") &&
1630
+ !/^A new version of glab|^https:\/\/gitlab\.com\/gitlab-org\/cli\/-\/releases/.test(line),
1631
+ )
1632
+ .map(line => line.replace(/^X\s+/, ""))
1633
+ .join(" ")
1634
+ .trim();
1635
+ }
1636
+
1637
+ export function formatGlabFailure(
1638
+ args: readonly string[],
1639
+ stdout: string,
1640
+ stderr: string,
1641
+ options?: GlabCommandOptions,
1642
+ ): string {
1643
+ const message = cleanGlabMessage(stderr || stdout);
1644
+ if (/401 Unauthorized|glab auth login|No token found|could not authenticate/i.test(message)) {
1645
+ return `GitLab CLI is not authenticated for this host. Run \`glab auth login\`. (${message})`;
1646
+ }
1647
+ if (
1648
+ !options?.repoProvided &&
1649
+ /not a git repository|no git remotes found|none of the git remotes configured/i.test(message)
1650
+ ) {
1651
+ return "GitLab repository context is unavailable. Pass `repo` explicitly or run the tool inside a GitLab checkout.";
1652
+ }
1653
+ if (message.length > 0) return message;
1654
+ return `GitLab CLI command failed: glab ${args.join(" ")}`;
1655
+ }
1656
+
1657
+ /**
1658
+ * Parse `glab --output json` stdout. glab prints deprecation/update notices on stdout ahead of the
1659
+ * payload in some versions, so parsing starts at the first line that opens a JSON value.
1660
+ */
1661
+ export function parseGlabJson<T>(stdout: string): T {
1662
+ const lines = stdout.split("\n");
1663
+ const start = lines.findIndex(line => /^\s*[[{]/.test(line));
1664
+ if (start < 0) {
1665
+ throw new ToolError(
1666
+ stdout.trim() ? "GitLab CLI returned invalid JSON output." : "GitLab CLI returned empty output.",
1667
+ );
1668
+ }
1669
+ try {
1670
+ return JSON.parse(lines.slice(start).join("\n")) as T;
1671
+ } catch {
1672
+ throw new ToolError("GitLab CLI returned invalid JSON output.");
1673
+ }
1674
+ }
1675
+
1676
+ export const gitlab = {
1677
+ /** Check if `glab` CLI is installed. */
1678
+ available(): boolean {
1679
+ return Boolean($which("glab"));
1680
+ },
1681
+
1682
+ /** Run a raw non-interactive `glab` command. Does not throw on non-zero exit. */
1683
+ async run(cwd: string, args: string[], signal?: AbortSignal): Promise<GhCommandResult> {
1684
+ throwIfAborted(signal);
1685
+ if (!$which("glab")) {
1686
+ throw new ToolError("GitLab CLI (glab) is not installed. Install it from https://gitlab.com/gitlab-org/cli.");
1687
+ }
1688
+ try {
1689
+ const child = Bun.spawn(["glab", ...args], {
1690
+ cwd,
1691
+ stdin: "ignore",
1692
+ stdout: "pipe",
1693
+ stderr: "pipe",
1694
+ windowsHide: true,
1695
+ signal,
1696
+ env: {
1697
+ ...process.env,
1698
+ NO_COLOR: "1",
1699
+ GLAB_NO_PROMPT: "1",
1700
+ GLAB_CHECK_UPDATE: "false",
1701
+ GLAB_SEND_TELEMETRY: "false",
1702
+ },
1703
+ });
1704
+ if (!child.stdout || !child.stderr) {
1705
+ throw new ToolError("Failed to capture GitLab CLI output.");
1706
+ }
1707
+ const [stdout, stderr, exitCode] = await Promise.all([
1708
+ new Response(child.stdout).text(),
1709
+ new Response(child.stderr).text(),
1710
+ child.exited,
1711
+ ]);
1712
+ throwIfAborted(signal);
1713
+ return { exitCode: exitCode ?? 0, stdout: stdout.trim(), stderr: stderr.trim() };
1714
+ } catch (error) {
1715
+ if (signal?.aborted) throw new ToolAbortError();
1716
+ throw error;
1717
+ }
1718
+ },
1719
+
1720
+ /** Run `glab` and parse stdout as JSON. Throws on non-zero exit or invalid JSON. */
1721
+ async json<T>(cwd: string, args: string[], signal?: AbortSignal, options?: GlabCommandOptions): Promise<T> {
1722
+ const result = await gitlab.run(cwd, args, signal);
1723
+ if (result.exitCode !== 0) {
1724
+ throw new ToolError(formatGlabFailure(args, result.stdout, result.stderr, options));
1725
+ }
1726
+ return parseGlabJson<T>(result.stdout);
1727
+ },
1728
+
1729
+ /** Run `glab` and return stdout as text. Throws on non-zero exit. */
1730
+ async text(cwd: string, args: string[], signal?: AbortSignal, options?: GlabCommandOptions): Promise<string> {
1731
+ const result = await gitlab.run(cwd, args, signal);
1732
+ if (result.exitCode !== 0) {
1733
+ throw new ToolError(formatGlabFailure(args, result.stdout, result.stderr, options));
1734
+ }
1735
+ return result.stdout;
1736
+ },
1737
+ };