feat: update readme & agent TUI reliability (#239)

This commit is contained in:
Carlos Florêncio
2026-02-17 22:59:53 +00:00
committed by GitHub
parent 1f4170da8b
commit 90bec9aaa0
47 changed files with 2129 additions and 911 deletions
+3 -3
View File
@@ -272,13 +272,13 @@ lib/api/domains/ # API clients
Static analysis runs in CI and pre-commit. New code **must** stay within these limits:
**Go** (`apps/backend/.golangci.yml` — errors on new code only):
**Go** (`apps/backend/.golangci.yml` - errors on new code only):
- Functions: **≤80 lines**, **≤50 statements**
- Cyclomatic complexity: **≤15** · Cognitive complexity: **≤30**
- Nesting depth: **≤5** · Naked returns only in functions **≤30 lines**
- No duplicated blocks (**≥150 tokens**) · Repeated strings → constants (**≥3 occurrences**)
**TypeScript** (`apps/web/eslint.config.mjs` — warnings, will become errors):
**TypeScript** (`apps/web/eslint.config.mjs` - warnings, will become errors):
- Files: **≤600 lines** · Functions: **≤100 lines**
- Cyclomatic complexity: **≤15** · Cognitive complexity: **≤20**
- Nesting depth: **≤4** · Parameters: **≤5**
@@ -311,7 +311,7 @@ Static analysis runs in CI and pre-commit. New code **must** stay within these l
## Maintaining This File
This file is read by AI coding agents (Claude Code via `CLAUDE.md` symlink, Codex via `AGENTS.md`). If your changes make any section of this file outdated or inaccurate — e.g., you add/remove/rename packages, change architectural patterns, add new adapters, modify store slices, or change conventions — **update the relevant sections of this file as part of the same PR**. Keep descriptions concise and factual. Do not add speculative or aspirational content.
This file is read by AI coding agents (Claude Code via `CLAUDE.md` symlink, Codex via `AGENTS.md`). If your changes make any section of this file outdated or inaccurate - e.g., you add/remove/rename packages, change architectural patterns, add new adapters, modify store slices, or change conventions - **update the relevant sections of this file as part of the same PR**. Keep descriptions concise and factual. Do not add speculative or aspirational content.
---
+39
View File
@@ -0,0 +1,39 @@
# Contributing to Kandev
Contributions are welcome! This document covers the basics.
## Important
You must understand the code you submit. You're welcome to use AI tools to help write code, but every PR will be reviewed by a human maintainer and the feature you're contributing should be manually tested. If you can't explain what your code does and why, it's not ready to submit.
## How to Contribute
1. **Fork and branch.** Create a feature branch from `main`.
2. **Keep PRs focused.** One logical change per PR. Small PRs get reviewed faster.
3. **Test your changes.** Run `make typecheck test lint` before submitting. Manually verify that your feature works end-to-end, add screenshots or recordings to the PR if it has a UI component.
## Bug Reports
Search [existing issues](https://github.com/cflynn7/kandev/issues) first. If your bug isn't already reported, open one with:
- Steps to reproduce
- Expected vs actual behavior
- Environment details (OS, browser, agent type)
## Feature Ideas
Open an issue describing the feature and the problem it solves. Keep it concise.
## Code Quality
New code must pass the existing linters and tests:
```bash
make test # Backend + web tests
make lint # Backend + web linters
make typecheck # TypeScript type checking
```
## License
By contributing, you agree that your contributions will be licensed under the [AGPL-3.0](LICENSE) license.
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+115 -203
View File
@@ -1,227 +1,152 @@
# Kandev - Kanban Board with AI Agent Orchestration
# Kandev
A Kanban board system that integrates AI agent orchestration capabilities with **real-time Agent Communication Protocol (ACP) streaming**, allowing tasks to be automatically executed by AI agents running in isolated Docker containers.
Manage tasks. Orchestrate agents. Review changes. Ship value.
## Overview
[Workflows](docs/workflow-tips.md) | [Roadmap](docs/roadmap.md) | [Contributing](CONTRIBUTING.md) | [Architecture](docs/ARCHITECTURE.md)
Kandev combines traditional Kanban task management with automated AI agent execution and real-time feedback streaming. Users create tasks on a Kanban board, and when configured with an AI agent type, the system automatically launches Docker containers to execute those tasks against specified code repositories. **Real-time progress, logs, and results are streamed from agents to the frontend via WebSocket connections.**
<!-- TODO: add screenshot -->
### Key Features
## What
- **Kanban Board Management**: Create and manage tasks across multiple boards with columns
- **AI Agent Orchestration**: Launch AI agents (Augment Agent) to execute tasks
- **Real-Time ACP Streaming**: Live progress updates, logs, and results streamed from agents
- **Session Resumption**: Agents can resume previous conversations using session IDs
- **Docker Isolation**: Each agent runs in an isolated Docker container with resource limits
- **Repository Integration**: Agents can work on code repositories with host credentials
- **Host Credential Mounting**: Secure read-only mounting of SSH keys and Git credentials
- **SQLite Persistence**: Lightweight file-based database for task and board storage
- **Local Deployment**: Designed for client machines with minimal dependencies
## Architecture
Organize work across kanban and pipeline views with opinionated workflows. Assign agents from any provider, and review their output in an integrated workspace - file editor, file tree, terminal, browser preview, and git changes in one place. Terminal agent TUIs are great for running agents, but reviewing and iterating on changes there doesn't scale.
The system runs as a **unified Go binary** that includes:
Run it locally or self-host it on your own infrastructure and access it from anywhere via [Tailscale](https://tailscale.com/) or any VPN.
- **Task Service**: Manages tasks, boards, and columns with SQLite persistence
- **Agent Manager**: Manages Docker container lifecycle and ACP message streaming
- **Orchestrator**: Coordinates agent launches and monitors execution
- **WebSocket API**: Real-time bidirectional communication for all operations (Port 8080)
Open source, multi-provider, no telemetry, not tied to any cloud.
### Agent Communication Protocol (ACP)
## Vision
ACP is a JSON-based streaming protocol that enables real-time communication between AI agents and the backend:
> **Humans stay in control.** Define tasks, build agentic workflows with gates, review every change, decide what ships.
```
Agent Container (stdout) → Agent Manager → Event Bus → API
```
- **Review-first** - Humans support production systems. We need to understand (yet) and trust the code that gets deployed.
- **Your workflow** - Every team is different, and not every developer uses AI the same way. Define workflows once, share them across the team, and give everyone a consistent process for working with agents - regardless of experience level.
- **Remote agents** - Running multiple agents on a large codebase can quickly saturate a local machine. The goal is a single control plane: offload execution to servers, orchestrate from anywhere, including your phone.
**Message Types**: `progress`, `log`, `result`, `error`, `status`, `heartbeat`
<details>
<summary><strong>Where this is heading</strong></summary>
See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for detailed architecture documentation.
While agents can already plan, implement, test, and deploy autonomously with the right workflows, we don't yet trust their output enough for production-grade software without human review. Crossing that trust threshold will fundamentally transform our industry.
## Supported Agent Types
</details>
1. **Augment Agent** (`augment-agent`)
- Uses Auggie CLI for code analysis, generation, debugging, refactoring
- Native ACP support via stdout JSON streaming
- Session resumption for multi-turn conversations
## Features
## Technology Stack
- **Multi-agent support** - Claude Code, Codex, GitHub Copilot, Gemini CLI, Amp, Auggie, OpenCode
- **Integrated workspace** - Built-in terminal, code editor with LSP, git changes panel, and chat in one IDE-like view
- **Kanban task management** - Drag-and-drop boards, columns, and workflow automation
- **Agentic workflows** - Multi-step pipelines that chain agents through automated task routing. See [docs/workflows.md](docs/workflow-tips.md)
- **CLI passthrough** - Drop into raw agent CLI mode for direct terminal interaction with any supported agent, leverage the full power of their TUIs
- **Workspace isolation** - Git worktrees prevent concurrent agents from conflicting
- **Flexible runtimes** - Run agents as local processes or in isolated Docker containers
- **Session management** - Resume and review agent conversations
- **Stats** - Track your productivity with stats on the completed tasks, agent turns, etc
- **Backend**: Go 1.21+
- **Database**: SQLite (with WAL mode)
- **Container Runtime**: Docker
- **Web Framework**: Gin
- **Logging**: Zap (structured logging)
- **Deployment**: Single binary for client machines
## Supported Agents
| Agent | Default Model | Other Models | Protocol |
|-------|--------------|--------------|----------|
| **Claude Code** | Sonnet 4.5 | Opus 4.6, Opus 4.5, Haiku 4.5 | stream-json |
| **Codex** | GPT-5.2 Codex | GPT-5.1 Codex Max, GPT-5.1 Codex Mini, GPT-5.2 | Codex |
| **GitHub Copilot** | GPT-4.1 | GPT-5.2, Claude Sonnet 4.5, Gemini 3 Pro, +10 more | Copilot SDK |
| **Gemini CLI** | Gemini 3 Flash | Gemini 3 Pro | ACP |
| **Amp** | Smart Mode | Deep Mode | stream-json |
| **Auggie** | Sonnet 4.5 | Opus 4.5, GPT-5.1, GPT-5, Haiku 4.5 (dynamic) | ACP |
| **OpenCode** | GPT-5 Nano | Claude Sonnet 4, Opus 4, etc (dynamic) | REST/SSE |
> **CLI Passthrough mode** - we should be able to support any agent that has a CLI interface, even if they don't have an official API or SDK. The agent runs in a terminal session and we pass input/output through a websocket connection. If your agent isn't supported yet, open an issue or submit a PR with the integration. See [Adding a New Agent CLI](docs/add-agent-cli.md) for a step-by-step guide.
## Quick Start
### Prerequisites
> **Beta** - Under active development. Expect rough edges and breaking changes. Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for details.
- Go 1.21 or higher
- Docker
- Augment CLI credentials (`~/.augment/session.json`)
### Build and Run
#### NPX Launcher (recommended)
### NPX (recommended)
```bash
npx kandev
```
This downloads prebuilt backend + frontend bundles and starts them locally.
This downloads prebuilt backend + frontend bundles and starts them locally. The worktrees and sqlite db will be created in `~/.kandev` by default. Should work on macOS, Linux, and Windows (WSL or native).
#### From Source
### From Source
```bash
cd apps/backend
# Clone the repository
git clone git@github.com:kdlbs/kandev.git
cd kandev
# Build the binary
make build
# Run the server (creates kandev.db in current directory)
./bin/kandev
# Or specify a custom database path
KANDEV_DB_PATH=/path/to/kandev.db ./bin/kandev
# Start in production mode
make start
```
### WebSocket API Usage
**Prerequisites:** Go 1.26+, Node.js 18+, pnpm, Docker (optional - needed for container runtimes)
**Connection**: `ws://localhost:8080/ws`
## High level architecture
#### Message Envelope
```mermaid
graph LR
UI[Web UI] --> Backend
```json
{
"id": "correlation-uuid",
"type": "request|response|notification|error",
"action": "action.name",
"payload": {},
"timestamp": "2026-01-10T10:30:00Z"
}
Backend["Backend (Orchestrator)"]
Backend --> W1 & W2
subgraph W1[Local Process]
Agent1[Agent CLI] --- WT1[Worktree]
end
subgraph W2[Docker Container]
Agent2[Agent CLI] --- WT2[Worktree]
end
```
#### Key Message Actions
We also want to add support for these remote runtimes:
- Remote SSH - run agents on remote servers over SSH, using docker or local processes with workspace isolation
- K8s operator - run agents in a Kubernetes cluster, with auto-scaling and resource management.
- `board.create` - Create board
- `board.list` - List boards
- `column.create` - Create column
- `task.create` - Create task
- `agent.launch` - Launch agent
- `agent.status` - Get agent status
- `orchestrator.start` - Start task execution
<details>
<summary><strong>Development</strong></summary>
#### Example Usage (JavaScript)
```javascript
const ws = new WebSocket('ws://localhost:8080/ws');
// Create a board
ws.send(JSON.stringify({
id: crypto.randomUUID(),
type: 'request',
action: 'board.create',
payload: { name: 'My Project', description: 'Project tasks' }
}));
// Create a task
ws.send(JSON.stringify({
id: crypto.randomUUID(),
type: 'request',
action: 'task.create',
payload: {
board_id: '{board_id}',
column_id: '{column_id}',
title: 'Fix login bug',
description: 'Users cannot login'
}
}));
// Launch an agent
ws.send(JSON.stringify({
id: crypto.randomUUID(),
type: 'request',
action: 'agent.launch',
payload: {
task_id: '{task_id}',
agent_type: 'augment-agent',
workspace_path: '/path/to/project',
env: {
AUGMENT_SESSION_AUTH: '...',
TASK_DESCRIPTION: 'What is 2+2?'
}
}
}));
// Handle responses and notifications
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'response') {
console.log('Response:', msg.payload);
} else if (msg.type === 'notification') {
// Real-time updates: acp.progress, acp.log, task.updated, etc.
console.log('Notification:', msg.action, msg.payload);
}
};
```
See [apps/backend/NEXT_STEPS.md](apps/backend/NEXT_STEPS.md) for detailed API reference and next steps.
## Project Structure
### Project Structure
```
kandev/
├── apps/
│ ├── backend/ # Go backend services
│ │ ├── cmd/kandev/ # Unified binary entry point
│ │ ├── internal/
│ │ │ ├── agent/ # Agent manager (docker, lifecycle, registry, api)
│ │ │ ├── task/ # Task service (models, repository, service, api)
│ │ │ ├── orchestrator/ # Orchestrator service
│ │ │ ├── events/ # In-memory event bus
│ │ │ └── common/ # Shared utilities (logger, config)
│ │ ├── pkg/acp/ # ACP protocol types
│ │ ├── dockerfiles/ # Agent container Dockerfiles
│ │ └── Makefile
│ └── web/ # Frontend application
├── docs/ # Architecture and planning docs
├── deployments/ # Deployment configs
└── scripts/ # Utility scripts (including e2e-test.sh)
apps/
├── backend/ # Go backend (orchestrator, lifecycle, agentctl, WS gateway)
├── web/ # Next.js frontend (SSR, Zustand, real-time subscriptions)
├── cli/ # CLI tool (npx kandev launcher)
└── packages/ # Shared UI components & types
```
## Configuration
### Prerequisites
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `KANDEV_DB_PATH` | `./kandev.db` | SQLite database file path |
| `PORT` | `8080` | HTTP server port |
- Go 1.21+
- Node.js 18+
- pnpm
- Docker (optional)
## Development
### Running Dev Servers
```bash
cd apps/backend
# Start everything (backend + frontend with auto ports)
make dev
# Build
make build
# Run tests
make test
# Format code
go fmt ./...
# Lint
go vet ./...
# Or run separately
make dev-backend # Backend on :8080
make dev-web # Frontend on :3000
```
## Pre-commit Hooks
### Testing & Linting
We use `pre-commit` to run the backend tests, web tests, and web lint before commits.
```bash
make test # Run all tests (backend + web)
make lint # Run all linters
make typecheck # TypeScript type checking
make fmt # Format all code
```
### Install
### Pre-commit Hooks
```bash
# Install pre-commit (https://pre-commit.com/#install)
@@ -231,43 +156,30 @@ pipx install pre-commit
pre-commit install
```
### Run Manually
</details>
```bash
# Run all hooks once
pre-commit run --all-files
```
## Comparison to Other Tools
### Hooks Config
There are a couple similar tools in this space, and new ones appearing everyday. Here's what sets this one apart:
The hooks are defined in `.pre-commit-config.yaml` and run these Makefile targets:
- **Server-first architecture** - Not a desktop app. Runs as a server you can access from any device, including your phone. Start a task away from your computer and check in on it later.
- **Remote runtimes** - Run agents on remote servers and Docker hosts, not just your local machine.
- **Multi-provider** - Use Claude Code, Codex, Copilot, Gemini, Amp, Auggie, and OpenCode side by side. Not locked to one vendor.
- **CLI passthrough and chat** - Interact with agents through structured chat messages or drop into raw CLI mode for full agent TUI capabilities.
- **Open source and self-hostable** - No vendor lock-in, no telemetry, runs on your infrastructure.
- `make test-backend`
- `make test-web`
- `make lint-web`
## Contributing
## Project Status
Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a PR.
✅ **Core Features Working**
- [x] SQLite persistence for boards, columns, and tasks
- [x] Agent lifecycle management with Docker
- [x] ACP message streaming from containers
- [x] Session resumption for multi-turn agent conversations
- [x] WebSocket-first API for all operations
- [x] Real-time bidirectional communication
🚧 **In Progress**
- [ ] Authentication and authorization
- [ ] Frontend UI
See [apps/backend/NEXT_STEPS.md](apps/backend/NEXT_STEPS.md) for the complete roadmap.
## License
[To be determined]
See the [issue tracker](https://github.com/kdlbs/kandev/issues) for open tasks.
## Acknowledgments
Built with Go and inspired by modern DevOps practices and AI-assisted development workflows.
Built with these excellent open-source projects:
[Monaco Editor](https://microsoft.github.io/monaco-editor/) · [Tiptap](https://tiptap.dev/) · [xterm.js](https://xtermjs.org/) · [dockview](https://dockview.dev/) · [CodeMirror](https://codemirror.net/) · [dnd-kit](https://dndkit.com/) · [Mermaid](https://mermaid.js.org/) · [Recharts](https://recharts.org/) · [TanStack Table](https://tanstack.com/table) · [Zustand](https://zustand.docs.pmnd.rs/) · [Shadcn/UI](https://ui.shadcn.com/) · [Radix UI](https://www.radix-ui.com/) · [Tailwind CSS](https://tailwindcss.com/)
## License
[AGPL-3.0](LICENSE)
@@ -1,92 +0,0 @@
package agents
import (
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/acp"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/codex"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/opencode"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/streamjson"
)
// Adapter wrappers convert transport-specific adapters to the common AgentAdapter interface.
// These handle the type conversion between transport-specific AgentInfo and adapter.AgentInfo.
// --- ACP ---
type acpAdapterWrapper struct {
*acp.Adapter
}
func newACPAdapterWrapper(a *acp.Adapter) *acpAdapterWrapper {
return &acpAdapterWrapper{Adapter: a}
}
func (w *acpAdapterWrapper) GetAgentInfo() *adapter.AgentInfo {
info := w.Adapter.GetAgentInfo()
if info == nil {
return nil
}
return &adapter.AgentInfo{Name: info.Name, Version: info.Version}
}
// --- Stream JSON (Claude Code, Amp) ---
type streamJSONAdapterWrapper struct {
*streamjson.Adapter
}
func newStreamJSONAdapterWrapper(a *streamjson.Adapter) *streamJSONAdapterWrapper {
return &streamJSONAdapterWrapper{Adapter: a}
}
func (w *streamJSONAdapterWrapper) GetAgentInfo() *adapter.AgentInfo {
info := w.Adapter.GetAgentInfo()
if info == nil {
return nil
}
return &adapter.AgentInfo{Name: info.Name, Version: info.Version}
}
func (w *streamJSONAdapterWrapper) SetStderrProvider(provider adapter.StderrProvider) {
w.Adapter.SetStderrProvider(provider)
}
// --- Codex ---
type codexAdapterWrapper struct {
*codex.Adapter
}
func newCodexAdapterWrapper(a *codex.Adapter) *codexAdapterWrapper {
return &codexAdapterWrapper{Adapter: a}
}
func (w *codexAdapterWrapper) GetAgentInfo() *adapter.AgentInfo {
info := w.Adapter.GetAgentInfo()
if info == nil {
return nil
}
return &adapter.AgentInfo{Name: info.Name, Version: info.Version}
}
func (w *codexAdapterWrapper) SetStderrProvider(provider adapter.StderrProvider) {
w.Adapter.SetStderrProvider(provider)
}
// --- OpenCode ---
type openCodeAdapterWrapper struct {
*opencode.Adapter
}
func newOpenCodeAdapterWrapper(a *opencode.Adapter) *openCodeAdapterWrapper {
return &openCodeAdapterWrapper{Adapter: a}
}
func (w *openCodeAdapterWrapper) GetAgentInfo() *adapter.AgentInfo {
info := w.Adapter.GetAgentInfo()
if info == nil {
return nil
}
return &adapter.AgentInfo{Name: info.Name, Version: info.Version}
}
@@ -9,8 +9,6 @@ import (
"errors"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -37,9 +35,6 @@ type Agent interface {
DefaultModel() string
ListModels(ctx context.Context) (*ModelList, error)
// --- Protocol ---
CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error)
// --- Execution ---
BuildCommand(opts CommandOptions) Command
@@ -132,7 +127,6 @@ type RuntimeConfig struct {
RequiredEnv []string
Mounts []MountTemplate
ResourceLimits ResourceLimits
Capabilities []string
SessionConfig SessionConfig
Protocol agent.Protocol
ModelFlag Param // e.g. NewParam("--model", "{model}")
@@ -206,11 +200,6 @@ type PassthroughConfig struct {
// DefaultBufferMaxBytes is the default maximum buffer size for passthrough mode (2 MB).
const DefaultBufferMaxBytes int64 = 2 * 1024 * 1024
// DefaultCapabilities is the standard set of capabilities shared by most agents.
var DefaultCapabilities = []string{
"code_generation", "code_review", "refactoring", "testing", "shell_execution",
}
// DefaultResourceLimits is the standard resource limit set shared by most agents.
var DefaultResourceLimits = ResourceLimits{
MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour,
@@ -5,8 +5,6 @@ import (
_ "embed"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -87,10 +85,6 @@ func (a *Amp) ListModels(ctx context.Context) (*ModelList, error) {
return &ModelList{Models: ampStaticModels(), SupportsDynamic: false}, nil
}
func (a *Amp) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return adapter.NewAmpAdapter(cfg, log), nil
}
func (a *Amp) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", "@sourcegraph/amp@latest", "--execute", "--stream-json", "--stream-json-input").
Model(NewParam("-m", "{model}"), opts.Model).
@@ -105,7 +99,6 @@ func (a *Amp) Runtime() *RuntimeConfig {
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
Capabilities: []string{"code_generation", "code_review", "refactoring", "testing", "shell_execution"},
Protocol: agent.ProtocolAmp,
ModelFlag: NewParam("-m", "{model}"),
SessionConfig: SessionConfig{
@@ -8,9 +8,6 @@ import (
"strings"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/acp"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -91,10 +88,6 @@ func (a *Auggie) ListModels(ctx context.Context) (*ModelList, error) {
return &ModelList{Models: models, SupportsDynamic: true}, nil
}
func (a *Auggie) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return newACPAdapterWrapper(acp.NewAdapter(cfg.ToSharedConfig(), log)), nil
}
func (a *Auggie) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", "@augmentcode/auggie@0.15.0", "--acp").
Model(NewParam("--model", "{model}"), opts.Model).
@@ -117,7 +110,6 @@ func (a *Auggie) Runtime() *RuntimeConfig {
{Source: "{workspace}", Target: "/workspace"},
},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
Capabilities: []string{"code_generation", "code_review", "refactoring", "testing", "shell_execution"},
Protocol: agent.ProtocolACP,
ModelFlag: NewParam("--model", "{model}"),
WorkspaceFlag: "--workspace-root",
@@ -5,9 +5,6 @@ import (
_ "embed"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/streamjson"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -80,10 +77,6 @@ func (a *ClaudeCode) ListModels(ctx context.Context) (*ModelList, error) {
return &ModelList{Models: claudeCodeStaticModels(), SupportsDynamic: false}, nil
}
func (a *ClaudeCode) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return newStreamJSONAdapterWrapper(streamjson.NewAdapter(cfg.ToSharedConfig(), log)), nil
}
func (a *ClaudeCode) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", "@anthropic-ai/claude-code@2.1.29",
"-p", "--output-format=stream-json", "--input-format=stream-json",
@@ -106,7 +99,6 @@ func (a *ClaudeCode) Runtime() *RuntimeConfig {
RequiredEnv: []string{"ANTHROPIC_API_KEY"},
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
Capabilities: []string{"code_generation", "code_review", "refactoring", "testing", "shell_execution"},
Protocol: agent.ProtocolClaudeCode,
ModelFlag: NewParam("--model", "{model}"),
SessionConfig: SessionConfig{
@@ -5,9 +5,6 @@ import (
_ "embed"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/codex"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -75,10 +72,6 @@ func (a *Codex) ListModels(ctx context.Context) (*ModelList, error) {
return &ModelList{Models: codexStaticModels(), SupportsDynamic: false}, nil
}
func (a *Codex) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return newCodexAdapterWrapper(codex.NewAdapter(cfg.ToSharedConfig(), log)), nil
}
func (a *Codex) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", "@openai/codex@0.98.0", "app-server").
Model(NewParam("-c", "model=\"{model}\""), opts.Model).
@@ -100,7 +93,6 @@ func (a *Codex) Runtime() *RuntimeConfig {
{Source: "{home}/.codex", Target: "/root/.codex"},
},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
Capabilities: []string{"code_generation", "code_review", "refactoring", "testing", "shell_execution"},
Protocol: agent.ProtocolCodex,
ModelFlag: NewParam("-c", "model=\"{model}\""),
SessionConfig: SessionConfig{
@@ -5,8 +5,6 @@ import (
_ "embed"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -87,10 +85,6 @@ func (a *Copilot) ListModels(ctx context.Context) (*ModelList, error) {
return &ModelList{Models: copilotStaticModels(), SupportsDynamic: false}, nil
}
func (a *Copilot) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return adapter.NewCopilotAdapter(cfg, log), nil
}
func (a *Copilot) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", "@github/copilot@0.0.406", "--server", "--log-level", "error").
Model(NewParam("--model", "{model}"), opts.Model).
@@ -106,7 +100,6 @@ func (a *Copilot) Runtime() *RuntimeConfig {
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
Capabilities: []string{"code_generation", "code_review", "refactoring", "testing", "shell_execution"},
Protocol: agent.ProtocolCopilot,
ModelFlag: NewParam("--model", "{model}"),
SessionConfig: SessionConfig{
@@ -5,9 +5,6 @@ import (
_ "embed"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/acp"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -90,10 +87,6 @@ func (a *Gemini) ListModels(ctx context.Context) (*ModelList, error) {
return &ModelList{Models: geminiStaticModels(), SupportsDynamic: false}, nil
}
func (a *Gemini) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return newACPAdapterWrapper(acp.NewAdapter(cfg.ToSharedConfig(), log)), nil
}
func (a *Gemini) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", "@google/gemini-cli@0.25.2", "--experimental-acp").
Model(NewParam("--model", "{model}"), opts.Model).
@@ -108,7 +101,6 @@ func (a *Gemini) Runtime() *RuntimeConfig {
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
Capabilities: []string{"code_generation", "code_review", "refactoring", "testing", "shell_execution"},
Protocol: agent.ProtocolACP,
ModelFlag: NewParam("--model", "{model}"),
SessionConfig: SessionConfig{
@@ -5,9 +5,6 @@ import (
_ "embed"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/streamjson"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -59,10 +56,6 @@ func (a *MockAgent) ListModels(ctx context.Context) (*ModelList, error) {
return &ModelList{Models: mockStaticModels(), SupportsDynamic: false}, nil
}
func (a *MockAgent) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return newStreamJSONAdapterWrapper(streamjson.NewAdapter(cfg.ToSharedConfig(), log)), nil
}
func (a *MockAgent) BuildCommand(opts CommandOptions) Command {
binary := "mock-agent"
if a.binaryPath != "" {
@@ -80,7 +73,6 @@ func (a *MockAgent) Runtime() *RuntimeConfig {
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 512, CPUCores: 0.5, Timeout: time.Hour},
Capabilities: []string{"code_generation", "code_review", "refactoring", "testing", "shell_execution"},
Protocol: agent.ProtocolClaudeCode,
ModelFlag: NewParam("--model", "{model}"),
SessionConfig: SessionConfig{
@@ -6,9 +6,6 @@ import (
"strings"
"time"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/agentctl/server/adapter/transport/opencode"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/pkg/agent"
)
@@ -95,10 +92,6 @@ func (a *OpenCode) ListModels(ctx context.Context) (*ModelList, error) {
return &ModelList{Models: models, SupportsDynamic: true}, nil
}
func (a *OpenCode) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return newOpenCodeAdapterWrapper(opencode.NewAdapter(cfg.ToSharedConfig(), log)), nil
}
func (a *OpenCode) BuildCommand(opts CommandOptions) Command {
return Cmd("npx", "-y", "opencode-ai@1.1.25", "serve", "--hostname", "127.0.0.1", "--port", "0").Build()
}
@@ -110,7 +103,6 @@ func (a *OpenCode) Runtime() *RuntimeConfig {
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: ResourceLimits{MemoryMB: 4096, CPUCores: 2.0, Timeout: time.Hour},
Capabilities: []string{"code_generation", "code_review", "refactoring", "testing", "shell_execution"},
Protocol: agent.ProtocolOpenCode,
SessionConfig: SessionConfig{
NativeSessionResume: true,
@@ -0,0 +1,129 @@
package agents
import (
"context"
"time"
"github.com/kandev/kandev/pkg/agent"
)
// TUIAgentConfig is a declarative specification for CLI passthrough / TUI agents.
// TUI tools like k9s or lazydocker can be defined in ~20 lines instead of ~90.
type TUIAgentConfig struct {
// Required
AgentID string
AgentName string
Command string // binary name, e.g. "claude"
Desc string
// Optional (zero values get sensible defaults)
Display string // defaults to AgentName
Order *int // defaults to 99 when nil; use a pointer so 0 is a valid explicit value
Protocol agent.Protocol // defaults to ProtocolACP
LogoLight []byte // nil = no logo (frontend shows a blank placeholder)
LogoDark []byte // nil = no logo
IdleTimeout time.Duration // defaults to 3s
BufferMax int64 // defaults to DefaultBufferMaxBytes
WaitForTerm bool // delay process start until the terminal WebSocket connects and sends its first resize
ModelFlag Param // e.g. NewParam("--model", "{model}") — lets users pick a model in profile settings
CommandArgs []string // extra args after Command
DetectOpts []DetectOption // defaults to WithCommand(Command)
}
// TUIAgent implements Agent + PassthroughAgent for CLI passthrough TUI tools.
type TUIAgent struct {
StandardPassthrough
cfg TUIAgentConfig
cmd Command // cached command built once from cfg.Command + cfg.CommandArgs
}
// NewTUIAgent creates a TUIAgent from a declarative config, applying defaults.
func NewTUIAgent(cfg TUIAgentConfig) *TUIAgent {
if cfg.Display == "" {
cfg.Display = cfg.AgentName
}
if cfg.Order == nil {
defaultOrder := 99
cfg.Order = &defaultOrder
}
if cfg.Protocol == "" {
cfg.Protocol = agent.ProtocolACP
}
if cfg.IdleTimeout == 0 {
cfg.IdleTimeout = 3 * time.Second
}
if cfg.BufferMax == 0 {
cfg.BufferMax = DefaultBufferMaxBytes
}
if len(cfg.DetectOpts) == 0 {
cfg.DetectOpts = []DetectOption{WithCommand(cfg.Command)}
}
cmdArgs := append([]string{cfg.Command}, cfg.CommandArgs...)
cmd := Cmd(cfg.Command).Flag(cfg.CommandArgs...).Build()
a := &TUIAgent{
StandardPassthrough: StandardPassthrough{
Cfg: PassthroughConfig{
Supported: true,
Label: "CLI Passthrough",
Description: cfg.Desc,
PassthroughCmd: NewCommand(cmdArgs...),
ModelFlag: cfg.ModelFlag,
IdleTimeout: cfg.IdleTimeout,
BufferMaxBytes: cfg.BufferMax,
WaitForTerminal: cfg.WaitForTerm,
},
},
cfg: cfg,
cmd: cmd,
}
return a
}
// Compile-time interface checks.
var (
_ Agent = (*TUIAgent)(nil)
_ PassthroughAgent = (*TUIAgent)(nil)
)
func (a *TUIAgent) ID() string { return a.cfg.AgentID }
func (a *TUIAgent) Name() string { return a.cfg.AgentName }
func (a *TUIAgent) DisplayName() string { return a.cfg.Display }
func (a *TUIAgent) Description() string { return a.cfg.Desc }
func (a *TUIAgent) Enabled() bool { return true }
func (a *TUIAgent) DisplayOrder() int { return *a.cfg.Order }
func (a *TUIAgent) Logo(v LogoVariant) []byte {
if v == LogoDark {
return a.cfg.LogoDark
}
return a.cfg.LogoLight
}
func (a *TUIAgent) IsInstalled(ctx context.Context) (*DiscoveryResult, error) {
return Detect(ctx, a.cfg.DetectOpts...)
}
func (a *TUIAgent) DefaultModel() string { return "" }
func (a *TUIAgent) ListModels(_ context.Context) (*ModelList, error) {
return &ModelList{Models: nil, SupportsDynamic: false}, nil
}
func (a *TUIAgent) BuildCommand(_ CommandOptions) Command {
return a.cmd
}
func (a *TUIAgent) PermissionSettings() map[string]PermissionSetting { return nil }
func (a *TUIAgent) Runtime() *RuntimeConfig {
return &RuntimeConfig{
Cmd: a.cmd,
WorkingDir: "{workspace}",
Env: map[string]string{},
ResourceLimits: DefaultResourceLimits,
Protocol: a.cfg.Protocol,
}
}
@@ -0,0 +1,172 @@
package agents
import (
"context"
"testing"
"github.com/kandev/kandev/pkg/agent"
)
func TestNewTUIAgent_Defaults(t *testing.T) {
a := NewTUIAgent(TUIAgentConfig{
AgentID: "test-tui",
AgentName: "TestTUI",
Command: "testtui",
Desc: "A test TUI agent.",
})
if a.ID() != "test-tui" {
t.Errorf("ID() = %q, want %q", a.ID(), "test-tui")
}
if a.Name() != "TestTUI" {
t.Errorf("Name() = %q, want %q", a.Name(), "TestTUI")
}
if a.DisplayName() != "TestTUI" {
t.Errorf("DisplayName() should default to AgentName, got %q", a.DisplayName())
}
if a.DisplayOrder() != 99 {
t.Errorf("DisplayOrder() = %d, want 99 (default)", a.DisplayOrder())
}
if !a.Enabled() {
t.Error("Enabled() should return true")
}
rt := a.Runtime()
if rt.Protocol != agent.ProtocolACP {
t.Errorf("Protocol = %q, want %q (default)", rt.Protocol, agent.ProtocolACP)
}
pt := a.PassthroughConfig()
if pt.IdleTimeout.Seconds() != 3 {
t.Errorf("IdleTimeout = %v, want 3s", pt.IdleTimeout)
}
if pt.BufferMaxBytes != DefaultBufferMaxBytes {
t.Errorf("BufferMaxBytes = %d, want %d", pt.BufferMaxBytes, DefaultBufferMaxBytes)
}
}
func intPtr(v int) *int { return &v }
func TestNewTUIAgent_CustomValues(t *testing.T) {
a := NewTUIAgent(TUIAgentConfig{
AgentID: "lazydocker",
AgentName: "Lazydocker",
Command: "lazydocker",
Desc: "Docker TUI.",
Display: "Docker UI",
Order: intPtr(50),
WaitForTerm: true,
CommandArgs: []string{"--debug"},
})
if a.DisplayName() != "Docker UI" {
t.Errorf("DisplayName() = %q, want %q", a.DisplayName(), "Docker UI")
}
if a.DisplayOrder() != 50 {
t.Errorf("DisplayOrder() = %d, want 50", a.DisplayOrder())
}
cmd := a.BuildCommand(CommandOptions{})
args := cmd.Args()
if len(args) != 2 || args[0] != "lazydocker" || args[1] != "--debug" {
t.Errorf("BuildCommand() = %v, want [lazydocker --debug]", args)
}
pt := a.PassthroughConfig()
if !pt.WaitForTerminal {
t.Error("WaitForTerminal should be true")
}
ptCmd := pt.PassthroughCmd.Args()
if len(ptCmd) != 2 || ptCmd[0] != "lazydocker" || ptCmd[1] != "--debug" {
t.Errorf("PassthroughCmd = %v, want [lazydocker --debug]", ptCmd)
}
}
func TestNewTUIAgent_OrderZeroIsValid(t *testing.T) {
a := NewTUIAgent(TUIAgentConfig{
AgentID: "zero-order", AgentName: "ZeroOrder", Command: "zo", Desc: "desc",
Order: intPtr(0),
})
if a.DisplayOrder() != 0 {
t.Errorf("DisplayOrder() = %d, want 0 (explicit zero should not be overridden)", a.DisplayOrder())
}
}
func TestNewTUIAgent_Logo(t *testing.T) {
// No logos
a := NewTUIAgent(TUIAgentConfig{
AgentID: "no-logo", AgentName: "NoLogo", Command: "nol", Desc: "No logo.",
})
if a.Logo(LogoLight) != nil {
t.Error("Logo(Light) should be nil when no logo provided")
}
if a.Logo(LogoDark) != nil {
t.Error("Logo(Dark) should be nil when no logo provided")
}
// With logos
light := []byte("<svg>light</svg>")
dark := []byte("<svg>dark</svg>")
b := NewTUIAgent(TUIAgentConfig{
AgentID: "with-logo", AgentName: "WithLogo", Command: "wl", Desc: "With logo.",
LogoLight: light, LogoDark: dark,
})
if string(b.Logo(LogoLight)) != string(light) {
t.Errorf("Logo(Light) = %q, want %q", b.Logo(LogoLight), light)
}
if string(b.Logo(LogoDark)) != string(dark) {
t.Errorf("Logo(Dark) = %q, want %q", b.Logo(LogoDark), dark)
}
}
func TestNewTUIAgent_ModelMethods(t *testing.T) {
a := NewTUIAgent(TUIAgentConfig{
AgentID: "tui", AgentName: "TUI", Command: "tui", Desc: "desc",
})
if a.DefaultModel() != "" {
t.Errorf("DefaultModel() = %q, want empty", a.DefaultModel())
}
models, err := a.ListModels(context.Background())
if err != nil {
t.Fatalf("ListModels() error = %v", err)
}
if models.SupportsDynamic {
t.Error("SupportsDynamic should be false")
}
if models.Models != nil {
t.Errorf("Models should be nil, got %v", models.Models)
}
}
func TestNewTUIAgent_PermissionSettings(t *testing.T) {
a := NewTUIAgent(TUIAgentConfig{
AgentID: "tui", AgentName: "TUI", Command: "tui", Desc: "desc",
})
if a.PermissionSettings() != nil {
t.Error("PermissionSettings() should return nil for TUI agents")
}
}
func TestNewTUIAgent_CustomDetectOpts(t *testing.T) {
customDetect := WithFileExists("/nonexistent/path")
a := NewTUIAgent(TUIAgentConfig{
AgentID: "custom-detect",
AgentName: "CustomDetect",
Command: "cd",
Desc: "Custom detection.",
DetectOpts: []DetectOption{customDetect},
})
result, err := a.IsInstalled(context.Background())
if err != nil {
t.Fatalf("IsInstalled() error = %v", err)
}
// Custom detect with nonexistent path should return not available
if result.Available {
t.Error("expected not available for nonexistent path")
}
}
@@ -156,7 +156,6 @@ func (c *Controller) ListAgentTypes(ctx context.Context, req dto.ListAgentTypesR
Name: t.Name(),
Description: t.Description(),
Image: image,
Capabilities: t.Runtime().Capabilities,
Enabled: t.Enabled(),
}))
}
-3
View File
@@ -77,7 +77,6 @@ type AgentTypeDTO struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Image string `json:"image"`
Capabilities []string `json:"capabilities,omitempty"`
Enabled bool `json:"enabled"`
}
@@ -129,7 +128,6 @@ func FromAgentType(t *AgentTypeData) AgentTypeDTO {
Name: t.Name,
Description: t.Description,
Image: t.Image,
Capabilities: t.Capabilities,
Enabled: t.Enabled,
}
}
@@ -140,7 +138,6 @@ type AgentTypeData struct {
Name string
Description string
Image string
Capabilities []string
Enabled bool
}
@@ -2762,8 +2762,12 @@ func (m *Manager) ResumePassthroughSession(ctx context.Context, sessionID string
}
}
// Start the interactive process
// Use the same settings as initial start (including wait_for_terminal)
// Start the interactive process.
// Always use immediate start on resume — the terminal WebSocket is already connected,
// so we don't need to wait for a resize to get exact dimensions. The first resize
// from the terminal will correct the dimensions. Without this, TUI apps that use
// WaitForTerminal would never start because the frontend may not send resizes
// to a process it doesn't know about yet.
startReq := process.InteractiveStartRequest{
SessionID: sessionID,
Command: cmd.Args(),
@@ -2774,7 +2778,7 @@ func (m *Manager) ResumePassthroughSession(ctx context.Context, sessionID string
StatusDetector: pt.StatusDetector,
CheckInterval: pt.CheckInterval,
StabilityWindow: pt.StabilityWindow,
ImmediateStart: !pt.WaitForTerminal,
ImmediateStart: true,
DefaultCols: 120,
DefaultRows: 40,
}
@@ -2807,8 +2811,8 @@ func (m *Manager) ResumePassthroughSession(ctx context.Context, sessionID string
}
// Connect to workspace stream for shell/git/file features.
// This re-establishes the connection that was lost on backend restart.
if m.streamManager != nil && execution.agentctl != nil {
// Only connect if not already connected (process restart reuses the same agentctl).
if m.streamManager != nil && execution.agentctl != nil && execution.GetWorkspaceStream() == nil {
go m.streamManager.connectWorkspaceStream(execution, nil)
}
@@ -12,7 +12,6 @@ import (
"github.com/kandev/kandev/internal/agent/docker"
"github.com/kandev/kandev/internal/agent/registry"
agentctl "github.com/kandev/kandev/internal/agentctl/client"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/events/bus"
"github.com/kandev/kandev/internal/task/models"
@@ -50,10 +49,6 @@ func (a *testAgent) ListModels(_ context.Context) (*agents.ModelList, error) {
return &agents.ModelList{}, nil
}
func (a *testAgent) CreateAdapter(_ *adapter.Config, _ *logger.Logger) (adapter.AgentAdapter, error) {
return nil, agents.ErrNotSupported
}
func (a *testAgent) BuildCommand(_ agents.CommandOptions) agents.Command { return agents.Command{} }
func (a *testAgent) PermissionSettings() map[string]agents.PermissionSetting {
@@ -74,7 +74,7 @@ func (r *Registry) Get(id string) (agents.Agent, bool) {
}
// GetDefault returns the default agent.
// It tries "auggie" first, then falls back to the first enabled agent.
// It tries "auggie" first, then falls back to the enabled agent with the lowest DisplayOrder.
func (r *Registry) GetDefault() (agents.Agent, error) {
r.mu.RLock()
defer r.mu.RUnlock()
@@ -83,13 +83,18 @@ func (r *Registry) GetDefault() (agents.Agent, error) {
return ag, nil
}
// Collect enabled agents and sort by DisplayOrder for deterministic fallback
var enabled []agents.Agent
for _, ag := range r.agents {
if ag.Enabled() {
return ag, nil
enabled = append(enabled, ag)
}
}
if len(enabled) == 0 {
return nil, fmt.Errorf("no default agent type available")
}
sortByDisplayOrder(enabled)
return enabled[0], nil
}
// sortByDisplayOrder sorts agents by their DisplayOrder in ascending order.
@@ -182,7 +187,6 @@ func ToAPIType(ag agents.Agent) *v1.AgentType {
MemoryLimit: fmt.Sprintf("%dM", rt.ResourceLimits.MemoryMB),
},
EnvironmentVars: rt.Env,
Capabilities: rt.Capabilities,
Enabled: ag.Enabled(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
@@ -6,7 +6,6 @@ import (
"time"
"github.com/kandev/kandev/internal/agent/agents"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/common/logger"
)
@@ -34,9 +33,6 @@ func (a *testAgent) DefaultModel() string { return "" }
func (a *testAgent) ListModels(context.Context) (*agents.ModelList, error) {
return nil, agents.ErrNotSupported
}
func (a *testAgent) CreateAdapter(*adapter.Config, *logger.Logger) (adapter.AgentAdapter, error) {
return nil, agents.ErrNotSupported
}
func (a *testAgent) BuildCommand(agents.CommandOptions) agents.Command { return agents.Command{} }
func (a *testAgent) PermissionSettings() map[string]agents.PermissionSetting {
return nil
@@ -66,7 +62,6 @@ func validAgentConfig(id, name string) *testAgent {
CPUCores: 1.0,
Timeout: time.Hour,
},
Capabilities: []string{"test"},
},
}
}
@@ -306,7 +301,6 @@ func TestRegistry_ListEnabled_OrderedByDisplayOrder(t *testing.T) {
func TestAgentTypeConfig_ToAPIType(t *testing.T) {
ag := validAgentConfig("test-agent", "Test Agent")
ag.description = "Test description"
ag.runtime.Capabilities = []string{"cap1", "cap2"}
ag.runtime.Env = map[string]string{"KEY": "value"}
apiType := ToAPIType(ag)
@@ -323,9 +317,6 @@ func TestAgentTypeConfig_ToAPIType(t *testing.T) {
if apiType.DockerImage != ag.runtime.Image {
t.Errorf("expected DockerImage %q, got %q", ag.runtime.Image, apiType.DockerImage)
}
if len(apiType.Capabilities) != len(ag.runtime.Capabilities) {
t.Errorf("expected %d capabilities, got %d", len(ag.runtime.Capabilities), len(apiType.Capabilities))
}
if apiType.Enabled != ag.Enabled() {
t.Errorf("expected Enabled %v, got %v", ag.Enabled(), apiType.Enabled)
}
@@ -294,9 +294,15 @@ func (c *Controller) EnsureInitialAgentProfiles(ctx context.Context) error {
return fmt.Errorf("unknown agent display name: %s", result.Name)
}
defaultModel := agentConfig.DefaultModel()
isPassthroughOnly := false
if defaultModel == "" {
if ptAgent, ok := agentConfig.(agents.PassthroughAgent); ok && ptAgent.PassthroughConfig().Supported {
isPassthroughOnly = true
defaultModel = "passthrough"
} else {
return fmt.Errorf("unknown agent default model: %s", result.Name)
}
}
agent, err := c.repo.GetAgentByName(ctx, result.Name)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
@@ -357,6 +363,9 @@ func (c *Controller) EnsureInitialAgentProfiles(ctx context.Context) error {
// Re-resolve profile name from model display name
resolvedName := resolveModelDisplayName(modelList, profile.Model)
if isPassthroughOnly {
resolvedName = displayName
}
if profile.Name != resolvedName {
profile.Name = resolvedName
updated = true
@@ -374,6 +383,10 @@ func (c *Controller) EnsureInitialAgentProfiles(ctx context.Context) error {
profile.DangerouslySkipPermissions = skipPermissions
updated = true
}
if isPassthroughOnly && !profile.CLIPassthrough {
profile.CLIPassthrough = true
updated = true
}
if updated {
if err := c.repo.UpdateAgentProfile(ctx, profile); err != nil {
@@ -385,6 +398,9 @@ func (c *Controller) EnsureInitialAgentProfiles(ctx context.Context) error {
}
profileName := resolveModelDisplayName(modelList, defaultModel)
if isPassthroughOnly {
profileName = displayName
}
defaultProfile := &models.AgentProfile{
AgentID: agent.ID,
Name: profileName,
@@ -393,6 +409,7 @@ func (c *Controller) EnsureInitialAgentProfiles(ctx context.Context) error {
AutoApprove: autoApprove,
AllowIndexing: allowIndexing,
DangerouslySkipPermissions: skipPermissions,
CLIPassthrough: isPassthroughOnly,
}
if err := c.repo.CreateAgentProfile(ctx, defaultProfile); err != nil {
return err
@@ -9,7 +9,6 @@ import (
"github.com/kandev/kandev/internal/agent/registry"
"github.com/kandev/kandev/internal/agent/settings/dto"
"github.com/kandev/kandev/internal/agent/settings/modelfetcher"
"github.com/kandev/kandev/internal/agentctl/server/adapter"
"github.com/kandev/kandev/internal/common/logger"
)
@@ -47,10 +46,6 @@ func (a *testAgent) ListModels(ctx context.Context) (*agents.ModelList, error) {
return &agents.ModelList{}, nil
}
func (a *testAgent) CreateAdapter(cfg *adapter.Config, log *logger.Logger) (adapter.AgentAdapter, error) {
return nil, agents.ErrNotSupported
}
// BuildCommand builds a command using runtime config, model flag, and permission flags.
func (a *testAgent) BuildCommand(opts agents.CommandOptions) agents.Command {
rt := a.Runtime()
@@ -41,6 +41,7 @@ type InteractiveStartRequest struct {
DefaultRows int `json:"default_rows,omitempty"` // Default rows if ImmediateStart (default 40)
InitialCommand string `json:"initial_command,omitempty"` // Command to write to stdin after shell starts (for script terminals)
DisableTurnDetection bool `json:"disable_turn_detection,omitempty"` // Disable idle timer and turn detection (for user shell terminals)
IsUserShell bool `json:"is_user_shell,omitempty"` // Mark as user shell process (excluded from session-level lookups)
}
// InteractiveProcessInfo represents the state of an interactive process.
@@ -80,6 +81,10 @@ type interactiveProcess struct {
statusTracker *StatusTracker
lastState AgentState
// User shell flag - when true, process is excluded from session-level lookups
// (ResizeBySession, GetPtyWriterBySession) to prevent conflicts with passthrough processes
isUserShell bool
// Deferred start - process created lazily on first resize
// This ensures PTY is created at exact frontend dimensions
started bool
@@ -189,9 +194,9 @@ func (r *InteractiveRunner) SetStateCallback(cb AgentStateCallback) {
r.stateCallback = cb
}
// createStatusDetector creates the appropriate detector based on the detector type.
// The idle detector is the default - it relies on the idle timer mechanism for turn detection.
func createStatusDetector(detectorType string) StatusDetector {
// createStatusDetector creates a status detector for TUI state tracking.
// Currently always returns an idle detector that relies on the idle timer mechanism.
func createStatusDetector() StatusDetector {
return NewIdleDetector()
}
@@ -251,6 +256,7 @@ func (r *InteractiveRunner) Start(ctx context.Context, req InteractiveStartReque
promptPattern: promptPattern,
idleTimeout: idleTimeout,
lastState: StateUnknown,
isUserShell: req.IsUserShell,
stopSignal: make(chan struct{}),
waitDone: make(chan struct{}),
// Store start parameters for deferred initialization
@@ -337,7 +343,7 @@ func (r *InteractiveRunner) startProcess(proc *interactiveProcess, cols, rows in
// Create status tracker if a detector is configured
var statusTracker *StatusTracker
if req.StatusDetector != "" {
detector := createStatusDetector(req.StatusDetector)
detector := createStatusDetector()
config := StatusTrackerConfig{
Rows: rows,
Cols: cols,
@@ -568,30 +574,15 @@ func (r *InteractiveRunner) GetBuffer(processID string) ([]ProcessOutputChunk, b
return proc.buffer.snapshot(), true
}
// ResizeBySession resizes the PTY for a process by session ID.
// On first resize, this triggers lazy process start at the exact frontend dimensions.
func (r *InteractiveRunner) ResizeBySession(sessionID string, cols, rows uint16) error {
r.mu.RLock()
var proc *interactiveProcess
for _, p := range r.processes {
if p.info.SessionID == sessionID {
proc = p
break
}
}
r.mu.RUnlock()
if proc == nil {
return fmt.Errorf("no process found for session %s", sessionID)
}
// lazyStartAndResize handles the common pattern of lazy-starting a process on the first
// resize and then resizing its PTY and status tracker. All three public Resize* methods
// delegate here to avoid duplicating the start-once + resize logic.
func (r *InteractiveRunner) lazyStartAndResize(proc *interactiveProcess, cols, rows uint16, logFields ...zap.Field) error {
// Lazy start: spawn process on first resize when we have exact dimensions
var startErr error
proc.startOnce.Do(func() {
r.logger.Info("first resize received - starting process",
zap.String("session_id", sessionID),
zap.Uint16("cols", cols),
zap.Uint16("rows", rows))
fields := append([]zap.Field{zap.Uint16("cols", cols), zap.Uint16("rows", rows)}, logFields...)
r.logger.Info("first resize received - starting process", fields...)
startErr = r.startProcess(proc, int(cols), int(rows))
})
if startErr != nil {
@@ -603,19 +594,71 @@ func (r *InteractiveRunner) ResizeBySession(sessionID string, cols, rows uint16)
statusTracker := proc.statusTracker
proc.mu.Unlock()
// If process started, resize the PTY
// On Unix this sends SIGWINCH; on Windows it updates the ConPTY dimensions
// Resize the PTY (Unix: SIGWINCH, Windows: ConPTY dimensions)
if ptyInstance != nil {
if err := ptyInstance.Resize(cols, rows); err != nil {
return fmt.Errorf("failed to resize PTY: %w", err)
}
}
// Also resize the status tracker's virtual terminal
// Also resize the status tracker's virtual terminal (if present)
if statusTracker != nil {
statusTracker.Resize(int(cols), int(rows))
}
return nil
}
// ResizeByProcessID resizes the PTY for a specific process by its ID.
// On first resize, this triggers lazy process start at the exact frontend dimensions.
// This is preferred over ResizeBySession when the process ID is known, as it avoids
// ambiguity when multiple processes exist for the same session.
func (r *InteractiveRunner) ResizeByProcessID(processID string, cols, rows uint16) error {
proc, ok := r.get(processID)
if !ok {
return fmt.Errorf("process not found: %s", processID)
}
if err := r.lazyStartAndResize(proc, cols, rows,
zap.String("process_id", processID),
zap.String("session_id", proc.info.SessionID),
); err != nil {
return err
}
r.logger.Debug("resized PTY",
zap.String("process_id", processID),
zap.String("session_id", proc.info.SessionID),
zap.Uint16("cols", cols),
zap.Uint16("rows", rows))
return nil
}
// ResizeBySession resizes the PTY for a process by session ID.
// On first resize, this triggers lazy process start at the exact frontend dimensions.
// Skips user shell processes to avoid conflicts with passthrough processes.
func (r *InteractiveRunner) ResizeBySession(sessionID string, cols, rows uint16) error {
r.mu.RLock()
var proc *interactiveProcess
for _, p := range r.processes {
if p.info.SessionID == sessionID && !p.isUserShell {
proc = p
break
}
}
r.mu.RUnlock()
if proc == nil {
return fmt.Errorf("no process found for session %s", sessionID)
}
if err := r.lazyStartAndResize(proc, cols, rows,
zap.String("session_id", sessionID),
); err != nil {
return err
}
r.logger.Debug("resized PTY",
zap.String("session_id", sessionID),
zap.Uint16("cols", cols),
@@ -968,7 +1011,9 @@ func (p *interactiveProcess) snapshot(includeOutput bool) InteractiveProcessInfo
// SetDirectOutput sets a direct output writer for a process.
// When set, PTY output bypasses the event bus and goes directly to this writer.
// This is used for the dedicated binary WebSocket in passthrough mode.
// Also tracks the WebSocket at the session level to survive process restarts.
// For non-user-shell processes, also tracks the WebSocket at the session level
// to survive process restarts. User shells are excluded from session-level tracking
// to prevent overwriting the agent terminal's WebSocket.
// Returns error if process not found.
func (r *InteractiveRunner) SetDirectOutput(processID string, writer DirectOutputWriter) error {
proc, ok := r.get(processID)
@@ -983,21 +1028,26 @@ func (r *InteractiveRunner) SetDirectOutput(processID string, writer DirectOutpu
proc.hasActiveWebSocket = true
proc.directOutputMu.Unlock()
// Also track at session level for restart support
// Track at session level for restart support (agent passthrough only).
// User shells have their own tracking via userShells map and must not
// overwrite the agent terminal's session-level WebSocket.
if !proc.isUserShell {
r.sessionWsMu.Lock()
r.sessionWs[sessionID] = &sessionWebSocket{writer: writer}
r.sessionWsMu.Unlock()
}
r.logger.Info("direct output set for process",
zap.String("process_id", processID),
zap.String("session_id", sessionID))
zap.String("session_id", sessionID),
zap.Bool("is_user_shell", proc.isUserShell))
return nil
}
// ClearDirectOutput clears the direct output writer for a process.
// Output will return to the normal event bus path.
// Also clears the session-level WebSocket tracking.
// For non-user-shell processes, also clears the session-level WebSocket tracking.
func (r *InteractiveRunner) ClearDirectOutput(processID string) error {
proc, ok := r.get(processID)
if !ok {
@@ -1014,10 +1064,12 @@ func (r *InteractiveRunner) ClearDirectOutput(processID string) error {
proc.hasActiveWebSocket = false
proc.directOutputMu.Unlock()
// Also clear session-level tracking
// Clear session-level tracking (agent passthrough only)
if !proc.isUserShell {
r.sessionWsMu.Lock()
delete(r.sessionWs, sessionID)
r.sessionWsMu.Unlock()
}
r.logger.Info("direct output cleared for process",
zap.String("process_id", processID),
@@ -1027,17 +1079,18 @@ func (r *InteractiveRunner) ClearDirectOutput(processID string) error {
}
// ClearDirectOutputBySession clears the direct output for a session.
// This is used when the terminal WebSocket disconnects.
// This is used when the agent terminal WebSocket disconnects.
// Only clears non-user-shell processes to avoid disrupting user shell terminals.
func (r *InteractiveRunner) ClearDirectOutputBySession(sessionID string) {
// Clear session-level tracking
r.sessionWsMu.Lock()
delete(r.sessionWs, sessionID)
r.sessionWsMu.Unlock()
// Also clear from any process with this session
// Clear from non-user-shell processes with this session
r.mu.RLock()
for _, proc := range r.processes {
if proc.info.SessionID == sessionID {
if proc.info.SessionID == sessionID && !proc.isUserShell {
proc.directOutputMu.Lock()
proc.directOutput = nil
proc.hasActiveWebSocket = false
@@ -1113,11 +1166,12 @@ func (r *InteractiveRunner) GetPtyWriter(processID string) (io.Writer, error) {
// GetPtyWriterBySession returns a writer for sending input to the PTY for a session.
// This is used to reconnect after a process restart.
// Skips user shell processes to avoid conflicts with passthrough processes.
func (r *InteractiveRunner) GetPtyWriterBySession(sessionID string) (io.Writer, string, error) {
r.mu.RLock()
var proc *interactiveProcess
for _, p := range r.processes {
if p.info.SessionID == sessionID {
if p.info.SessionID == sessionID && !p.isUserShell {
proc = p
break
}
@@ -1344,6 +1398,7 @@ func (r *InteractiveRunner) StartUserShell(ctx context.Context, sessionID, termi
WorkingDir: workingDir,
InitialCommand: initialCommand,
DisableTurnDetection: true, // User shells must not trigger turn complete / MarkReady
IsUserShell: true, // Exclude from session-level lookups (ResizeBySession, GetPtyWriterBySession)
}
info, err := r.Start(ctx, req)
@@ -1500,31 +1555,10 @@ func (r *InteractiveRunner) ResizeUserShell(sessionID, terminalID string, cols,
return fmt.Errorf("process not found: %s", entry.ProcessID)
}
// Lazy start: spawn process on first resize when we have exact dimensions
var startErr error
proc.startOnce.Do(func() {
r.logger.Info("first resize received for user shell - starting process",
return r.lazyStartAndResize(proc, cols, rows,
zap.String("session_id", sessionID),
zap.String("terminal_id", terminalID),
zap.Uint16("cols", cols),
zap.Uint16("rows", rows))
startErr = r.startProcess(proc, int(cols), int(rows))
})
if startErr != nil {
return fmt.Errorf("failed to start process on first resize: %w", startErr)
}
proc.mu.Lock()
ptyInstance := proc.ptmx
proc.mu.Unlock()
if ptyInstance != nil {
if err := ptyInstance.Resize(cols, rows); err != nil {
return fmt.Errorf("failed to resize PTY: %w", err)
}
}
return nil
)
}
// GetUserShellPtyWriter returns the PTY writer for a user shell.
@@ -1581,26 +1615,23 @@ func containsDSRQuery(data []byte) bool {
}
// containsDA1Query checks if data contains a Primary Device Attributes query.
// DA1 query is: ESC [ c or ESC [ 0 c (but NOT ESC [ <digit> c which is cursor forward)
// DA1 query is: ESC [ c or ESC [ 0 c (but NOT ESC [ <digit> c where digit is 1-9,
// since those are cursor forward sequences).
func containsDA1Query(data []byte) bool {
// Check for exact ESC [ c sequence
csiC := []byte("\x1b[c")
for i := 0; i <= len(data)-len(csiC); i++ {
if data[i] == '\x1b' && i+2 < len(data) && data[i+1] == '[' && data[i+2] == 'c' {
// Make sure it's not preceded by a digit (which would make it cursor forward)
// ESC [ c is valid, ESC [ 0 c is valid, but ESC [ 1 c is cursor forward
if i+2 == len(data)-1 {
// ESC [ c at end
for i := 0; i+2 < len(data); i++ {
if data[i] != '\x1b' || data[i+1] != '[' {
continue
}
// ESC [ c — DA1 with no parameter
if data[i+2] == 'c' {
return true
}
// Check what's before 'c' - if it's just '[' or '[0' it's DA1
// We already matched ESC [ c, so this is valid
// ESC [ 0 c — DA1 with explicit 0 parameter
if data[i+2] == '0' && i+3 < len(data) && data[i+3] == 'c' {
return true
}
// ESC [ <1-9> c would be cursor forward — skip it
}
// Check for ESC [ 0 c
csi0C := []byte("\x1b[0c")
return bytes.Contains(data, csi0C)
return false
}
@@ -595,97 +595,183 @@ func TestInteractiveRunner_IsProcessReadyOrPending(t *testing.T) {
_ = runner.Stop(ctx, info.ID)
}
func TestCursorPositionQueryDetection(t *testing.T) {
func TestContainsDSRQuery(t *testing.T) {
tests := []struct {
name string
data []byte
wantDSR bool // Device Status Report (cursor position query)
wantDA bool // Device Attributes query
want bool
}{
{
name: "cursor position query ESC[6n",
data: []byte("\x1b[6n"),
wantDSR: true,
wantDA: false,
},
{
name: "cursor position query ESC[?6n",
data: []byte("\x1b[?6n"),
wantDSR: true,
wantDA: false,
},
{
name: "device attributes query ESC[c",
data: []byte("\x1b[c"),
wantDSR: false,
wantDA: true,
},
{
name: "device attributes query ESC[0c",
data: []byte("\x1b[0c"),
wantDSR: false,
wantDA: true,
},
{
name: "no escape sequence",
data: []byte("hello world"),
wantDSR: false,
wantDA: false,
},
{
name: "mixed content with DSR",
data: []byte("some text\x1b[6nmore text"),
wantDSR: true,
wantDA: false,
},
{
name: "both DSR and DA",
data: []byte("\x1b[6n\x1b[c"),
wantDSR: true,
wantDA: true,
},
{"ESC[6n", []byte("\x1b[6n"), true},
{"ESC[?6n", []byte("\x1b[?6n"), true},
{"mixed content with DSR", []byte("text\x1b[6nmore"), true},
{"no escape", []byte("hello world"), false},
{"partial ESC[6", []byte("\x1b[6"), false},
{"ESC[c is not DSR", []byte("\x1b[c"), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotDSR := containsCursorPositionQuery(tt.data)
gotDA := containsDeviceAttributesQuery(tt.data)
if gotDSR != tt.wantDSR {
t.Errorf("containsCursorPositionQuery() = %v, want %v", gotDSR, tt.wantDSR)
}
if gotDA != tt.wantDA {
t.Errorf("containsDeviceAttributesQuery() = %v, want %v", gotDA, tt.wantDA)
if got := containsDSRQuery(tt.data); got != tt.want {
t.Errorf("containsDSRQuery(%q) = %v, want %v", tt.data, got, tt.want)
}
})
}
}
// containsCursorPositionQuery checks for DSR cursor position query (CSI 6 n)
func containsCursorPositionQuery(data []byte) bool {
return bytesContains(data, []byte("\x1b[6n")) || bytesContains(data, []byte("\x1b[?6n"))
func TestContainsDA1Query(t *testing.T) {
tests := []struct {
name string
data []byte
want bool
}{
{"ESC[c (DA1 no param)", []byte("\x1b[c"), true},
{"ESC[0c (DA1 explicit 0)", []byte("\x1b[0c"), true},
{"mixed with DA1", []byte("text\x1b[cmore"), true},
{"both DSR and DA1", []byte("\x1b[6n\x1b[c"), true},
{"no escape", []byte("hello world"), false},
{"ESC[1c is cursor forward, not DA1", []byte("\x1b[1c"), false},
{"ESC[2c is cursor forward, not DA1", []byte("\x1b[2c"), false},
{"ESC[5c is cursor forward, not DA1", []byte("\x1b[5c"), false},
{"ESC[9c is cursor forward, not DA1", []byte("\x1b[9c"), false},
{"partial ESC[", []byte("\x1b["), false},
{"empty data", []byte{}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := containsDA1Query(tt.data); got != tt.want {
t.Errorf("containsDA1Query(%q) = %v, want %v", tt.data, got, tt.want)
}
})
}
}
// containsDeviceAttributesQuery checks for DA query (CSI c or CSI 0 c)
func containsDeviceAttributesQuery(data []byte) bool {
return bytesContains(data, []byte("\x1b[c")) || bytesContains(data, []byte("\x1b[0c"))
func TestInteractiveRunner_ResizeByProcessID(t *testing.T) {
log := newTestLogger(t)
runner := NewInteractiveRunner(nil, log, 2*1024*1024)
// Start a deferred process
req := InteractiveStartRequest{
SessionID: "resize-pid-test",
Command: []string{"cat"},
}
info, err := runner.Start(context.Background(), req)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
// Process should not be running yet
if runner.IsProcessRunning(info.ID) {
t.Error("process should not be running before resize")
}
// Trigger start via ResizeByProcessID
if err := runner.ResizeByProcessID(info.ID, 80, 24); err != nil {
t.Fatalf("ResizeByProcessID() error = %v", err)
}
// Give process time to start
time.Sleep(100 * time.Millisecond)
if !runner.IsProcessRunning(info.ID) {
t.Error("process should be running after ResizeByProcessID")
}
// Subsequent resize should succeed
if err := runner.ResizeByProcessID(info.ID, 120, 40); err != nil {
t.Errorf("second ResizeByProcessID() error = %v", err)
}
// Non-existent process should fail
if err := runner.ResizeByProcessID("nonexistent", 80, 24); err == nil {
t.Error("ResizeByProcessID() should fail for nonexistent process")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = runner.Stop(ctx, info.ID)
}
// bytesContains is a simple contains check (bytes.Contains equivalent for tests)
func bytesContains(data, substr []byte) bool {
for i := 0; i <= len(data)-len(substr); i++ {
match := true
for j := 0; j < len(substr); j++ {
if data[i+j] != substr[j] {
match = false
break
func TestInteractiveRunner_IsUserShellIsolation(t *testing.T) {
log := newTestLogger(t)
runner := NewInteractiveRunner(nil, log, 2*1024*1024)
// Start a regular (non-user-shell) process
agentReq := InteractiveStartRequest{
SessionID: "isolation-test",
Command: []string{"cat"},
ImmediateStart: true,
DefaultCols: 80,
DefaultRows: 24,
}
agentInfo, err := runner.Start(context.Background(), agentReq)
if err != nil {
t.Fatalf("Start() agent error = %v", err)
}
if match {
return true
// Start a user shell process for the same session
shellReq := InteractiveStartRequest{
SessionID: "isolation-test",
Command: []string{"cat"},
IsUserShell: true,
ImmediateStart: true,
DefaultCols: 80,
DefaultRows: 24,
}
shellInfo, err := runner.Start(context.Background(), shellReq)
if err != nil {
t.Fatalf("Start() shell error = %v", err)
}
return false
time.Sleep(100 * time.Millisecond)
// ResizeBySession should target the agent process, not the user shell
if err := runner.ResizeBySession("isolation-test", 120, 40); err != nil {
t.Errorf("ResizeBySession() error = %v", err)
}
// GetPtyWriterBySession should return the agent process, not the user shell
_, procID, err := runner.GetPtyWriterBySession("isolation-test")
if err != nil {
t.Fatalf("GetPtyWriterBySession() error = %v", err)
}
if procID != agentInfo.ID {
t.Errorf("GetPtyWriterBySession() returned process %q, want agent process %q", procID, agentInfo.ID)
}
// SetDirectOutput on user shell should NOT track at session level
writer := &mockDirectWriter{}
if err := runner.SetDirectOutput(shellInfo.ID, writer); err != nil {
t.Fatalf("SetDirectOutput() shell error = %v", err)
}
// Session-level WebSocket should NOT be set for user shells
if runner.HasActiveWebSocketBySession("isolation-test") {
t.Error("user shell should not set session-level WebSocket tracking")
}
// SetDirectOutput on agent process SHOULD track at session level
agentWriter := &mockDirectWriter{}
if err := runner.SetDirectOutput(agentInfo.ID, agentWriter); err != nil {
t.Fatalf("SetDirectOutput() agent error = %v", err)
}
if !runner.HasActiveWebSocketBySession("isolation-test") {
t.Error("agent process should set session-level WebSocket tracking")
}
// ClearDirectOutputBySession should clear agent but not user shell
runner.ClearDirectOutputBySession("isolation-test")
// Agent should have its direct output cleared
if runner.HasActiveWebSocket(agentInfo.ID) {
t.Error("agent WebSocket should be cleared after ClearDirectOutputBySession")
}
// User shell should still have its direct output
if !runner.HasActiveWebSocket(shellInfo.ID) {
t.Error("user shell WebSocket should NOT be cleared by ClearDirectOutputBySession")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = runner.Stop(ctx, agentInfo.ID)
_ = runner.Stop(ctx, shellInfo.ID)
}
// --- User Shell Tests ---
@@ -10,7 +10,6 @@ import (
"net/url"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
gorillaws "github.com/gorilla/websocket"
@@ -258,13 +257,7 @@ func (h *TerminalHandler) runTerminalBridge(
var ptyWriter io.Writer
var directOutputSet bool
// Channel to signal cleanup to any spawned goroutines
done := make(chan struct{})
defer func() {
// Signal any background goroutines to stop
close(done)
// Clean up: clear direct output at session level (process may have been restarted with new ID)
interactiveRunner.ClearDirectOutputBySession(sessionID)
_ = wsw.Close()
@@ -305,119 +298,70 @@ func (h *TerminalHandler) runTerminalBridge(
}
}
// Now handle the resize - this sends SIGWINCH which triggers TUI redraw
h.handleResize(data[1:], sessionID, interactiveRunner)
// Handle resize — may return updated processID if process was restarted.
// Falls back to session-level resize when the old process is gone.
newProcessID := h.handleResize(data[1:], sessionID, processID, interactiveRunner)
if newProcessID != processID {
processID = newProcessID
directOutputSet = false
ptyWriter = nil
}
// Retry setupPtyAccess after resize — process may have been lazily started
// by the resize (deferred-start), so the PTY is now available.
if !directOutputSet {
if h.setupPtyAccess(sessionID, processID, interactiveRunner, wsw, &ptyWriter) {
directOutputSet = true
}
}
continue
}
// Regular input - write to PTY if available
if ptyWriter != nil {
if _, err := ptyWriter.Write(data); err != nil {
h.logger.Debug("PTY write error, attempting reconnect",
h.logger.Debug("PTY write error",
zap.String("session_id", sessionID),
zap.String("process_id", processID),
zap.Error(err))
// Try to reconnect to a new process (may have been restarted)
newWriter, newProcID := h.attemptReconnect(sessionID, interactiveRunner, wsw, done)
if newWriter != nil {
ptyWriter = newWriter
processID = newProcID
directOutputSet = true
// Retry write with new writer
if _, err := ptyWriter.Write(data); err != nil {
h.logger.Debug("PTY write error after reconnect",
zap.String("session_id", sessionID),
zap.Error(err))
// Reset state and discover the new process immediately.
// Without this, the bridge would be stuck with the old processID
// until a resize message arrives (which may never come after restart).
ptyWriter = nil
directOutputSet = false
processID = h.discoverProcessBySession(sessionID, processID, interactiveRunner)
continue
}
h.detectInputSubmission(sessionID, data)
} else {
h.logger.Debug("reconnect failed, PTY unavailable",
zap.String("session_id", sessionID))
// Don't return - keep trying on subsequent inputs
continue
}
} else {
// Detect Enter key (user submitted input) - notify lifecycle manager
h.detectInputSubmission(sessionID, data)
}
} else {
// PTY not ready yet - try to set it up
if h.setupPtyAccess(sessionID, processID, interactiveRunner, wsw, &ptyWriter) {
directOutputSet = true
// Double-check ptyWriter is valid after setup
// PTY not ready — try setup. If it fails, processID may be stale
// (process was restarted with a new ID). Discover the current process
// by session before giving up.
if !h.setupPtyAccess(sessionID, processID, interactiveRunner, wsw, &ptyWriter) {
newID := h.discoverProcessBySession(sessionID, processID, interactiveRunner)
if newID != processID {
processID = newID
h.setupPtyAccess(sessionID, processID, interactiveRunner, wsw, &ptyWriter)
}
}
if ptyWriter == nil {
h.logger.Error("PTY writer is nil after successful setup",
zap.String("session_id", sessionID))
h.logger.Debug("PTY not ready, dropping input",
zap.String("session_id", sessionID),
zap.Int("bytes", len(data)))
continue
}
// Retry writing after setup
directOutputSet = true
if _, err := ptyWriter.Write(data); err != nil {
h.logger.Debug("PTY write error after setup",
zap.String("session_id", sessionID),
zap.Error(err))
continue
}
// Detect Enter key (user submitted input) - notify lifecycle manager
h.detectInputSubmission(sessionID, data)
} else {
h.logger.Debug("PTY not ready, dropping input",
zap.String("session_id", sessionID),
zap.Int("bytes", len(data)))
}
}
}
}
// attemptReconnect tries to reconnect to a new process after the old one exited.
// Returns the new PTY writer and process ID if successful, or nil if not.
func (h *TerminalHandler) attemptReconnect(
sessionID string,
interactiveRunner *process.InteractiveRunner,
wsw *wsWriter,
done <-chan struct{},
) (io.Writer, string) {
const maxRetries = 20 // 20 retries
const retryInterval = 100 * time.Millisecond // 100ms between retries = 2s total
for i := 0; i < maxRetries; i++ {
select {
case <-done:
// Bridge is shutting down
return nil, ""
default:
}
// Try to get the PTY writer for the session (may be a new process)
writer, newProcID, err := interactiveRunner.GetPtyWriterBySession(sessionID)
if err == nil && writer != nil {
// Found a new process - set up direct output
if err := interactiveRunner.SetDirectOutput(newProcID, wsw); err != nil {
h.logger.Debug("failed to set direct output during reconnect",
zap.String("session_id", sessionID),
zap.String("process_id", newProcID),
zap.Error(err))
} else {
h.logger.Info("reconnected to new process after restart",
zap.String("session_id", sessionID),
zap.String("process_id", newProcID))
return writer, newProcID
}
}
// Wait before retrying
select {
case <-done:
return nil, ""
case <-time.After(retryInterval):
}
}
h.logger.Debug("reconnect attempts exhausted",
zap.String("session_id", sessionID),
zap.Int("attempts", maxRetries))
return nil, ""
}
// detectInputSubmission checks if the input contains Enter key and notifies
@@ -452,69 +396,31 @@ func (h *TerminalHandler) setupPtyAccess(
wsw *wsWriter,
ptyWriter *io.Writer,
) bool {
// Try to get PTY writer - this will fail if process hasn't started yet
writer, err := interactiveRunner.GetPtyWriter(processID)
if err != nil {
h.logger.Debug("PTY writer not ready yet",
zap.String("session_id", sessionID),
zap.String("process_id", processID))
return false
getWriter := func() (io.Writer, error) {
return interactiveRunner.GetPtyWriter(processID)
}
// Send buffered output to the terminal before switching to direct mode.
// This provides scrollback history when reconnecting to an existing session.
// We batch all chunks into a single write for efficiency.
if chunks, ok := interactiveRunner.GetBuffer(processID); ok && len(chunks) > 0 {
var combined bytes.Buffer
for _, chunk := range chunks {
combined.WriteString(chunk.Data)
}
if combined.Len() > 0 {
h.logger.Debug("sending buffered output to terminal",
zap.String("session_id", sessionID),
zap.Int("chunks", len(chunks)),
zap.Int("total_bytes", combined.Len()))
if _, writeErr := wsw.Write(combined.Bytes()); writeErr != nil {
h.logger.Warn("failed to send buffered output",
zap.String("session_id", sessionID),
zap.Error(writeErr))
}
}
}
// Set up direct output
if err := interactiveRunner.SetDirectOutput(processID, wsw); err != nil {
h.logger.Error("failed to set direct output",
zap.String("session_id", sessionID),
zap.String("process_id", processID),
zap.Error(err))
return false
}
*ptyWriter = writer
h.logger.Info("PTY access established",
zap.String("session_id", sessionID),
zap.String("process_id", processID))
return true
return h.setupPtyAccessCommon(sessionID, processID, interactiveRunner, wsw, ptyWriter, getWriter)
}
// handleResize processes a resize command from the WebSocket.
// Returns the parsed dimensions (0, 0 if parsing failed).
// Uses process-specific resize to avoid targeting the wrong process when multiple
// processes exist for the same session (e.g., passthrough + user shell).
// If the process was restarted (old process gone), falls back to session-level resize
// and returns the new process ID.
func (h *TerminalHandler) handleResize(
data []byte,
sessionID string,
processID string,
interactiveRunner *process.InteractiveRunner,
) (cols, rows uint16) {
) (effectiveProcessID string) {
effectiveProcessID = processID
var resize ResizePayload
if err := json.Unmarshal(data, &resize); err != nil {
h.logger.Warn("failed to parse resize command",
zap.String("session_id", sessionID),
zap.Error(err))
return 0, 0
return effectiveProcessID
}
if resize.Cols == 0 || resize.Rows == 0 {
@@ -522,27 +428,80 @@ func (h *TerminalHandler) handleResize(
zap.String("session_id", sessionID),
zap.Uint16("cols", resize.Cols),
zap.Uint16("rows", resize.Rows))
return 0, 0
return effectiveProcessID
}
// Resize triggers lazy process start if not already started
if err := interactiveRunner.ResizeBySession(sessionID, resize.Cols, resize.Rows); err != nil {
h.logger.Warn("failed to resize PTY",
zap.String("session_id", sessionID),
zap.Uint16("cols", resize.Cols),
zap.Uint16("rows", resize.Rows),
zap.Error(err))
} else {
// Resize the specific process by ID to avoid targeting the wrong process.
// If the process was restarted (old ID gone), fall back to session-level resize.
resizeErr := interactiveRunner.ResizeByProcessID(processID, resize.Cols, resize.Rows)
if resizeErr == nil {
h.logger.Debug("PTY resized",
zap.String("session_id", sessionID),
zap.String("process_id", processID),
zap.Uint16("cols", resize.Cols),
zap.Uint16("rows", resize.Rows))
}
// Give the process a moment to start if this was the first resize
time.Sleep(50 * time.Millisecond)
if resizeErr != nil {
h.logger.Debug("process-specific resize failed, trying session-level fallback",
zap.String("session_id", sessionID),
zap.String("process_id", processID),
zap.Error(resizeErr))
effectiveProcessID = h.resizeBySessionFallback(sessionID, processID, resize.Cols, resize.Rows, interactiveRunner)
}
return resize.Cols, resize.Rows
return effectiveProcessID
}
// discoverProcessBySession looks up the current passthrough process for a session.
// Returns the new processID if found and different from oldProcessID.
// This is used when the bridge has a stale processID after a process restart.
func (h *TerminalHandler) discoverProcessBySession(
sessionID string,
oldProcessID string,
interactiveRunner *process.InteractiveRunner,
) string {
_, newProcID, _ := interactiveRunner.GetPtyWriterBySession(sessionID)
if newProcID != "" && newProcID != oldProcessID {
h.logger.Info("discovered new process by session lookup",
zap.String("session_id", sessionID),
zap.String("old_process_id", oldProcessID),
zap.String("new_process_id", newProcID))
return newProcID
}
return oldProcessID
}
// resizeBySessionFallback attempts a session-level resize when the process-specific
// resize failed (e.g., process was restarted). Returns the new processID if found.
func (h *TerminalHandler) resizeBySessionFallback(
sessionID string,
oldProcessID string,
cols, rows uint16,
interactiveRunner *process.InteractiveRunner,
) string {
sessionErr := interactiveRunner.ResizeBySession(sessionID, cols, rows)
if sessionErr != nil {
h.logger.Warn("failed to resize PTY (both process and session)",
zap.String("session_id", sessionID),
zap.String("process_id", oldProcessID),
zap.Uint16("cols", cols),
zap.Uint16("rows", rows),
zap.Error(sessionErr))
return oldProcessID
}
// Session-level resize succeeded — look up the new process ID
_, newProcID, _ := interactiveRunner.GetPtyWriterBySession(sessionID)
if newProcID != "" && newProcID != oldProcessID {
h.logger.Info("resize fallback succeeded, process ID updated",
zap.String("session_id", sessionID),
zap.String("old_process_id", oldProcessID),
zap.String("new_process_id", newProcID))
return newProcID
}
return oldProcessID
}
// handleUserShellWS handles WebSocket connections for user shell terminals.
@@ -780,26 +739,46 @@ func (h *TerminalHandler) setupUserShellPtyAccess(
wsw *wsWriter,
ptyWriter *io.Writer,
) bool {
// Get PTY writer for the user shell
getWriter := func() (io.Writer, error) {
writer, _, err := interactiveRunner.GetUserShellPtyWriter(sessionID, terminalID)
return writer, err
}
return h.setupPtyAccessCommon(sessionID, processID, interactiveRunner, wsw, ptyWriter, getWriter)
}
// setupPtyAccessCommon is the shared implementation for setupPtyAccess and setupUserShellPtyAccess.
// It gets a PTY writer via getWriter, sends buffered output, and sets up direct output.
func (h *TerminalHandler) setupPtyAccessCommon(
sessionID string,
processID string,
interactiveRunner *process.InteractiveRunner,
wsw *wsWriter,
ptyWriter *io.Writer,
getWriter func() (io.Writer, error),
) bool {
writer, err := getWriter()
if err != nil {
h.logger.Debug("user shell PTY writer not ready",
h.logger.Debug("PTY writer not ready yet",
zap.String("session_id", sessionID),
zap.String("terminal_id", terminalID))
zap.String("process_id", processID))
return false
}
// Send buffered output
// Send buffered output to the terminal before switching to direct mode.
// This provides scrollback history when reconnecting to an existing session.
if chunks, ok := interactiveRunner.GetBuffer(processID); ok && len(chunks) > 0 {
var combined bytes.Buffer
for _, chunk := range chunks {
combined.WriteString(chunk.Data)
}
if combined.Len() > 0 {
h.logger.Debug("sending buffered output to terminal",
zap.String("session_id", sessionID),
zap.Int("chunks", len(chunks)),
zap.Int("total_bytes", combined.Len()))
if _, writeErr := wsw.Write(combined.Bytes()); writeErr != nil {
h.logger.Warn("failed to send buffered output",
zap.String("session_id", sessionID),
zap.String("terminal_id", terminalID),
zap.Error(writeErr))
}
}
@@ -807,18 +786,17 @@ func (h *TerminalHandler) setupUserShellPtyAccess(
// Set up direct output
if err := interactiveRunner.SetDirectOutput(processID, wsw); err != nil {
h.logger.Error("failed to set direct output for user shell",
h.logger.Error("failed to set direct output",
zap.String("session_id", sessionID),
zap.String("terminal_id", terminalID),
zap.String("process_id", processID),
zap.Error(err))
return false
}
*ptyWriter = writer
h.logger.Info("user shell PTY access established",
h.logger.Info("PTY access established",
zap.String("session_id", sessionID),
zap.String("terminal_id", terminalID),
zap.String("process_id", processID))
return true
@@ -864,7 +842,4 @@ func (h *TerminalHandler) handleUserShellResize(
zap.Uint16("cols", resize.Cols),
zap.Uint16("rows", resize.Rows))
}
// Give the process a moment to start if this was the first resize
time.Sleep(50 * time.Millisecond)
}
@@ -0,0 +1,63 @@
package websocket
import (
"net/http"
"net/url"
"testing"
)
func TestCheckWebSocketOrigin(t *testing.T) {
tests := []struct {
name string
origin string
host string
want bool
}{
// No origin — allow (non-browser client)
{"no origin", "", "example.com", true},
// Localhost variants
{"http://localhost", "http://localhost", "localhost", true},
{"http://localhost:3000", "http://localhost:3000", "localhost:8080", true},
{"https://localhost", "https://localhost", "localhost", true},
{"http://127.0.0.1", "http://127.0.0.1", "127.0.0.1", true},
{"http://127.0.0.1:3000", "http://127.0.0.1:3000", "127.0.0.1:8080", true},
{"https://127.0.0.1", "https://127.0.0.1", "127.0.0.1", true},
// Same-origin (origin host matches request host)
{"same origin", "https://example.com", "example.com", true},
{"same origin with port", "https://example.com:443", "example.com:8080", true},
// Cross-origin — reject
{"cross origin", "https://evil.com", "example.com", false},
{"cross origin similar", "https://notexample.com", "example.com", false},
// Malformed origin
{"malformed origin", "not-a-url", "example.com", false},
// IPv6 host
{"ipv6 cross origin", "http://[::1]:3000", "example.com:8080", false},
// Empty host — no match possible
{"empty host rejects", "https://example.com", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := &http.Request{
Header: http.Header{},
Host: tt.host,
URL: &url.URL{Host: tt.host},
}
if tt.origin != "" {
r.Header.Set("Origin", tt.origin)
}
got := checkWebSocketOrigin(r)
if got != tt.want {
t.Errorf("checkWebSocketOrigin(origin=%q, host=%q) = %v, want %v",
tt.origin, tt.host, got, tt.want)
}
})
}
}
-1
View File
@@ -49,7 +49,6 @@ type AgentType struct {
DockerTag string `json:"docker_tag"`
DefaultResources ResourceLimits `json:"default_resources"`
EnvironmentVars map[string]string `json:"environment_vars,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
Enabled bool `json:"enabled"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
+37 -12
View File
@@ -1,32 +1,57 @@
# Kandev
Kandev is a local-first AI execution platform for software development work. It pairs a kanban-style task surface with live agent orchestration, file/workspace access, and real-time streaming of changes.
Manage tasks. Orchestrate agents. Review changes. Ship value.
## Start locally
## Quick Start
```bash
npx kandev
```
The launcher downloads the latest release bundle, starts the backend + web app, and opens your browser.
Downloads the latest release, starts the backend + web app, and opens your browser. Data (worktrees, SQLite DB) is stored in `~/.kandev` by default.
## What you get
## What You Get
- **Task-centric execution**: turn tasks into runnable sessions with streaming updates.
- **Workspace control**: shell, file, and git access scoped to each task.
- **Agent orchestration**: run different agent types and resume sessions.
- **Change visibility**: review diffs and track state per task/session.
- **Live UI**: WebSocket-driven updates across tasks, messages, and outputs.
- **Multi-agent support** - Claude Code, Codex, GitHub Copilot, Gemini CLI, Amp, Auggie, OpenCode
- **Integrated workspace** - Terminal, code editor with LSP, git changes, browser preview, and chat
- **Kanban & pipeline views** - Organize tasks with opinionated workflows and gates
- **CLI passthrough** - Drop into raw agent TUI mode for full terminal access
- **Workspace isolation** - Git worktrees prevent concurrent agents from conflicting
- **Session management** - Resume and review agent conversations
## Supported Agents
| Agent | Default Model | Protocol |
|-------|--------------|----------|
| **Claude Code** | Sonnet 4.5 | stream-json |
| **Codex** | GPT-5.2 Codex | Codex |
| **GitHub Copilot** | GPT-4.1 | Copilot SDK |
| **Gemini CLI** | Gemini 3 Flash | ACP |
| **Amp** | Smart Mode | stream-json |
| **Auggie** | Sonnet 4.5 | ACP |
| **OpenCode** | GPT-5 Nano | REST/SSE |
> **Beta** - Under active development. Expect rough edges and breaking changes.
## Requirements
- Node.js (for `npx`)
- Git (for repository access)
- Docker (optional; only needed for containerized agents)
- Git
- Docker (optional - needed for container runtimes)
## Platforms
- macOS (Intel + Apple Silicon)
- Linux (x64)
- Windows (x64) (not tested yet)
- Windows (x64, WSL)
## Learn More
Open source, multi-provider, no telemetry, not tied to any cloud.
See the [GitHub repository](https://github.com/kdlbs/kandev) for architecture, vision, development setup, and contributing guidelines.
## License
[AGPL-3.0](https://github.com/kdlbs/kandev/blob/main/LICENSE)
+1 -1
View File
@@ -96,7 +96,7 @@ function CommandList({
<CommandPrimitive.List
data-slot="command-list"
className={cn(
"no-scrollbar max-h-72 scroll-py-1 outline-none overflow-x-hidden overflow-y-auto",
"max-h-72 scroll-py-1 outline-none overflow-x-hidden overflow-y-auto",
className
)}
{...props}
+5 -4
View File
@@ -21,10 +21,10 @@ function PopoverContent({
className,
align = "center",
sideOffset = 4,
portal = true,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
}: React.ComponentProps<typeof PopoverPrimitive.Content> & { portal?: boolean }) {
const content = (
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
@@ -35,8 +35,9 @@ function PopoverContent({
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
if (!portal) return content
return <PopoverPrimitive.Portal>{content}</PopoverPrimitive.Portal>
}
function PopoverAnchor({
-36
View File
@@ -1,36 +0,0 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
+2 -6
View File
@@ -13,6 +13,7 @@ import {
listTaskSessions,
listWorkspaces,
} from '@/lib/api';
import { toAgentProfileOption } from '@/lib/state/slices/settings/types';
import { listSessionTurns } from '@/lib/api/domains/session-api';
import { fetchTerminals } from '@/lib/api/domains/user-shell-api';
import type { ListMessagesResponse, Task } from '@/lib/types/http';
@@ -151,12 +152,7 @@ export default async function SessionPage({
},
agentProfiles: {
items: agents.agents.flatMap((agent) =>
agent.profiles.map((profile) => ({
id: profile.id,
label: `${profile.agent_display_name} • ${profile.name}`,
agent_id: agent.id,
agent_name: agent.name,
}))
agent.profiles.map((profile) => toAgentProfileOption(agent, profile))
),
version: 0,
},
+2 -5
View File
@@ -8,6 +8,7 @@ import {
listExecutors,
listWorkspaces,
} from '@/lib/api';
import { toAgentProfileOption } from '@/lib/state/slices/settings/types';
export default function SettingsLayout({
children,
@@ -58,11 +59,7 @@ async function SettingsLayoutServer({ children }: { children: React.ReactNode })
},
agentProfiles: {
items: agents.agents.flatMap((agent) =>
agent.profiles.map((profile) => ({
id: profile.id,
label: `${profile.agent_display_name} • ${profile.name}`,
agent_id: agent.id,
}))
agent.profiles.map((profile) => toAgentProfileOption(agent, profile))
),
},
settingsAgents: {
+1 -1
View File
@@ -83,7 +83,7 @@ export const Combobox = memo(function Combobox({
<IconChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className={cn("w-[var(--radix-popover-trigger-width)] min-w-[300px] max-w-none p-0", className)} align="start">
<PopoverContent portal={false} className={cn("w-[var(--radix-popover-trigger-width)] min-w-[300px] max-w-none p-0 max-h-[var(--radix-popover-content-available-height)]", className)} align="start">
<Command value={highlighted} onValueChange={setHighlighted}>
{dropdownLabel ? (
<div className="text-muted-foreground px-2 py-1.5 text-xs border-b">
+3 -3
View File
@@ -1296,7 +1296,7 @@ export function TaskCreateDialog({
type="submit"
variant="default"
className="rounded-none border-0 cursor-pointer gap-1.5 h-full"
disabled={isCreatingTask || !hasTitle || (!repositoryId && !selectedLocalRepo) || !branch || !agentProfileId}
disabled={isCreatingTask || !hasTitle || (!repositoryId && !selectedLocalRepo) || !branch || !agentProfileId || (isCreateMode && (!workspaceId || !effectiveWorkflowId))}
>
{isCreatingTask ? <IconLoader2 className="h-3.5 w-3.5 animate-spin" /> : <IconSend className="h-3.5 w-3.5" />}
{isCreatingTask ? 'Starting...' : 'Start task'}
@@ -1307,7 +1307,7 @@ export function TaskCreateDialog({
type="button"
variant="default"
className="rounded-none border-0 border-l border-primary-foreground/20 px-2 cursor-pointer h-full"
disabled={isCreatingTask || !hasTitle || (!repositoryId && !selectedLocalRepo) || !branch || !agentProfileId}
disabled={isCreatingTask || !hasTitle || (!repositoryId && !selectedLocalRepo) || !branch || !agentProfileId || (isCreateMode && (!workspaceId || !effectiveWorkflowId))}
>
<IconChevronDown className="h-3.5 w-3.5" />
</Button>
@@ -1332,7 +1332,7 @@ export function TaskCreateDialog({
isCreatingTask ||
(isSessionMode
? (!hasDescription && !isPassthroughProfile) || !agentProfileId
: !hasTitle || (!repositoryId && !selectedLocalRepo) || !branch)
: !hasTitle || (!repositoryId && !selectedLocalRepo) || !branch || (isCreateMode && (!workspaceId || !effectiveWorkflowId)))
}
>
{isCreatingSession || isCreatingTask ? (
@@ -1,6 +1,7 @@
import { useEffect } from 'react';
import { useAppStore } from '@/components/state-provider';
import { listAgents, listEnvironments, listExecutors } from '@/lib/api';
import { toAgentProfileOption } from '@/lib/state/slices/settings/types';
export function useSettingsData(enabled = true) {
const executors = useAppStore((state) => state.executors.items);
@@ -48,13 +49,7 @@ export function useSettingsData(enabled = true) {
setSettingsAgents(response.agents);
setAgentProfiles(
response.agents.flatMap((agent) =>
agent.profiles.map((profile) => ({
id: profile.id,
label: `${profile.agent_display_name} • ${profile.name}`,
agent_id: agent.id,
agent_name: agent.name,
cli_passthrough: profile.cli_passthrough,
}))
agent.profiles.map((profile) => toAgentProfileOption(agent, profile))
)
);
})
+16 -1
View File
@@ -1,5 +1,6 @@
import type {
Agent,
AgentProfile,
AvailableAgent,
AgentDiscovery,
CustomPrompt,
@@ -36,9 +37,23 @@ export type AgentProfileOption = {
label: string;
agent_id: string;
agent_name: string;
cli_passthrough?: boolean;
cli_passthrough: boolean;
};
/** Single source of truth for mapping an API Agent+Profile to a store AgentProfileOption. */
export function toAgentProfileOption(
agent: Pick<Agent, 'id' | 'name'>,
profile: Pick<AgentProfile, 'id' | 'agent_display_name' | 'name'> & { cli_passthrough?: boolean },
): AgentProfileOption {
return {
id: profile.id,
label: `${profile.agent_display_name} • ${profile.name}`,
agent_id: agent.id,
agent_name: agent.name,
cli_passthrough: profile.cli_passthrough ?? false,
};
}
export type AgentProfilesState = {
items: AgentProfileOption[];
version: number;
+7 -6
View File
@@ -1,6 +1,7 @@
import type { StoreApi } from 'zustand';
import type { AppState } from '@/lib/state/store';
import type { WsHandlers } from '@/lib/ws/handlers/types';
import { toAgentProfileOption } from '@/lib/state/slices/settings/types';
export function registerAgentsHandlers(store: StoreApi<AppState>): WsHandlers {
return {
'agent.available.updated': (message) => {
@@ -28,11 +29,11 @@ export function registerAgentsHandlers(store: StoreApi<AppState>): WsHandlers {
},
'agent.profile.created': (message) => {
store.setState((state) => {
const label = `${message.payload.profile.agent_display_name} • ${message.payload.profile.name}`;
const agentName = state.settingsAgents.items.find((a) => a.id === message.payload.profile.agent_id)?.name ?? '';
const agent = state.settingsAgents.items.find((a) => a.id === message.payload.profile.agent_id);
const agentStub = { id: message.payload.profile.agent_id, name: agent?.name ?? '' };
const nextProfiles = [
...state.agentProfiles.items.filter((profile) => profile.id !== message.payload.profile.id),
{ id: message.payload.profile.id, label, agent_id: message.payload.profile.agent_id, agent_name: agentName },
toAgentProfileOption(agentStub, message.payload.profile),
];
const nextAgents = state.settingsAgents.items.map((item) =>
item.id === message.payload.profile.agent_id
@@ -67,11 +68,11 @@ export function registerAgentsHandlers(store: StoreApi<AppState>): WsHandlers {
},
'agent.profile.updated': (message) => {
store.setState((state) => {
const label = `${message.payload.profile.agent_display_name} • ${message.payload.profile.name}`;
const agentName = state.settingsAgents.items.find((a) => a.id === message.payload.profile.agent_id)?.name ?? '';
const agent = state.settingsAgents.items.find((a) => a.id === message.payload.profile.agent_id);
const agentStub = { id: message.payload.profile.agent_id, name: agent?.name ?? '' };
const nextProfiles = state.agentProfiles.items.map((profile) =>
profile.id === message.payload.profile.id
? { ...profile, label, agent_id: message.payload.profile.agent_id, agent_name: agentName }
? toAgentProfileOption(agentStub, message.payload.profile)
: profile
);
const nextAgents = state.settingsAgents.items.map((item) =>
-46
View File
@@ -15,8 +15,6 @@ The current implementation uses a **unified binary architecture** instead of sep
- ✅ **Permission request handling** - Auto-approval of workspace indexing and tool permissions
- ✅ **Session resumption** for multi-turn agent conversations
- ✅ WebSocket-first API for all operations (replacing REST)
- 📋 JWT authentication
- 📋 NATS event bus for distributed deployment
---
@@ -48,50 +46,6 @@ flowchart TB
---
## Planned Architecture (Microservices) 📋
### 1. API Gateway (WebSocket-First)
**Port:** 8080
**Purpose:** Single entry point for all client requests via WebSocket
**Responsibilities:**
- Route WebSocket messages to appropriate services
- JWT authentication and authorization
- **WebSocket connection management for all API operations**
- **WebSocket message routing for real-time ACP streaming**
- Rate limiting and request validation
- CORS handling for WebSocket upgrade requests
- API versioning via message schema
**Dependencies:**
- Task Service (internal)
- Agent Manager (internal)
- Orchestrator (internal - WebSocket message routing)
- PostgreSQL (for user auth)
---
### 2. Task Service
**Port:** 8081
**Purpose:** Manage kanban tasks and boards
**Responsibilities:**
- CRUD operations for tasks and boards
- Task state transitions
- Task priority and scheduling metadata
- Publish task events to NATS
**Dependencies:**
- PostgreSQL (tasks, boards, task_events tables)
- NATS (event publishing)
**Events Published:**
- `task.created`
- `task.updated`
- `task.state_changed`
- `task.deleted`
---
### 3. Orchestrator Service
**Port:** 8082
+241
View File
@@ -0,0 +1,241 @@
# Adding a New Agent CLI Integration
This guide explains how to add support for a new coding agent CLI to Kandev.
Agents are defined entirely in Go. The backend discovers them through a registry, and the frontend picks them up automatically via the API - **no frontend changes are needed**.
For a clean reference implementation, see [`gemini.go`](../apps/backend/internal/agent/agents/gemini.go) (ACP protocol). For a CLI-only TUI agent, see the `TUIAgent` declarative type in [`tui_agent.go`](../apps/backend/internal/agent/agents/tui_agent.go).
---
## CLI-Only Agent (Passthrough Only) - Recommended for TUI tools
If an agent has a CLI but no structured protocol (no JSON-RPC, no streaming API), use the **`TUIAgent` declarative type**. The agent runs in a terminal session and input/output passes through a WebSocket - users interact with the full agent TUI directly.
This is the simplest path. A complete agent definition is ~20 lines.
### Step 1: Create the agent file
Create `apps/backend/internal/agent/agents/{agent_id}.go`:
```go
package agents
func NewClaude() *TUIAgent {
return NewTUIAgent(TUIAgentConfig{
AgentID: "claude",
AgentName: "Claude",
Command: "claude",
Desc: "Claude Code - an agentic coding tool by Anthropic.",
// Optional: let users select a model in profile settings.
// The {model} placeholder is replaced with the user's chosen model at launch.
// Omit this if the CLI doesn't accept a model flag.
ModelFlag: NewParam("--model", "{model}"),
})
}
```
Logos are optional - the UI shows a blank placeholder when none is provided. To add them, embed SVGs and pass `LogoLight` / `LogoDark`:
```go
package agents
import _ "embed"
//go:embed logos/claude_light.svg
var claudeLogoLight []byte
//go:embed logos/claude_dark.svg
var claudeLogoDark []byte
func NewClaude() *TUIAgent {
return NewTUIAgent(TUIAgentConfig{
AgentID: "claude",
AgentName: "Claude",
Command: "claude",
Desc: "Claude Code - an agentic coding tool by Anthropic.",
ModelFlag: NewParam("--model", "{model}"),
LogoLight: claudeLogoLight,
LogoDark: claudeLogoDark,
})
}
```
`TUIAgentConfig` fields (all optional fields have sensible defaults):
| Field | Required | Description |
|-------|----------|-------------|
| `AgentID` | Yes | Unique lowercase identifier (e.g. `"claude"`) |
| `AgentName` | Yes | Display name (e.g. `"Claude"`) |
| `Command` | Yes | Binary name to run (e.g. `"claude"`) |
| `Desc` | Yes | Description shown in the UI |
| `ModelFlag` | No | Model CLI flag, e.g. `NewParam("--model", "{model}")`. Lets users pick a model in profile settings. Omit if the CLI doesn't support model selection. |
| `CommandArgs` | No | Extra args appended after `Command` (e.g. `[]string{"--debug"}`) |
| `WaitForTerm` | No | When `true`, delays process start until the terminal WebSocket connects and sends its first resize event. Use this for TUI apps that need accurate terminal dimensions on startup (e.g. ncurses-based UIs). Most agents don't need this. Defaults to `false`. |
| `LogoLight` / `LogoDark` | No | Embedded SVG bytes for light/dark themes. The UI shows a blank placeholder if omitted. |
| `DetectOpts` | No | Custom detection options. Defaults to `WithCommand(Command)` which checks if the binary is in `$PATH`. |
### Step 2: Register the agent
Add your agent to `LoadDefaults()` in [`apps/backend/internal/agent/registry/registry.go`](../apps/backend/internal/agent/registry/registry.go):
```go
func (r *Registry) LoadDefaults() {
all := []agents.Agent{
// ... existing agents ...
agents.NewMyAgent(), // add here
}
// ...
}
```
### Step 3: Build and test
```bash
make -C apps/backend build && make -C apps/backend test && make -C apps/backend lint
```
Note: passthrough-only agents provide terminal interaction only. There are no structured chat messages, tool call visibility, or progress tracking in the chat UI.
---
## Adding a New Agent (Full Integration)
For agents with a structured protocol (JSON-RPC, streaming JSON, etc.), implement the full [`Agent`](../apps/backend/internal/agent/agents/agent.go) interface.
### Step 1: Create the agent definition file
Create `apps/backend/internal/agent/agents/{agent_id}.go`.
This file implements the [`Agent`](../apps/backend/internal/agent/agents/agent.go) interface. See the interface definition in `agent.go` for the full contract.
Embed `StandardPassthrough` to get CLI passthrough support for free:
```go
type MyAgent struct {
StandardPassthrough
}
func NewMyAgent() *MyAgent {
return &MyAgent{
StandardPassthrough: StandardPassthrough{
PermSettings: myAgentPermSettings,
Cfg: PassthroughConfig{
Supported: true,
Label: "CLI Passthrough",
Description: "Show terminal directly instead of chat interface",
PassthroughCmd: NewCommand("myagent"),
ModelFlag: NewParam("--model", "{model}"),
PromptFlag: NewParam("--prompt", "{prompt}"),
IdleTimeout: 3 * time.Second,
BufferMaxBytes: DefaultBufferMaxBytes,
},
},
}
}
```
Key implementation notes:
- **`BuildCommand()`** returns the CLI command for structured protocol mode (the agent communicates via stdin/stdout with a protocol adapter). Include the protocol flag here (e.g. `--experimental-acp`, `--stream-json`).
- **`Runtime()`** returns configuration used when running the agent in Docker or as a standalone process. Set `Protocol` to tell the adapter factory which transport to use.
- **`IsInstalled()`** uses the `Detect()` helper with `WithFileExists()` to check for known installation paths. Set `SupportsMCP` and `MCPConfigPaths` on the result.
- **`ListModels()`** can return a static list or dynamically query the CLI. Use `execAndParse()` from `helpers.go` for dynamic model discovery.
- Use `Cmd()` builder for constructing commands fluently: `Cmd("myagent", "--flag").Model(...).Settings(...).Build()`.
### Step 2: Add logos (optional)
Logos are optional - the UI shows a blank placeholder when none is provided. To add them, place SVGs in:
```
apps/backend/internal/agent/agents/logos/{agent_id}_light.svg
apps/backend/internal/agent/agents/logos/{agent_id}_dark.svg
```
Embed them in your agent file:
```go
//go:embed logos/myagent_light.svg
var myagentLogoLight []byte
//go:embed logos/myagent_dark.svg
var myagentLogoDark []byte
```
### Step 3: Register the agent
Add your agent to `LoadDefaults()` in [`apps/backend/internal/agent/registry/registry.go`](../apps/backend/internal/agent/registry/registry.go):
```go
func (r *Registry) LoadDefaults() {
all := []agents.Agent{
// ... existing agents ...
agents.NewMyAgent(), // add here
}
// ...
}
```
That's it for registration. The frontend discovers agents through the API automatically.
### Step 4: Choose a protocol
Check [`apps/backend/pkg/agent/protocol.go`](../apps/backend/pkg/agent/protocol.go) for available protocols:
| Protocol | Constant | Transport | Used By |
|----------|----------|-----------|---------|
| ACP | `ProtocolACP` | JSON-RPC 2.0 over stdin/stdout | Gemini, Auggie |
| stream-json | `ProtocolClaudeCode` | Streaming JSON over stdin/stdout | Claude Code |
| Codex | `ProtocolCodex` | JSON-RPC variant over stdin/stdout | Codex |
| OpenCode | `ProtocolOpenCode` | REST/SSE over HTTP | OpenCode |
| Copilot | `ProtocolCopilot` | Go SDK (JSON-RPC internally) | GitHub Copilot |
| Amp | `ProtocolAmp` | Streaming JSON over stdin/stdout | Amp |
**If an existing protocol fits your agent**, reuse it - set `Protocol` in `Runtime()`. The adapter factory in `factory.go` selects the right transport automatically based on this value.
**If you need a new protocol**, you'll need to:
1. Add a new `Protocol` constant in `apps/backend/pkg/agent/protocol.go`
2. Create a transport adapter in `apps/backend/internal/agentctl/server/adapter/transport/{protocol}/`
3. Add the case to the factory switch in [`apps/backend/internal/agentctl/server/adapter/factory.go`](../apps/backend/internal/agentctl/server/adapter/factory.go)
### Step 5: Build and test
```bash
make -C apps/backend build && make -C apps/backend test && make -C apps/backend lint
```
Start the dev server and verify:
- The agent appears in the agent selector in the UI
- Agent execution works (start a task, send a prompt)
- Passthrough mode works (toggle to CLI passthrough in the session)
- Model listing works
---
## Updating an Existing Agent
| Change | Where |
|--------|-------|
| Update CLI version | `BuildCommand()` and `Runtime().Cmd` in the agent file |
| Add/remove models | `ListModels()` - update static list or dynamic command |
| Update permissions | `PermissionSettings()` variable and `PassthroughConfig` |
| Update Docker image | `Runtime()` - change `Image`/`Tag` fields |
| Change protocol | `Runtime().Protocol` in the agent file |
---
## File Reference
| File | When to modify |
|------|---------------|
| `apps/backend/internal/agent/agents/{agent_id}.go` | Always - agent definition |
| `apps/backend/internal/agent/agents/logos/{agent_id}_{light,dark}.svg` | Optional - agent logos (UI shows blank placeholder if omitted) |
| `apps/backend/internal/agent/registry/registry.go` | Always - register in `LoadDefaults()` |
| `apps/backend/internal/agent/agents/tui_agent.go` | Never - provides `TUIAgent` declarative type (read-only reference) |
| `apps/backend/pkg/agent/protocol.go` | Only if adding a new protocol |
| `apps/backend/internal/agentctl/server/adapter/factory.go` | Only if adding a new protocol |
| `apps/backend/internal/agentctl/server/adapter/transport/{proto}/` | Only if adding a new protocol |
| `apps/backend/internal/agent/agents/passthrough.go` | Never - provides `StandardPassthrough` (read-only reference) |
| `apps/backend/internal/agent/agents/agent.go` | Never - defines the `Agent` interface (read-only reference) |
+2 -2
View File
@@ -21,7 +21,7 @@ database:
path: ./kandev.db
```
No additional setup is needed — the database file is created automatically on first run.
No additional setup is needed - the database file is created automatically on first run.
## PostgreSQL
@@ -71,4 +71,4 @@ KANDEV_DATABASE_PASSWORD=your-password \
kandev
```
Tables are created automatically on first run — no manual migrations needed.
Tables are created automatically on first run - no manual migrations needed.
+1 -1
View File
@@ -14,7 +14,7 @@ Git operations are executed **in agentctl**, not in the backend. This ensures co
| **Push** | Worktree → Remote | Push local commits to remote |
| **Rebase** | Base → Worktree | Rebase worktree branch onto base branch (rewrites history) |
| **Merge** | Base → Worktree | Merge base branch into worktree branch (creates merge commit) |
| **Abort** | — | Abort an in-progress merge or rebase |
| **Abort** | - | Abort an in-progress merge or rebase |
## Architecture
+21
View File
@@ -0,0 +1,21 @@
# Roadmap
High-level direction for the project. This is not a commitment - priorities shift as we learn more.
## Now
- Stability and bug fixes across all agent integrations
- Improved plan mode - richer plan editing, version history, plan diffs
## Next
- Github integration - link tasks to GitHub issues, PRs
- Workflow templates sharing - import/export workflows
- Mobile-friendly UI - orchestrate and review from your phone
- Remote SSH runtime - run agents on remote servers over SSH
- Linear / Jira integration - sync tasks and workflows with popular project management tools
## Later
- Kubernetes operator - auto-scaling agent workloads in a cluster
- Analytics dashboard - agent performance, cost tracking, success rates
+8 -8
View File
@@ -2,7 +2,7 @@
## Overview
The stats system provides workspace-level analytics about tasks, agent sessions, repository activity, and git commits. It computes everything on-demand from existing tables — there are no dedicated stats tables.
The stats system provides workspace-level analytics about tasks, agent sessions, repository activity, and git commits. It computes everything on-demand from existing tables - there are no dedicated stats tables.
**Route**: `/stats` (with `?range=week|month|all`)
@@ -101,10 +101,10 @@ Key indexes: tasks(workspace_id, created_at), task_sessions(task_id, started_at)
## Known Limitations
1. **No caching** — every page load runs all 7 queries
2. **No real-time updates** — single fetch on page load, no WebSocket/polling
3. **Git tracking gaps** — only commits made during task sessions are tracked
4. **Duration precision** — `julianday()` returns float, cast to int64 (minor precision loss)
5. **Incomplete turns** — turns with NULL `completed_at` count in totals but contribute 0ms to duration
6. **"Month" = 30 days** — not a calendar month
7. **Sequential queries** — the 7 repo calls in the handler run sequentially, not in parallel
1. **No caching** - every page load runs all 7 queries
2. **No real-time updates** - single fetch on page load, no WebSocket/polling
3. **Git tracking gaps** - only commits made during task sessions are tracked
4. **Duration precision** - `julianday()` returns float, cast to int64 (minor precision loss)
5. **Incomplete turns** - turns with NULL `completed_at` count in totals but contribute 0ms to duration
6. **"Month" = 30 days** - not a calendar month
7. **Sequential queries** - the 7 repo calls in the handler run sequentially, not in parallel
+104
View File
@@ -0,0 +1,104 @@
# Workflows
Kandev ships with four workflow templates. Each defines a sequence of steps with automated transitions - agents start, stop, and move between steps based on events like entering a step, sending a message, or an agent completing its turn.
You can use these as-is or **create custom workflows** tailored to your or your team.
## Default Workflows
### Kanban
Classic kanban board with automated agent execution. Good for straightforward tasks where you want to assign work, let the agent run, and review the result.
**Steps:** Backlog → In Progress → Review → Done
| Step | What happens |
|------|-------------|
| **Backlog** | Tasks wait here. Sending a message moves the task to In Progress. |
| **In Progress** | Agent starts automatically. When it completes, the task moves to Review. |
| **Review** | You review the agent's work. Sending a message moves it back to In Progress for another iteration. |
| **Done** | Final state. Sending a message reopens the task in In Progress. |
**When to use it:**
- Bug fixes with clear reproduction steps
- Small, well-scoped features
- Chores and refactoring tasks
- Any task where you want a simple assign → run → review loop
---
### Plan & Build
Two-phase workflow where the agent first creates a plan for your review, then implements it. The plan is saved as a structured document you can edit before the agent proceeds to implementation.
**Steps:** Todo → Plan → Implementation → Done
| Step | What happens |
|------|-------------|
| **Todo** | Backlog. Move tasks here when they're ready to be planned. |
| **Plan** | Agent analyzes the task and creates a detailed implementation plan - requirements, files to modify, step-by-step approach, risks. Supports mermaid diagrams. The plan is saved via MCP tool and the agent stops for your review. You can edit the plan in the UI before moving forward. |
| **Implementation** | Agent retrieves the plan (including your edits), acknowledges modifications, and implements step-by-step. Moves to Done on completion. |
| **Done** | Final state. |
**When to use it:**
- Features that benefit from upfront design
- Tasks where you want to steer the approach before code is written
- Larger changes spanning multiple files
- When working with less familiar codebases where you want to validate the agent's understanding first
---
### Architecture
Focused on design and architecture. The agent creates technical designs for your review - no implementation happens in this workflow. Useful for capturing architectural decisions before any code is written.
**Steps:** Ideas → Planning → Review → Approved
| Step | What happens |
|------|-------------|
| **Ideas** | Backlog of architectural ideas and proposals. |
| **Planning** | Agent analyzes the task, asks clarifying questions, and produces an architectural design with mermaid diagrams. Saves the design and stops for your review. |
| **Review** | You review the design. Sending a message moves it back to Planning for revisions. |
| **Approved** | Design is accepted. Ready for implementation (in a separate task/workflow). |
**When to use it:**
- System design and technical RFCs
- Evaluating approaches before committing to implementation
- Cross-team architectural proposals
- Breaking down large projects into implementable pieces
---
### PR Review
Track pull requests through automated code review. The agent reviews changed files and produces structured findings.
**Steps:** Waiting → Review → Done
| Step | What happens |
|------|-------------|
| **Waiting** | PR queue. Sending a message starts the review process. |
| **Review** | Agent reviews the changed files in the git worktree. If there are uncommitted changes, it reviews those; otherwise, it reviews commits that diverged from the main branch. Findings are organized into four categories: **BUG**, **IMPROVEMENT**, **NITPICK**, **PERFORMANCE** - each with file:line references. |
| **Done** | Review complete. Sending a message moves it back to Review for another pass. |
**When to use it:**
- Automated first-pass code review before human review
- Catching bugs, performance issues, and style problems early
- Reviewing agent-generated PRs from other workflows
- Supplementing human review on large changesets
---
## Tips
### Repository-Level Agent Configuration
Each repository should maintain its own agent configuration - `CLAUDE.md`, `AGENTS.md`, custom skills, MCP servers, and any agent-specific instructions. This keeps agent behavior consistent with the codebase it's working on, regardless of who triggers the task or which workflow runs it.
When an agent is assigned a task in a repository, it picks up that repository's configuration automatically. Coding standards, project context, and tooling constraints travel with the code, not with the platform.
### Cross-Repository Workflows
Workflow pipelines often span multiple repositories - a backend change triggers a client update, an infrastructure change follows a service deployment. Each step in the pipeline runs an agent inside a specific repository, and that agent should use the repository's own AI harness (prompts, rules, skills) rather than a shared global config.
This keeps each agent grounded in the right context. A backend agent follows backend conventions, a frontend agent follows frontend conventions, even when they're part of the same pipeline.