Skip to content
Open
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
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,11 @@ 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.

## 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 });
}
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.
Loading