@sayknow-cli/coding-agent 0.7.8 → 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.
- package/CHANGELOG.md +20 -0
- package/dist/types/config/settings-schema.d.ts +9 -0
- package/dist/types/session/internal/managed-session-storage.d.ts +8 -0
- package/dist/types/session/session-storage.d.ts +4 -1
- package/dist/types/skc-runtime/launch-tmux.d.ts +1 -1
- package/dist/types/tools/gitlab.d.ts +128 -0
- package/dist/types/tools/index.d.ts +1 -0
- package/dist/types/utils/git.d.ts +21 -0
- package/package.json +7 -7
- package/src/cli/args.ts +12 -18
- package/src/config/settings-schema.ts +11 -0
- package/src/i18n/messages/de.settings.ts +3 -0
- package/src/i18n/messages/es.settings.ts +3 -0
- package/src/i18n/messages/fr.settings.ts +3 -0
- package/src/i18n/messages/ja.settings.ts +3 -0
- package/src/i18n/messages/ko.settings.ts +3 -0
- package/src/i18n/messages/zh.settings.ts +2 -0
- package/src/internal-urls/docs-index.generated.ts +9 -7
- package/src/modes/utils/abort-message.ts +3 -1
- package/src/prompts/tools/gitlab.md +13 -0
- package/src/sdk/session.ts +12 -1
- package/src/session/agent-session.ts +17 -3
- package/src/session/internal/managed-session-storage.ts +62 -5
- package/src/session/session-storage.ts +10 -1
- package/src/skc-runtime/launch-tmux.ts +1 -1
- package/src/tools/gitlab.ts +355 -0
- package/src/tools/index.ts +4 -0
- package/src/utils/git.ts +128 -0
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { getStreamIdleTimeoutRemediationMs } from "@sayknow-cli/ai/utils/idle-iterator";
|
|
2
|
+
|
|
1
3
|
const STREAM_IDLE_TIMEOUT_PATTERN = /\bstream stalled while waiting for the next event\b/i;
|
|
2
4
|
const GENERIC_ABORT_PATTERN = /^Request was aborted\.?$/i;
|
|
3
5
|
const ABORT_DISPLAY_LABEL_PATTERN = /^(?:Operation aborted|Aborted after \d+ retry attempts?)(?::|$)/;
|
|
@@ -37,5 +39,5 @@ function normalizeAbortCause(errorMessage: string | undefined): string {
|
|
|
37
39
|
function streamIdleTimeoutHint(cause: string): string {
|
|
38
40
|
if (!STREAM_IDLE_TIMEOUT_PATTERN.test(cause)) return "";
|
|
39
41
|
const separator = /[.!?]$/.test(cause) ? " " : ". ";
|
|
40
|
-
return `${separator}Hint: set PI_STREAM_IDLE_TIMEOUT_MS
|
|
42
|
+
return `${separator}Hint: set PI_STREAM_IDLE_TIMEOUT_MS=${getStreamIdleTimeoutRemediationMs()} for slow reasoning/proxy streams, or PI_STREAM_IDLE_TIMEOUT_MS=0 to disable the watchdog.`;
|
|
41
43
|
}
|
|
@@ -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>
|
package/src/sdk/session.ts
CHANGED
|
@@ -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
|
-
|
|
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.
|
|
@@ -12781,9 +12781,23 @@ export class AgentSession {
|
|
|
12781
12781
|
}
|
|
12782
12782
|
|
|
12783
12783
|
#closeCodexProviderSessionsForHistoryRewrite(): void {
|
|
12784
|
-
const
|
|
12785
|
-
|
|
12786
|
-
this
|
|
12784
|
+
const providerKey = "openai-codex-responses";
|
|
12785
|
+
const maps = new Set<Map<string, ProviderSessionState>>([this.#providerSessionState]);
|
|
12786
|
+
if (this.agent.providerSessionState) maps.add(this.agent.providerSessionState);
|
|
12787
|
+
for (const scope of this.#temporaryProviderSessionScopes) maps.add(scope.providerSessionState);
|
|
12788
|
+
for (const providerSessionState of maps) {
|
|
12789
|
+
const state = providerSessionState.get(providerKey);
|
|
12790
|
+
if (!state) continue;
|
|
12791
|
+
try {
|
|
12792
|
+
state.close();
|
|
12793
|
+
} catch (error) {
|
|
12794
|
+
logger.warn("Failed to close Codex provider session state after history rewrite", {
|
|
12795
|
+
providerKey,
|
|
12796
|
+
error: String(error),
|
|
12797
|
+
});
|
|
12798
|
+
}
|
|
12799
|
+
providerSessionState.delete(providerKey);
|
|
12800
|
+
}
|
|
12787
12801
|
}
|
|
12788
12802
|
|
|
12789
12803
|
/**
|
|
@@ -319,7 +319,7 @@ export function retainManagedDirectoryAuthority(
|
|
|
319
319
|
expected?: { dev: bigint; ino: bigint },
|
|
320
320
|
): RecoveryFsRoot | undefined {
|
|
321
321
|
assertManagedDirectoryRoot(root);
|
|
322
|
-
managedRelativePath(root, directory);
|
|
322
|
+
const components = managedRelativePath(root, directory);
|
|
323
323
|
const resolved = path.resolve(directory);
|
|
324
324
|
if (process.platform !== "linux") return undefined;
|
|
325
325
|
const named = fs.lstatSync(resolved, { bigint: true });
|
|
@@ -336,7 +336,7 @@ export function retainManagedDirectoryAuthority(
|
|
|
336
336
|
retainedRoot.identity.ino !== root.ino.toString()
|
|
337
337
|
)
|
|
338
338
|
throw new Error("Managed root authority changed");
|
|
339
|
-
const relative =
|
|
339
|
+
const relative = components.join("/");
|
|
340
340
|
return rootAuthority.retainManagedDirectory(relative, named.dev.toString(), named.ino.toString());
|
|
341
341
|
} finally {
|
|
342
342
|
rootAuthority.close();
|
|
@@ -368,13 +368,70 @@ function ensureManagedRoot(root: ManagedDirectoryRoot): void {
|
|
|
368
368
|
}
|
|
369
369
|
|
|
370
370
|
function managedRelativePath(root: ManagedDirectoryRoot, pathname: string): readonly string[] {
|
|
371
|
-
const
|
|
371
|
+
const resolved = path.resolve(pathname);
|
|
372
|
+
const components = textualRelativePath(root.canonicalPath, resolved) ?? aliasedRelativePath(root, resolved);
|
|
373
|
+
if (components === undefined) throw new Error(`Managed path escapes configured root: ${pathname}`);
|
|
374
|
+
return components;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function textualRelativePath(rootPath: string, resolved: string): string[] | undefined {
|
|
378
|
+
const relative = path.relative(rootPath, resolved);
|
|
372
379
|
if (relative === "") return [];
|
|
373
|
-
if (path.isAbsolute(relative) || relative.split(path.sep).includes(".."))
|
|
374
|
-
throw new Error(`Managed path escapes configured root: ${pathname}`);
|
|
380
|
+
if (path.isAbsolute(relative) || relative.split(path.sep).includes("..")) return undefined;
|
|
375
381
|
return relative.split(path.sep);
|
|
376
382
|
}
|
|
377
383
|
|
|
384
|
+
/**
|
|
385
|
+
* The root is canonical, but a caller may name it through an OS alias such as macOS
|
|
386
|
+
* `/var` -> `/private/var`. Find the textual ancestor that is the root directory itself
|
|
387
|
+
* (same device and inode, not a link) and accept it only when every link above it is OS
|
|
388
|
+
* layout. Components below it stay textual, so the per-component checks still reject any
|
|
389
|
+
* link inside the root.
|
|
390
|
+
*/
|
|
391
|
+
function aliasedRelativePath(root: ManagedDirectoryRoot, resolved: string): string[] | undefined {
|
|
392
|
+
const below: string[] = [];
|
|
393
|
+
let current = resolved;
|
|
394
|
+
for (;;) {
|
|
395
|
+
try {
|
|
396
|
+
const stat = fs.lstatSync(current, { bigint: true });
|
|
397
|
+
if (stat.isDirectory() && stat.dev === root.dev && stat.ino === root.ino) {
|
|
398
|
+
return onlyTrustedSystemLinks(path.dirname(current)) ? below.reverse() : undefined;
|
|
399
|
+
}
|
|
400
|
+
} catch (error) {
|
|
401
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
402
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
|
|
403
|
+
}
|
|
404
|
+
const parent = path.dirname(current);
|
|
405
|
+
if (parent === current) return undefined;
|
|
406
|
+
below.push(path.basename(current));
|
|
407
|
+
current = parent;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function onlyTrustedSystemLinks(pathname: string): boolean {
|
|
412
|
+
const parsed = path.parse(pathname);
|
|
413
|
+
let current = parsed.root;
|
|
414
|
+
for (const part of pathname.slice(parsed.root.length).split(path.sep)) {
|
|
415
|
+
if (!part) continue;
|
|
416
|
+
current = path.join(current, part);
|
|
417
|
+
const stat = fs.lstatSync(current);
|
|
418
|
+
if (stat.isSymbolicLink() && !isTrustedSystemLink(current, stat)) return false;
|
|
419
|
+
}
|
|
420
|
+
return true;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* A root-owned link inside a root-owned directory that nobody else can write (macOS `/var`
|
|
425
|
+
* and `/tmp`, merged-usr `/bin`) is OS layout: replacing it already requires root. Windows
|
|
426
|
+
* reports uid 0 for every file, so the exemption is POSIX-only.
|
|
427
|
+
* @internal
|
|
428
|
+
*/
|
|
429
|
+
export function isTrustedSystemLink(linkPath: string, linkStat: fs.Stats): boolean {
|
|
430
|
+
if (process.platform === "win32" || linkStat.uid !== 0) return false;
|
|
431
|
+
const parent = fs.statSync(path.dirname(linkPath));
|
|
432
|
+
return parent.uid === 0 && (parent.mode & 0o022) === 0;
|
|
433
|
+
}
|
|
434
|
+
|
|
378
435
|
const PROCESS_START_ID = randomUUID();
|
|
379
436
|
|
|
380
437
|
function securityError(pathname: string, result: NativeSecurity): Error {
|
|
@@ -7,6 +7,7 @@ import * as native from "@sayknow-cli/natives";
|
|
|
7
7
|
import { isEnoent, pathIsWithin, peekFile, toError } from "@sayknow-cli/utils";
|
|
8
8
|
import {
|
|
9
9
|
assertManagedDirectoryRoot,
|
|
10
|
+
isTrustedSystemLink,
|
|
10
11
|
type ManagedDirectoryRoot,
|
|
11
12
|
validateNativeSecurityResult,
|
|
12
13
|
} from "./internal/managed-session-storage";
|
|
@@ -487,14 +488,22 @@ function assertNoReparsePath(pathname: string): void {
|
|
|
487
488
|
for (const part of resolved.slice(parsed.root.length).split(path.sep)) {
|
|
488
489
|
if (!part) continue;
|
|
489
490
|
current = path.join(current, part);
|
|
491
|
+
let stat: fs.Stats;
|
|
490
492
|
try {
|
|
491
|
-
|
|
493
|
+
stat = fs.lstatSync(current);
|
|
492
494
|
} catch (error) {
|
|
493
495
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (stat.isSymbolicLink() && !isTrustedSystemLink(current, stat)) {
|
|
499
|
+
throw new Error(`Unsafe reparse storage path: ${current}`);
|
|
494
500
|
}
|
|
495
501
|
}
|
|
496
502
|
}
|
|
497
503
|
|
|
504
|
+
/** @internal Exported for tests. */
|
|
505
|
+
export { assertNoReparsePath as assertNoReparseStoragePath };
|
|
506
|
+
|
|
498
507
|
// FinalizationRegistry to clean up leaked file descriptors
|
|
499
508
|
const writerRegistry = new FinalizationRegistry<number>(fd => {
|
|
500
509
|
try {
|
|
@@ -70,7 +70,7 @@ export interface TmuxLaunchContext {
|
|
|
70
70
|
|
|
71
71
|
export interface TmuxSpawnResult {
|
|
72
72
|
exitCode: number | null;
|
|
73
|
-
signalCode?:
|
|
73
|
+
signalCode?: NodeJS.Signals | number | null;
|
|
74
74
|
stderr?: string;
|
|
75
75
|
/** Populated only when the caller asked for `stdout: "pipe"`. */
|
|
76
76
|
stdout?: string;
|
|
@@ -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
|
+
}
|
package/src/tools/index.ts
CHANGED
|
@@ -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");
|