Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,13 @@ For other AI service:
* The `Server` should fill in a URL equivalent to OpenAI's `https://api.openai.com/v1`. For example, when using `Ollama`, it should be `http://localhost:11434/v1` instead of `http://localhost:11434/api/generate`
* The `API Key` is optional that depends on the service

## External AI commands

Configure an external command under **Preferences → AI → External CLI profiles** to generate a commit subject or analyze changes.
See [External AI commands](docs/external-ai.md) for input modes, example profiles, and the optional JSONL protocol.

See [Publishing pull and merge requests](docs/publishing-reviews.md) for the optional publishing workflow.

## External Tools

This app supports open repository in external tools listed in the table below.
Expand Down
7 changes: 7 additions & 0 deletions THIRD-PARTY-LICENSES.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ The project uses the following third-party libraries or assets
- **License**: MIT License
- **License Link**: https://github.com/danipen/TextMateSharp/blob/master/LICENSE.md

### Markdig

- **Source** https://github.com/xoofx/markdig
- **Version** 1.6.0
- **License** BSD-2-Clause
- **License Link** https://licenses.nuget.org/BSD-2-Clause

### OpenAI .NET SDK

- **Source**: https://github.com/openai/openai-dotnet
Expand Down
71 changes: 71 additions & 0 deletions docs/examples/codely-jsonl.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Optional adapter for Codely. Configure node as the executable in SourceGit.
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';

const [entry, promptFile, ...options] = process.argv.slice(2);
const emit = event => console.log(JSON.stringify(event));
if (!entry || !promptFile) {
emit({ type: 'error', text: 'Expected the Codely entry point and prompt file.' });
process.exit(2);
}

