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
23 changes: 14 additions & 9 deletions src/Main.qml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ ApplicationWindow {
if (backend.outcome === "material") return qsTr("Draw · insufficient material")
if (backend.outcome === "fifty-moves") return qsTr("Draw · fifty-move rule")
if (backend.outcome === "repetition") return qsTr("Draw · threefold repetition")
if (backend.thinking) return qsTr("Considering the next move…")
if (backend.thinking) return backend.agent ? qsTr("%1 is thinking…").arg(backend.agentName) : qsTr("Considering the next move…")
if (backend.checked) return backend.whiteTurn ? qsTr("White is in check") : qsTr("Black is in check")
return backend.whiteTurn ? qsTr("White to move") : qsTr("Black to move")
}
Expand Down Expand Up @@ -224,10 +224,10 @@ ApplicationWindow {
spacing: 18
RowLayout {
Layout.fillWidth: true
Text { text: backend.computer ? qsTr("VS COMPUTER") : qsTr("TWO PLAYERS"); font.pixelSize: 10; font.letterSpacing: Qt.application.layoutDirection === Qt.RightToLeft ? 0 : 2; color: window.muted; Layout.fillWidth: true }
Text { text: backend.agent ? qsTr("VS AGENT") : backend.computer ? qsTr("VS COMPUTER") : qsTr("TWO PLAYERS"); font.pixelSize: 10; font.letterSpacing: Qt.application.layoutDirection === Qt.RightToLeft ? 0 : 2; color: window.muted; Layout.fillWidth: true }
Text { text: "●"; color: window.setColors[backend.pieceSet]; font.pixelSize: 9 }
}
Text { text: backend.computer ? window.difficultyNames[backend.difficulty] : qsTr("One board. Two minds."); color: theme.foreground; font.family: "serif"; font.pixelSize: 23; Layout.fillWidth: true; wrapMode: Text.WordWrap }
Text { text: backend.agent ? backend.agentName : backend.computer ? window.difficultyNames[backend.difficulty] : qsTr("One board. Two minds."); color: theme.foreground; font.family: "serif"; font.pixelSize: 23; Layout.fillWidth: true; wrapMode: Text.WordWrap }
Repeater {
model: [false,true]
Rectangle {
Expand All @@ -243,7 +243,7 @@ ApplicationWindow {
Text { text: modelData ? "♙" : "♟"; font.pixelSize: 29; color: theme.foreground }
ColumnLayout {
spacing: 3
Text { text: backend.computer ? (backend.humanWhite === modelData ? qsTr("You") : qsTr("Computer")) : (modelData ? qsTr("Player 1") : qsTr("Player 2")); color: theme.foreground; font.pixelSize: 14 }
Text { text: backend.computer ? (backend.humanWhite === modelData ? qsTr("You") : backend.agent ? backend.agentName : qsTr("Computer")) : (modelData ? qsTr("Player 1") : qsTr("Player 2")); color: theme.foreground; font.pixelSize: 14 }
Text { text: modelData ? qsTr("White") : qsTr("Black"); color: window.muted; font.pixelSize: 11 }
}
Item { Layout.fillWidth: true }
Expand Down Expand Up @@ -295,7 +295,9 @@ ApplicationWindow {
id: errorRow
anchors { left: parent.left; right: parent.right; verticalCenter: parent.verticalCenter; margins: 14 }
Text { text: backend.error; color: theme.foreground; wrapMode: Text.WordWrap; Layout.fillWidth: true }
FlatButton { text: qsTr("Dismiss"); onClicked: backend.dismissError() }
// A stalled agent keeps its message up until the player asks again, undoes, or starts over.
FlatButton { objectName: "askAgain"; text: qsTr("Ask again"); visible: backend.agentStalled; onClicked: backend.askAgentAgain() }
FlatButton { text: qsTr("Dismiss"); visible: !backend.agentStalled; onClicked: backend.dismissError() }
}
}
}
Expand All @@ -317,20 +319,23 @@ ApplicationWindow {
}
Material.roundedScale: theme.radius
onOpened: {
mode.currentIndex = backend.computer ? 0 : 1
backend.refreshAgent()
mode.currentIndex = backend.agent && backend.agentAvailable ? 2 : backend.computer ? 0 : 1
level.currentIndex = backend.difficulty
side.currentIndex = backend.humanWhite ? 0 : 1
mode.forceActiveFocus()
}
onAccepted: { backend.newGame(mode.currentIndex === 0,level.currentIndex,side.currentIndex === 0); board.resetCamera() }
onAccepted: { backend.newGame(mode.currentIndex !== 1,level.currentIndex,side.currentIndex === 0,mode.currentIndex === 2); board.resetCamera() }
contentItem: ColumnLayout {
LayoutMirroring.enabled: Qt.application.layoutDirection === Qt.RightToLeft
LayoutMirroring.childrenInherit: true
spacing: 16
Label { text: backend.canUndo ? qsTr("Starting a new match replaces the saved game.") : qsTr("Choose your opponent and settle in."); wrapMode: Text.WordWrap; Layout.fillWidth: true }
ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: mode; objectName: "mode"; Layout.fillWidth: true; model: [qsTr("Play against the computer"),qsTr("Two players · same device")]; Material.roundedScale: theme.radius }
ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: mode; objectName: "mode"; Layout.fillWidth: true; // The default Omarchy agent joins the list when it can answer on its own; it comes last so the others keep their places.
model: backend.agentAvailable ? [qsTr("Play against the computer"),qsTr("Two players · same device"),qsTr("Play against %1").arg(backend.agentName)]
: [qsTr("Play against the computer"),qsTr("Two players · same device")]; Material.roundedScale: theme.radius }
ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: level; Layout.fillWidth: true; model: window.difficultyNames; visible: mode.currentIndex === 0; Material.roundedScale: theme.radius }
ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: side; Layout.fillWidth: true; model: [qsTr("Play as White"),qsTr("Play as Black")]; visible: mode.currentIndex === 0; Material.roundedScale: theme.radius }
ComboBox { leftPadding: mirrored ? 40 : 16; rightPadding: mirrored ? 16 : 40; id: side; Layout.fillWidth: true; model: [qsTr("Play as White"),qsTr("Play as Black")]; visible: mode.currentIndex !== 1; Material.roundedScale: theme.radius }
}
}
Dialog {
Expand Down
147 changes: 147 additions & 0 deletions src/agentplayer.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
#include "agentplayer.h"

#include <QFile>
#include <QRegularExpression>
#include <QStandardPaths>

namespace {
QString coordinates(Chess::Move move) {
auto text = Chess::squareName(move.from) + Chess::squareName(move.to);
if (move.promotion) text += char(std::tolower(" PNBRQK"[move.promotion]));
return QString::fromStdString(text);
}
}

AgentPlayer::AgentPlayer(const QString &defaultsFile, QObject *parent) : QObject(parent), m_defaultsFile(defaultsFile) {
m_timeout.setSingleShot(true);
// Agents think for a while, and some start slowly; past this the turn is handed back to the player to decide.
m_timeout.setInterval(180000);
connect(&m_timeout,&QTimer::timeout,this,[this] { fail(tr("%1 took too long to answer.").arg(name())); });
}
AgentPlayer::~AgentPlayer() {
m_timeout.stop();
if (m_process) { m_process->disconnect(this); m_process->kill(); }
}

QString AgentPlayer::omarchyDefaultsFile() {
return QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + "/omarchy/defaults/agent";
}
QString AgentPlayer::id() const {
QFile file(m_defaultsFile);
if (m_defaultsFile.isEmpty() || !file.open(QIODevice::ReadOnly)) return {};
return QString::fromUtf8(file.readLine(256)).trimmed();
}
QString AgentPlayer::displayName(const QString &id) {
static const QHash<QString,QString> names{
{"claude","Claude Code"},{"codex","Codex"},{"opencode","OpenCode"},{"kilo","Kilo"},{"pi","Pi"},{"omp","Oh My Pi"},
{"grok","Grok"},{"crush","Crush"},{"copilot","GitHub Copilot"},{"cursor-agent","Cursor CLI"},{"agy","Antigravity"},
{"qwen","Qwen Code"},{"kimi","Kimi"},{"amp","Amp"},{"ori","Ori"},{"hermes","Hermes"},{"openclaw","OpenClaw"},
{"muse","Muse Code"},{"dsh","DeepSeek Harness"},{"mcode","MiniMax Code"},{"kiro-cli","Kiro CLI"},{"freebuff","Freebuff"},
{"devin","Devin CLI"},{"commandcode","Command Code"}};
return names.value(id,id);
}
QStringList AgentPlayer::command(const QString &id, const QString &prompt) {
// Each harness spells "answer once and exit" its own way. One that isn't here has no such mode we know of.
if (id == "claude" || id == "pi" || id == "omp" || id == "grok" || id == "copilot" || id == "cursor-agent" || id == "agy" || id == "qwen")
return {id,"-p",prompt};
// Codex refuses to run outside a git repository unless told the folder is fine.
if (id == "codex") return {id,"exec","--skip-git-repo-check",prompt};
if (id == "opencode" || id == "kilo" || id == "crush") return {id,"run",prompt};
if (id == "kimi") return {id,"--prompt",prompt};
if (id == "amp") return {id,"--execute",prompt};
if (id == "ori") return {id,"code","--prompt",prompt};
return {};
}
bool AgentPlayer::available() const {
if (!m_override.isEmpty()) return !id().isEmpty();
const auto argv = command(id(),{});
return !argv.isEmpty() && !QStandardPaths::findExecutable(argv.first()).isEmpty();
}
QString AgentPlayer::prompt(const Chess::Position &position, const QStringList &history, const QString &rejected) {
QStringList played;
for (int i = 0; i < history.size(); ++i) played << (i % 2 ? history[i] : QString::number(i / 2 + 1) + ". " + history[i]);
QStringList legal;
for (auto move : position.legal()) legal << coordinates(move);
QString text = QString("You are playing chess as %1 and it is your move.\n\n").arg(position.white ? "White" : "Black");
text += "Position (FEN): " + QString::fromStdString(position.fen()) + "\n";
text += "Moves so far: " + (played.isEmpty() ? QString("none") : played.join(' ')) + "\n";
text += "Your legal moves: " + legal.join(' ') + "\n\n";
if (!rejected.isEmpty()) text += "Your last answer, \"" + rejected.left(80) + "\", named no move from that list.\n";
text += "Pick the strongest move from the list and reply with that move alone, written exactly as it is in the list, such as " + legal.value(0) +
". Use no tools, read no files, and give no explanation.";
return text;
}
bool AgentPlayer::parse(const QString &answer, const Chess::Position &position, Chess::Move *move) {
const auto legal = position.legal();
int best = -1;
// The last move named wins: an agent that thinks aloud ends on its choice.
static const QRegularExpression coordinate("(?<![a-z0-9])([a-h][1-8][a-h][1-8][qrbn]?)(?![a-z0-9])",QRegularExpression::CaseInsensitiveOption);
for (auto found = coordinate.globalMatch(answer); found.hasNext();) {
const auto match = found.next();
for (auto candidate : legal) if (coordinates(candidate) == match.captured(1).toLower() && match.capturedStart() > best) { best = match.capturedStart(); *move = candidate; }
}
if (best >= 0) return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 The final choice is ignored

parse() returns after finding a legal coordinate move, before checking later moves written as SAN. After e4, an answer such as “I considered e7e5, but my move is Nf6” plays e5, not the final choice. Compare both forms before choosing the last legal move.

for (auto candidate : legal) {
QString san = QString::fromStdString(position.san(candidate));
san.remove('+').remove('#');
const QRegularExpression written("(?<![A-Za-z0-9])" + QRegularExpression::escape(san) + "(?![A-Za-z0-9=])");
for (auto found = written.globalMatch(answer); found.hasNext();) {
const auto match = found.next();
if (match.capturedStart() > best) { best = match.capturedStart(); *move = candidate; }
Comment on lines +87 to +90

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 The wrong castle is played

When both castles are legal, answering O-O-O selects O-O. The shorter pattern matches the start of O-O-O because its boundary allows -. legal() lists the short castle first, and the strict position comparison prevents the full match from replacing it. Match the whole castle name and add a test with both castles legal.

}
}
return best >= 0;
}
void AgentPlayer::ask(const Chess::Position &position, const QStringList &history) {
cancel();
m_position = position; m_history = history; m_retried = false;
start({});
}
void AgentPlayer::start(const QString &rejected) {
m_asked = name();
const QString text = prompt(m_position,m_history,rejected);
QStringList argv = m_override.isEmpty() ? command(id(),text) : m_override + QStringList{text};
if (argv.isEmpty()) { fail(tr("%1 can't answer on its own yet. Choose another default agent, or play the computer.").arg(m_asked)); return; }
m_process = std::make_unique<QProcess>();
m_process->setWorkingDirectory(m_workspace.path());
// Nothing to read on its input, so an agent that waits for one sees the end of it at once.
m_process->setStandardInputFile(QProcess::nullDevice());
connect(m_process.get(),&QProcess::finished,this,&AgentPlayer::finish);
connect(m_process.get(),&QProcess::errorOccurred,this,[this](QProcess::ProcessError error) {
if (error == QProcess::FailedToStart) fail(tr("%1 is not installed.").arg(m_asked));
});
m_timeout.start();
m_process->start(argv.first(),argv.mid(1));
}
void AgentPlayer::finish(int exitCode, QProcess::ExitStatus status) {
if (!m_process) return;
m_timeout.stop();
const QString answer = QString::fromUtf8(m_process->readAllStandardOutput());
const QString complaint = QString::fromUtf8(m_process->readAllStandardError()).trimmed();
m_process.release()->deleteLater();
Chess::Move move;
if (status == QProcess::NormalExit && exitCode == 0 && parse(answer,m_position,&move)) { emit answered(move); return; }
if (status != QProcess::NormalExit || exitCode != 0) {
// The agent's own last words say why: not signed in, out of credit, offline.
const QString why = complaint.isEmpty() ? answer.trimmed() : complaint;
fail(why.isEmpty() ? tr("%1 stopped without answering.").arg(m_asked) : tr("%1 stopped without answering: %2").arg(m_asked,why.section('\n',-1).left(200)));
return;
}
if (!m_retried) { m_retried = true; start(answer.trimmed()); return; }
fail(tr("%1 did not answer with a legal move.").arg(m_asked));
}
void AgentPlayer::fail(const QString &reason) {
cancel();
emit failed(reason);
}
void AgentPlayer::cancel() {
m_timeout.stop();
if (!m_process) return;
auto process = m_process.release();
process->disconnect(this);
// Asked to stop, then stopped: the process is given its own time to end rather than blocking the window on it.
connect(process,&QProcess::finished,process,&QObject::deleteLater);
if (process->state() == QProcess::NotRunning) { process->deleteLater(); return; }
process->terminate();
QTimer::singleShot(2000,process,&QProcess::kill);
}
55 changes: 55 additions & 0 deletions src/agentplayer.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#pragma once

#include "chess.h"
#include <QObject>
#include <QProcess>
#include <QStringList>
#include <QTemporaryDir>
#include <QTimer>
#include <memory>

// Plays a side by asking the user's default Omarchy agent for each move. Omarchy only opens agents in a
// terminal, so the agent's own one-shot mode is run here: one prompt in, one answer out.
class AgentPlayer : public QObject {
Q_OBJECT
public:
// Tests pass their own defaults file; an empty path means no agent is chosen.
explicit AgentPlayer(const QString &defaultsFile, QObject *parent = nullptr);
~AgentPlayer() override;
// Where `omarchy default agent` records the choice.
static QString omarchyDefaultsFile();
// The chosen agent's id as Omarchy writes it ("claude", "codex"), read fresh so a new choice is seen.
QString id() const;
QString name() const { return displayName(id()); }
// Whether the chosen agent can answer on its own and is installed.
bool available() const;
static QString displayName(const QString &id);
// The agent's one-shot command for a prompt, or nothing when it has no such mode we know of.
static QStringList command(const QString &id, const QString &prompt);
static QString prompt(const Chess::Position &position, const QStringList &history, const QString &rejected = {});
// The last legal move the answer names, in coordinates (e7e5) or as written in the game (Nf6).
static bool parse(const QString &answer, const Chess::Position &position, Chess::Move *move);
void setDefaultsFile(const QString &path) { m_defaultsFile = path; }
// Tests stand a script in for the agent: the prompt is added as its last argument.
void setCommandOverride(const QStringList &command) { m_override = command; }
void setTimeout(int milliseconds) { m_timeout.setInterval(milliseconds); }
void ask(const Chess::Position &position, const QStringList &history);
void cancel();
signals:
void answered(Chess::Move move);
void failed(const QString &reason);
private:
void start(const QString &rejected);
void finish(int exitCode, QProcess::ExitStatus status);
void fail(const QString &reason);
QString m_defaultsFile;
QStringList m_override;
std::unique_ptr<QProcess> m_process;
// The agent works in an empty folder of its own, never among the user's files.
QTemporaryDir m_workspace;
QTimer m_timeout;
Chess::Position m_position;
QStringList m_history;
QString m_asked;
bool m_retried = false;
};
Loading
Loading