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())
75 changes: 75 additions & 0 deletions docs/external-ai.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# 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 when it has a saved ID and saves a returned ID after a successful answer. A command can report `{"type":"error","code":"session_expired","text":"…"}` to start one fresh session.

Chat session IDs are scoped to the worktree, conversation, profile and effective command arguments. Reopening a conversation can resume its session. Starting a new conversation or selecting a different model or effort starts a separate session. Commit generation uses its own session and resumes only when the profile's generation resume option is enabled.

## 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.

## Generate a commit subject

Open the AI helper from the commit toolbar and select **CLI**. Generate a one-line subject from all staged changes, review it, then apply it to the commit editor. From the staged file list, select the files to include and use its AI menu to generate from that selection. When amending, SourceGit uses the original commit's parent as the baseline.

## Ask about changes

- Use **AI Chat** at the right end of the repository toolbar. SourceGit opens a side panel, or shows the same chat in a separate window when the repository view is too narrow.
- Right-click a commit, selected files or lines in a text diff. **AI → Add to AI Chat** attaches the selection to the active draft. **AI → Analysis** prepares the selection and a suggested question for a new conversation. Review or remove attachments before sending.
- Press **Enter** to send or **Shift+Enter** for a new line. Sending clears the composer and shows the question and attachments in the conversation. Follow-up questions use the frozen attachments. **Stop** cancels the current request. On cancellation or CLI failure, SourceGit restores the draft and its attachments. The external command may impose its own time limit.
- Answers support Markdown and code blocks. Select text across paragraphs or blocks to copy it. If the CLI emits reasoning or tool events, expand them in the conversation.
- **History** reopens saved conversations and drafts for this worktree, including after restarting SourceGit. The application configuration directory stores chat messages, drafts and attached Git snapshots. Tool activity and reasoning are available in the current app session.

### Choose a model and effort

In an external CLI profile, expand **AI Chat model and effort**. Enter supported model IDs or effort values one per line, then add the argument templates for that CLI. For example, a CLI may expect `--model={model}` and `--reasoning_effort={effort}`. Use that CLI's documented flags and values. Add each argument on its own line.

The corresponding selectors appear under the chat composer. **CLI default** leaves the override unset, and SourceGit remembers the selection per conversation. For commit generation, use the profile's main arguments or create a dedicated profile with the desired model and effort.

## 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.
48 changes: 48 additions & 0 deletions docs/publishing-reviews.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# 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.

## Choose a destination and publish

1. In **Repository configuration → Publish Pull/Merge Request**, optionally set the source remote, target remote, default target branch and description template. For each target remote, SourceGit prefers the configured branch, then the last successful selection, then the remote's default branch.
2. Right-click a local branch and choose **AI → Create PR/MR…**. Check the source remote, target remote, target branch and matched connection. For a fork, select its remote as the source and the upstream repository's remote as the target. Both projects must be on the configured GitHub or GitLab instance.
3. Enter a title and description, or enable **Generate PR/MR draft** in an external AI profile and generate an editable draft. Drafting uses local Git objects for both selected revisions. Fetch the target branch and refresh the dialog if the revision shown in the dialog is missing locally.
4. Select **Push if needed and publish** after checking the refs and text. SourceGit verifies the reviewed tips and pushes the source branch if it needs updating. A rejected push stops publication. After a failed or interrupted create request, try again from the dialog. SourceGit checks for an existing open request for the same source and target before creating one.

### Troubleshooting

- If a connection is missing, use **Set access token** in the dialog. Match the target remote's host. GitHub and GitLab credentials control the provider API request.
- If Git rejects the push or cannot read either remote, check the remote URL and the repository's Git authentication, then refresh the dialog.
- If the provider denies publication, verify the token's access to both projects and its permission to create a pull or merge request.

## 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