const child = spawn(process.execPath, [entry, '-p', `@${promptFile}`, '--output-format', 'stream-json', ...options], {
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
let stderr = '';
let failure;
let delta = '';
let answer = '';
let session;
let userMessageSeen = false;
const tools = new Map();
child.stderr.setEncoding('utf8').on('data', text => { stderr = (stderr + text).slice(-8192); });
child.once('error', error => { failure = error.message; });
const exited = new Promise(resolve => child.once('close', resolve));

for await (const line of createInterface({ input: child.stdout, crlfDelay: Infinity })) {
let event;
try { event = JSON.parse(line); } catch { continue; }
if (!event || typeof event !== 'object') continue;
if (event.type === 'init' && typeof event.session_id === 'string') {
session = event.session_id;
emit({ type: 'session', id: session });
} else if (event.type === 'message') {
if (event.role === 'user') userMessageSeen = true;
if (event.role !== 'assistant') continue;
if (typeof event.reasoning_content === 'string' && event.reasoning_content)
emit({ type: 'thinking', text: event.reasoning_content });
const text = event.content;
if (typeof text !== 'string' || !text ||
(!userMessageSeen && session && text.startsWith(`resumed session ${session}, turns=`))) continue;
if (event.delta) delta += text;
else answer += text;
} else if (['thinking', 'reasoning', 'agent_think'].includes(event.type)) {
const text = event.thought ?? event.reasoning_content ?? event.content ?? event.text;
if (typeof text === 'string' && text) emit({ type: 'thinking', text });
} else if (['tool_use', 'tool_result', 'agent_tool_use', 'agent_tool_result'].includes(event.type)) {
const { type, ...details } = event;
if (event.tool_id && event.tool_name) tools.set(event.tool_id, event.tool_name);
const label = [event.tool_name ?? tools.get(event.tool_id) ?? event.agent_name ?? event.tool_id, event.status]
.filter(Boolean).join(' · ');
emit({ type: type.endsWith('use') ? 'tool_call' : 'tool_result', label, text: JSON.stringify(details, null, 2) });
if (type === 'tool_use' || type === 'tool_result') {
delta = '';
answer = '';
}
} else if (event.type === 'error' || (event.type === 'result' && event.status === 'error')) {
failure ??= event.error?.message ?? event.error ?? event.message ?? 'Codely reported an error.';
}
}

const code = await exited;
const text = (delta || answer).trim();
if (failure || code !== 0 || !text) {
const why = failure == null ? stderr.trim() || 'Codely returned no answer.' : String(failure);
const expired = /failed to restore startup resume history|no chat recording session found with id/i.test(why + stderr);
emit({ type: 'error', code: expired ? 'session_expired' : 'cli_failed', text: why });
process.exitCode = 1;
} else {
emit({ type: 'answer', text });
}
91 changes: 91 additions & 0 deletions docs/examples/gitlab-publisher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
"""Optional SourceGit publisher using a locally authenticated GitLab CLI."""

import argparse
import json
import subprocess
import sys
from urllib.parse import quote, urlencode, urlsplit


def project(url):
if "://" in url:
parsed = urlsplit(url)
host = parsed.netloc if parsed.scheme in ("https", "http") else parsed.hostname
path = parsed.path
else:
host, path = url.partition(":")[::2]
host = host.rsplit("@", 1)[-1]
path = path.strip("/").removesuffix(".git")
if not host or "/" not in path:
raise ValueError("Expected a GitLab remote URL with a group and project.")
return host, path


def api(host, method, path, payload=None):
args = ["glab", "api", "--hostname", host, "--method", method, path]
body = None
if payload is not None:
args += ["--input", "-"]
body = json.dumps(payload)
result = subprocess.run(args, input=body, capture_output=True, encoding="utf-8", check=False)
if result.returncode:
raise RuntimeError(result.stderr.strip() or "glab could not complete the request.")
return json.loads(result.stdout)


def publish(request, host_override):
source, target = request["source"], request["target"]
source_host, source_path = project(source["url"])
target_host, target_path = project(target["url"])
if source_host.lower() != target_host.lower() and host_override is None:
raise ValueError("Use a common GitLab host. Set --host explicitly for different aliases of that instance.")
host = host_override or target_host
source_id = api(host, "GET", "projects/" + quote(source_path, safe=""))["id"]
target_id = source_id if source_path == target_path else api(host, "GET", "projects/" + quote(target_path, safe=""))["id"]
if source_id == target_id and source["branch"] == target["branch"]:
raise ValueError("Choose different source and target branches.")

query = urlencode({
"state": "opened", "scope": "all", "source_branch": source["branch"],
"target_branch": target["branch"], "per_page": 100,
})
page = 1
while True:
items = api(host, "GET", f"projects/{target_id}/merge_requests?{query}&page={page}")
for item in items:
if item["source_project_id"] == source_id and item["target_project_id"] == target_id:
return {"status": "existing", "url": item["web_url"]}
if len(items) < 100:
break
page += 1

if request["operation"] == "find":
return {"status": "missing"}
if request["operation"] != "create":
raise ValueError("Unknown publication operation.")

created = api(host, "POST", f"projects/{source_id}/merge_requests", {
"source_branch": source["branch"],
"target_branch": target["branch"],
"target_project_id": target_id,
"title": request["title"],
"description": request["description"],
})
return {"status": "created", "url": created["web_url"]}


def main():
options = argparse.ArgumentParser(description=__doc__)
options.add_argument("--host", help="Override the GitLab hostname, for SSH aliases or self-managed servers.")
args = options.parse_args()
try:
request = json.loads(sys.stdin.buffer.read())
print(json.dumps(publish(request, args.host)))
except (OSError, ValueError, KeyError, RuntimeError, TypeError) as error:
print(str(error), file=sys.stderr)
return 1
return 0


if __name__ == "__main__":
sys.exit(main())
61 changes: 61 additions & 0 deletions docs/external-ai.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# External AI commands

Open **Preferences → AI → External CLI profiles** and add a profile. Set its executable and enter one argument per line. Put spaces inside the argument that needs them, without surrounding quotes. Select the tasks for this profile. A command can be a program from `PATH` or an absolute executable path. For a Windows script, select its interpreter as the executable and put the script path in the arguments.

SourceGit launches the command in the selected worktree. The command inherits your user permissions and can send the supplied prompt to its configured provider. Configure a headless, read-only command for analysis and generation. Set model and reasoning options in the command arguments, or create separate profiles for fast generation and deeper analysis.

## Input and output

- By default the command reads the UTF-8 prompt on stdin and writes the answer to stdout with exit code zero. The CLI should send diagnostics to stderr.
- To use a prompt file, select the prompt-file option and insert `{promptFile}` in one argument. The file is UTF-8 and temporary. A CLI that accepts an `@file` argument can use `@{promptFile}`.
- Select **Read SourceGit JSONL output** for a command or adapter that emits one UTF-8 JSON object per stdout line:

| Type | Fields | Meaning |
| --- | --- | --- |
| `answer` | `text` | One final answer |
| `thinking` | `text` | Optional reasoning output exposed by the provider |
| `tool_call`, `tool_result` | `text`, optional `label` | Optional tool activity |
| `session` | `id` | Optional session identifier for the completed answer |
| `error` | `text`, optional `code` | A failed request |

For a resumable JSONL profile, specify optional resume arguments with `{sessionId}`. SourceGit appends them only when it has an active ID. A resumed command can report `{"type":"error","code":"session_expired","text":"…"}` to request one fresh attempt. SourceGit stores an ID after successful completion, keyed by worktree, profile configuration and task. Analysis resumes by default when resume arguments are set. Generation resumes when its option is enabled. Stopping a request does not replace the saved ID.

## Examples

To check a profile without contacting an AI provider, choose `node` as the executable and enter these arguments in plain-text mode:

```text
-e
process.stdin.resume().on("end", () => console.log("fix: test the external generator"))
```

For a structured Codely profile, choose `node`, enable the prompt-file and JSONL options, and enter the following arguments. Replace the first two lines with absolute paths to the [adapter](examples/codely-jsonl.mjs) and the Codely JavaScript entry point from your installation. On npm installations, the Codely shim identifies its entry point.

```text
<absolute path to codely-jsonl.mjs>
<absolute path to the Codely CLI JavaScript entry point>
{promptFile}
--collaboration-mode
ask
--no-upm
--no-auto-edit-memory
```

Set the following resume arguments for that adapter:

```text
--resume-session
{sessionId}
```

The same app settings work with another vendor or a local backend by configuring its program directly or using a JSONL adapter for that backend. Profiles migrated from the older single-argument-string implementation show their previous arguments in the editor. Review the new input mode and enter any arguments you still need individually before enabling the profile's tasks.

## Use a profile

Open the AI helper from the commit toolbar to generate a subject for all staged changes. From a selection in the staged file list, the helper generates from those files. Apply the returned subject to the commit editor.

To analyze a commit, a file selection, or a text diff, open its context menu and choose **AI → Analysis**. Select a CLI profile at the top of the window and click **Start analysis**. The window captures the change when you open it and reuses that snapshot and the selected CLI for follow-up questions. Expand tool or provider reasoning output when available. Drag across the analysis to select multiple paragraphs and code blocks, then use the clipboard shortcut or the Copy menu.

## Create a branch and commit

In **Repository configuration → AI**, set the branch-name template. The default is `{type}/{slug}`. Generate a subject from the working-copy AI toolbar and review the branch name. **Create branch and commit** shows the branch, subject and staged file count before it writes to Git. If a hook rejects the commit, review the Git log and continue the commit on the new branch.
39 changes: 39 additions & 0 deletions docs/publishing-reviews.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Publishing pull and merge requests

## Set up PR/MR credentials

In **Preferences → PR/MR Credentials**, add a GitHub or GitLab connection. Enter the HTTPS address of the instance, such as `https://github.com`, `https://gitlab.com`, or your self-hosted server, and paste the token. For GitHub, use a token with access to the repositories and permission to write pull requests. For GitLab, use a token with the `api` scope and access to both projects. SourceGit stores tokens in the operating system's credential store and selects a connection by the target remote's host. An SSH remote can use the same PR/MR connection when its hostname matches the configured instance. Git reads and pushes use the repository's existing Git authentication.

In **Repository configuration → Publish Pull/Merge Request**, you can optionally set the source remote, target remote, default target branch and description template. The target branch falls back to the last successful selection for that remote or the remote's default branch. The publication dialog lets you change both remotes and the target branch. You can enable the draft task in an external AI profile to generate the title and description from local Git data, then edit both fields.

Right-click a local branch and choose **AI → Create PR/MR…**. The dialog shows the source remote, target remote, target branch, and matched connection. Confirm the displayed refs, title and description with **Push if needed and publish**. SourceGit pushes the selected revision when it is missing or behind on the source remote. A rejected push stops publication. If the result of a create request is uncertain, the next attempt checks for a matching request before creating one.

## Legacy publisher protocol

An existing command-based publisher can still run as a fallback when the selected target has no matching connection. The command receives a UTF-8 JSON request on stdin. Both `find` and `create` use the same publication metadata.

```json
{
"operation": "find",
"source": {
"remote": "fork",
"url": "https://forge.example.com/user/project.git",
"branch": "fix/example",
"commit": "the reviewed source commit ID"
},
"target": {
"remote": "upstream",
"url": "https://forge.example.com/team/project.git",
"branch": "main",
"commit": "the reviewed target commit ID"
},
"title": "Fix the example",
"description": "Markdown description"
}
```

- `find` is a read-only lookup. Return `{"status":"missing"}` or `{"status":"existing","url":"https://…"}` for an open request matching both projects and branches.
- `create` returns `{"status":"created","url":"https://…"}` or the same `existing` response if a matching request was created in the meantime.
- Write exactly one JSON result to stdout. Report failures on stderr with a nonzero exit code. Leave Git pushes to SourceGit.

The [GitLab command adapter](examples/gitlab-publisher.py) remains available for existing publisher configurations. It uses Python 3.9+ and an authenticated [GitLab CLI](https://docs.gitlab.com/cli/).
Loading