diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..df77a8c --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +node_modules/ +*.jsonl +exec-approvals.json +ide-agent-kit.json +.env +*.log +/tmp/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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 +. diff --git a/README.md b/README.md index 9909b0e..2e7899f 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,93 @@ -# IDE Agent Kit — v0.1 +# IDE Agent Kit - v0.1 -Let IDE AIs (Claude Code, Codex, Cursor, VS Code agents, local LLM assistants) participate in team workflows. +Let IDE AIs (Claude Code, Codex, Cursor, VS Code agents, local LLM assistants) participate in team workflows - including realtime multi-agent communication via shared chat rooms. ## How it works **Primary path: Webhooks (seconds)** GitHub event → webhook server → normalized JSONL queue → IDE agent reads queue → acts → receipt. -This is the fast path. Events arrive in seconds. Use this when your IDE supports webhook ingestion or can poll a local queue file. -**Fallback path: tmux (minutes)** -Poller checks for events → sends command to tmux session → IDE agent wakes up → acts → receipt. -Use this when webhooks aren't available (e.g., no public endpoint) or as a backup. +**Realtime path: Room poller (seconds)** +Poller watches chat room → detects new messages → nudges IDE agent via tmux → agent reads and responds. +Three agents tested concurrently with <10s response times. + +**Fallback path: tmux runner** +Run allowlisted commands in a named tmux session, capture output + exit code. ## v0.1 primitives -1. **Webhook relay** (primary) — ingest GitHub webhooks, normalize to a stable JSON schema, append to a local queue. -2. **tmux runner** (fallback) — run allowlisted commands in a named tmux session, capture output + exit code. -3. **Receipts** — append-only JSONL receipts with trace IDs + idempotency keys. -4. **IDE init** — generate starter configs for Claude Code, Codex, Cursor, or VS Code. +1. **Webhook relay** - ingest GitHub webhooks, normalize to a stable JSON schema, append to a local queue. +2. **Room poller** - watch Ant Farm chat rooms, auto-ack task requests, nudge IDE agents via tmux. +3. **tmux runner** - run allowlisted commands in a named tmux session, capture output + exit code. +4. **Receipts** - append-only JSONL receipts with trace IDs + idempotency keys. +5. **Session keepalive** - prevent macOS display/idle sleep for long-running remote sessions. +6. **IDE init** - generate starter configs for Claude Code, Codex, Cursor, or VS Code. No dependencies. Node.js ≥ 18 only. +## Testing setup - 3 agents, realtime comms + +This kit has been tested with three IDE agents from different AI providers, each running in its own IDE on separate machines - potentially in different countries. They communicate through shared [Ant Farm](https://antfarm.world) chat rooms over the internet, with no direct connections between them: + +| Agent | Handle | Model | IDE / App | Machine | Poller | +|-------|--------|-------|-----------|---------|--------| +| claudemm | @claudemm | Claude Opus 4.6 | Claude Code CLI | Mac mini | `scripts/room-poll.sh` (10s) | +| antigravity | @antigravity | GPT 5.3 Codex | Codex macOS app | MacBook | `tools/antigravity_room_autopost.sh` (8s) | +| geminimb | @geminiMB | Gemini 3.1 | Antigravity macOS app | MacBook | `tools/geminimb_room_autopost.sh` (8s) | + +All three agents share the same rooms (`feature-admin-planning`, `thinkoff-development`, `lattice-qcd`) and respond to messages within 3-10 seconds. Each agent only needs an API key and internet access - no VPN, shared filesystem, or direct networking between machines. + +### How it works + +Each agent runs in its own tmux session on its own machine. A background poller script watches the room API for new messages. When a new message arrives: + +1. The poller detects it (every 8-10s) +2. If from the owner and looks like a task request → posts an immediate auto-ack +3. Sends a tmux keystroke nudge (`check rooms` + Enter) to the IDE agent's session +4. The IDE agent reads the full message and responds with its own intelligence + +### Running an agent + +```bash +# Claude Code (@claudemm) - uses the generic poller +export IAK_API_KEY=xfb_your_antfarm_key +export IAK_SELF_HANDLES="@claudemm,claudemm" +export IAK_TARGET_HANDLE="@claudemm" +export IAK_TMUX_SESSION="claude" +export IAK_POLL_INTERVAL=10 +nohup ./scripts/room-poll.sh > /tmp/poll.log 2>&1 & + +# Codex (@antigravity) - smart poller with real codex exec replies +export ANTIGRAVITY_API_KEY=xfb_your_antfarm_key +export ROOMS=feature-admin-planning +export SMART_MODE=1 +export CODEX_APPROVAL_POLICY=on-request +export CODEX_SANDBOX_MODE=workspace-write +./tools/antigravity_room_autopost.sh tmux start +./tools/antigravity_room_autopost.sh tmux status +./tools/antigravity_room_autopost.sh tmux stop + +# Gemini (@geminiMB) - dedicated poller with tmux lifecycle +export IAK_API_KEY=xfb_your_antfarm_key # or GEMINIMB_API_KEY +./tools/geminimb_room_autopost.sh tmux start +./tools/geminimb_room_autopost.sh tmux status +./tools/geminimb_room_autopost.sh tmux stop +``` + +### Keeping sessions alive + +On macOS, prevent display/idle sleep so remote (VNC/SSH) sessions don't freeze: + +```bash +# Via CLI +node bin/cli.mjs keepalive start +node bin/cli.mjs keepalive status +node bin/cli.mjs keepalive stop + +# Or directly +caffeinate -d -i -s & +``` + ## Quick start ```bash @@ -47,6 +114,172 @@ node bin/cli.mjs receipt tail --n 5 node bin/cli.mjs emit --to https://example.com/webhook --json receipt.json ``` +## Room Poller + +The repo includes three poller implementations for watching Ant Farm chat rooms: + +**Generic poller** (`scripts/room-poll.sh` + `scripts/room-poll-check.py`): +- Works with any agent (Claude Code, Codex, etc.) +- Env-var-driven, no hardcoded secrets +- Auto-acks task requests from the owner +- Nudges IDE agent via tmux keystrokes + +**Poll command (`ide-agent-kit poll`) nudge modes**: +- `poller.nudge_mode = "tmux"` (default): send `tmux send-keys` +- `poller.nudge_mode = "command"`: execute `poller.nudge_command` with `IAK_NUDGE_TEXT` in env (useful for GUI agents) +- `poller.nudge_mode = "none"`: queue-only polling, no nudge side effects + +### Codex GUI setup (macOS) + +For Codex Desktop GUI (non-tmux) use command-mode nudging: + +```json +{ + "poller": { + "rooms": "thinkoff-development,feature-admin-planning,lattice-qcd", + "handle": "@CodexMB", + "interval_sec": 8, + "api_key": "antfarm_xxx", + "seen_file": "/tmp/codex-room-seen.txt", + "nudge_mode": "command", + "nudge_command": "/ABSOLUTE/PATH/ide-agent-kit/tools/codex_gui_nudge.sh" + }, + "tmux": { + "ide_session": "codex", + "nudge_text": "check room and respond [codex]" + } +} +``` + +Run: + +```bash +node bin/cli.mjs poll --config /ABSOLUTE/PATH/ide-agent-kit-codex.json +``` + +macOS permissions required for GUI keystroke injection: +- Privacy & Security → Accessibility: allow Terminal/iTerm (whichever runs the poller) +- Privacy & Security → Automation: allow Terminal/iTerm to control `System Events` + +**Gemini poller** (`tools/geminimb_room_autopost.sh`): +- Self-contained bash script with tmux lifecycle management +- Built-in hearing check responses with latency reporting +- Configurable mention-only or all-message modes + +**Codex smart poller** (`tools/antigravity_room_autopost.sh`): +- Self-contained bash script with tmux lifecycle management +- All-message intake mode with stale/backlog protection +- Smart path uses `codex exec` to generate real replies +- Canned poller replies only for hearing/webhook checks + +### Env vars (generic poller) + +| Variable | Default | Description | +|----------|---------|-------------| +| `IAK_API_KEY` | (required) | Ant Farm API key | +| `IAK_ROOMS` | `thinkoff-development,feature-admin-planning,lattice-qcd` | Rooms to watch | +| `IAK_SELF_HANDLES` | `@claudemm,claudemm` | This agent's handles (skip own messages) | +| `IAK_TARGET_HANDLE` | `@claudemm` | Handle used in ack messages | +| `IAK_OWNER_HANDLE` | `petrus` | Only auto-ack from this user | +| `IAK_TMUX_SESSION` | `claude` | tmux session to nudge | +| `IAK_POLL_INTERVAL` | `10` | Seconds between polls | +| `IAK_ACK_ENABLED` | `1` | Auto-ack task requests (`1`/`0`) | +| `IAK_NUDGE_TEXT` | `check rooms` | Text sent to tmux on new messages | +| `IAK_LISTEN_MODE` | `all` | Filter: `all`, `humans`, `tagged`, or `owner` | +| `IAK_BOT_HANDLES` | (empty) | Comma-separated bot handles for `humans` mode | +| `IAK_FETCH_LIMIT` | `20` | Messages per room per poll | + +### Env vars (Codex smart poller) + +| Variable | Default | Description | +|----------|---------|-------------| +| `ANTIGRAVITY_API_KEY` | (required) | Ant Farm API key | +| `ROOMS` | `feature-admin-planning` | Comma-separated rooms to watch | +| `POLL_INTERVAL` | `8` | Seconds between polls | +| `FETCH_LIMIT` | `30` | Messages per room request | +| `MENTION_ONLY` | `0` | Intake mode: `0` all messages, `1` mention only | +| `SMART_MODE` | `1` | `1` enables `codex exec` real-response generation | +| `CODEX_WORKDIR` | repo root | Working directory for `codex exec` | +| `CODEX_APPROVAL_POLICY` | `on-request` | Codex approval policy for smart replies | +| `CODEX_SANDBOX_MODE` | `workspace-write` | Codex sandbox mode for smart replies | +| `MAX_REPLY_AGE_SEC` | `900` | Skip stale messages older than this age | +| `SKIP_PRESTART_BACKLOG` | `1` | Skip messages older than process start | + +## Integrations + +### GitHub Webhooks (`src/webhook-server.mjs`) + +Receives GitHub webhook events, verifies HMAC signatures, normalizes them to a stable JSON schema, and appends to a local JSONL queue. Optionally nudges a tmux session when events arrive. + +Supported events: `pull_request.opened`, `pull_request.synchronize`, `pull_request.closed`, `push`, `issue_comment.created`, `issues.opened`. + +```bash +# Start the webhook server +node bin/cli.mjs serve --port 8787 + +# Configure GitHub to send webhooks to: +# http://your-host:8787/webhook +# Set a webhook secret in config for HMAC verification + +# Ant Farm webhooks are also accepted at: +# http://your-host:8787/antfarm +``` + +Config keys: `listen.port`, `github.webhook_secret`, `github.event_kinds`, `queue.path`. + +### OpenClaw Bot Fleet (`src/openclaw-*.mjs`) + +Five modules for managing an [OpenClaw](https://openclaw.dev) multi-agent bot fleet via its CLI. Since the OpenClaw gateway uses WebSocket (not HTTP) for RPC, all modules shell out to the `openclaw` CLI, optionally over SSH for cross-user setups. + +**Gateway** (`src/openclaw-gateway.mjs`): +- Start, stop, restart the OpenClaw gateway +- Check gateway status (deep health check) +- Config: `openclaw.home`, `openclaw.bin`, `openclaw.ssh` + +**Sessions** (`src/openclaw-sessions.mjs`): +- Send messages to agents, list active sessions +- Agent-to-agent communication via `openclaw agent` CLI +- Supports sending to specific agents by name + +**Exec Approvals** (`src/openclaw-exec.mjs`): +- Governance layer for agent command execution +- Manages an approval queue (pending → allow/deny) +- Reads OpenClaw's native exec-approvals allowlist (per-agent, glob-based) +- Files: `~/.openclaw/exec-approvals.json` (native), `./exec-approvals.json` (queue) + +**Hooks** (`src/openclaw-hooks.mjs`): +- Register and manage event hooks for agents +- Events: `message:received`, `message:sent`, `command:new`, `command:reset`, `command:stop`, `agent:bootstrap`, `gateway:startup` +- Hook locations: `workspace/hooks/` (per-agent) and `~/.openclaw/hooks/` (shared) + +**Cron** (`src/openclaw-cron.mjs`): +- Scheduled task management via `openclaw cron` CLI +- List, add, remove scheduled tasks for agents + +```bash +# OpenClaw config (in team-relay config file) +{ + "openclaw": { + "home": "/path/to/openclaw", + "bin": "/opt/homebrew/bin/openclaw", + "ssh": "family@localhost" + } +} +``` + +### Ant Farm Chat Rooms (`scripts/room-poll*.`) + +See [Room Poller](#room-poller) above. Provides realtime multi-agent communication via shared chat rooms at [antfarm.world](https://antfarm.world). + +### Other modules + +- **Receipts** (`src/receipt.mjs`) - Append-only JSONL receipt log with trace IDs and idempotency keys +- **Emit** (`src/emit.mjs`) - Send receipts/payloads to external webhook URLs +- **Memory** (`src/memory.mjs`) - Persistent key-value memory for agents across sessions +- **Session Keepalive** (`src/session-keepalive.mjs`) - macOS `caffeinate` management for remote sessions +- **tmux Runner** (`src/tmux-runner.mjs`) - Run allowlisted commands in tmux sessions with output capture +- **Watch** (`src/watch.mjs`) - File watcher for JSONL queue changes + ## Naming convention (frozen) - JSON fields (events, receipts, config): **snake_case** @@ -60,19 +293,20 @@ ide-agent-kit tmux run --cmd [--session ] [--cwd ] [--time ide-agent-kit emit --to --json ide-agent-kit receipt tail [--n ] ide-agent-kit init [--ide ] [--profile ] +ide-agent-kit keepalive [--pid-file ] [--heartbeat-sec ] ``` ## Config See `config/team-relay.example.json` for the full config shape. Key sections: -- `listen` — host/port for webhook server -- `queue.path` — where normalized events are appended (JSONL) -- `receipts.path` — where action receipts are appended (JSONL) -- `tmux.allow` — command allowlist (prefix match) -- `tmux.default_session` — tmux session name -- `github.webhook_secret` — HMAC secret for signature verification -- `github.event_kinds` — which GitHub events to accept +- `listen` - host/port for webhook server +- `queue.path` - where normalized events are appended (JSONL) +- `receipts.path` - where action receipts are appended (JSONL) +- `tmux.allow` - command allowlist (prefix match) +- `tmux.default_session` - tmux session name +- `github.webhook_secret` - HMAC secret for signature verification +- `github.event_kinds` - which GitHub events to accept ### Low-friction profile @@ -86,8 +320,8 @@ This profile broadens `tmux.allow` to include common read/build/test commands (` ## Schemas -- `schemas/event.normalized.json` — normalized inbound event -- `schemas/receipt.json` — action receipt +- `schemas/event.normalized.json` - normalized inbound event +- `schemas/receipt.json` - action receipt ## Tests @@ -98,3 +332,14 @@ node --test test/*.test.mjs ## Example flow See `examples/flow-pr-opened.md` for a complete PR → test → receipt walkthrough. + +## License + +GNU Affero General Public License v3.0 (AGPL-3.0). See [LICENSE](LICENSE) for details. +All source files include `SPDX-License-Identifier: AGPL-3.0-only`. +Source code for this deployment is available at commit [be641cf](https://github.com/ThinkOffApp/team-relay/tree/be641cf). + +## Ant Farm Helpers + +- `examples/antfarm/gemini_from_claude.sh` — non-interactive Gemini wrapper for room/autopost bots. + Uses `gemini -p` with a hard timeout to prevent stuck polling loops. diff --git a/bin/cli.mjs b/bin/cli.mjs index 171cbeb..019fd50 100755 --- a/bin/cli.mjs +++ b/bin/cli.mjs @@ -1,4 +1,7 @@ #!/usr/bin/env node + +// SPDX-License-Identifier: AGPL-3.0-only + import { parseArgs } from 'node:util'; import { loadConfig } from '../src/config.mjs'; import { tmuxRun } from '../src/tmux-runner.mjs'; diff --git a/examples/antfarm/gemini_from_claude.sh b/examples/antfarm/gemini_from_claude.sh new file mode 100755 index 0000000..39cea6b --- /dev/null +++ b/examples/antfarm/gemini_from_claude.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# gemini_from_claude.sh +# Non-interactive Gemini wrapper for Claude/Codex-style automation scripts. +# Enforces a hard timeout so polling bots do not hang indefinitely. + +set -euo pipefail + +MODEL="${GEMINI_MODEL:-gemini-3.1-pro}" +TIMEOUT_SEC="${GEMINI_TIMEOUT_SEC:-45}" +PROMPT="" +FALLBACK_MODEL="${GEMINI_FALLBACK_MODEL:-}" +GEMINI_BIN="${GEMINI_BIN:-/opt/homebrew/bin/gemini}" + +usage() { + cat <<'EOF' +Usage: gemini_from_claude.sh [options] [prompt words...] + +Options: + -m, --model Gemini model (default: GEMINI_MODEL or gemini-3.1-pro) + -t, --timeout Hard timeout in seconds (default: GEMINI_TIMEOUT_SEC or 45) + -p, --prompt Prompt text. If omitted, stdin is used. + --fallback-model Optional fallback model if primary returns non-zero. + -h, --help Show this help. +EOF +} + +while [[ $# -gt 0 ]]; do + case "$1" in + -m|--model) + MODEL="${2:-}" + shift 2 + ;; + -t|--timeout) + TIMEOUT_SEC="${2:-}" + shift 2 + ;; + -p|--prompt) + PROMPT="${2:-}" + shift 2 + ;; + --fallback-model) + FALLBACK_MODEL="${2:-}" + shift 2 + ;; + -h|--help) + usage + exit 0 + ;; + --) + shift + PROMPT="$*" + break + ;; + *) + if [[ -z "$PROMPT" ]]; then + PROMPT="$1" + else + PROMPT="$PROMPT $1" + fi + shift + ;; + esac +done + +if [[ -z "$PROMPT" ]]; then + if [[ ! -t 0 ]]; then + PROMPT="$(cat)" + fi +fi + +if [[ -z "$PROMPT" ]]; then + echo "No prompt provided." >&2 + exit 2 +fi + +if [[ ! "$TIMEOUT_SEC" =~ ^[0-9]+$ ]] || [[ "$TIMEOUT_SEC" -lt 1 ]]; then + echo "Invalid timeout: $TIMEOUT_SEC" >&2 + exit 2 +fi + +if [[ ! -x "$GEMINI_BIN" ]]; then + if command -v gemini >/dev/null 2>&1; then + GEMINI_BIN="$(command -v gemini)" + else + echo "Gemini CLI not found." >&2 + exit 127 + fi +fi + +# Load shell profile so GEMINI_API_KEY / auth envs mirror normal CLI sessions. +if [[ -f "$HOME/.zprofile" ]]; then + # shellcheck disable=SC1090 + source "$HOME/.zprofile" >/dev/null 2>&1 || true +fi + +python3 - "$TIMEOUT_SEC" "$GEMINI_BIN" "$MODEL" "$PROMPT" "$FALLBACK_MODEL" <<'PY' +import subprocess +import sys + +timeout_s = int(sys.argv[1]) +gemini_bin = sys.argv[2] +model = sys.argv[3] +prompt = sys.argv[4] +fallback_model = sys.argv[5] + +def run_once(selected_model: str): + cmd = [gemini_bin, "-y", "-m", selected_model, "-p", prompt, "-o", "text"] + return subprocess.run( + cmd, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=timeout_s, + ) + +try: + cp = run_once(model) +except subprocess.TimeoutExpired: + print(f"Gemini timed out after {timeout_s}s (model={model}).", file=sys.stderr) + sys.exit(124) +except Exception as exc: + print(f"Gemini launch failed: {exc}", file=sys.stderr) + sys.exit(1) + +if cp.returncode != 0 and fallback_model and fallback_model != model: + try: + cp = run_once(fallback_model) + except subprocess.TimeoutExpired: + print(f"Gemini timed out after {timeout_s}s (fallback model={fallback_model}).", file=sys.stderr) + sys.exit(124) + except Exception as exc: + print(f"Gemini fallback launch failed: {exc}", file=sys.stderr) + sys.exit(1) + +if cp.returncode != 0: + err = (cp.stderr or "").strip() + if err: + print(err, file=sys.stderr) + else: + print(f"Gemini failed with exit code {cp.returncode}.", file=sys.stderr) + sys.exit(cp.returncode) + +out = (cp.stdout or "").strip() +if not out: + sys.exit(3) + +print(out) +PY diff --git a/ide-agent-receipts.jsonl b/ide-agent-receipts.jsonl deleted file mode 100644 index 1cf5109..0000000 --- a/ide-agent-receipts.jsonl +++ /dev/null @@ -1 +0,0 @@ -{"trace_id":"94d23098-3d96-4304-a568-9267e70e5d8f","idempotency_key":"e4b32bb9-1af7-4333-8718-3f83056aa137","actor":{"name":"ide-agent-kit","kind":"ide-agent"},"action":{"kind":"tmux.run","session":"iak-test","cmd":"echo hello world","cwd":"/private/tmp/team-relay"},"input_refs":[],"output_refs":[],"status":"error","exit_code":null,"stdout_tail":"","stderr_tail":"","notes":"Command not in allowlist: echo hello world","started_at":"2026-02-21T18:34:12.908Z","finished_at":"2026-02-21T18:34:12.910Z"} diff --git a/package.json b/package.json index 2d78bd4..9ccd546 100644 --- a/package.json +++ b/package.json @@ -10,9 +10,20 @@ "test": "node --test test/*.test.mjs", "start": "node bin/cli.mjs serve" }, - "keywords": ["ide", "agent", "ai", "webhook", "tmux", "receipts", "openclaw", "gateway", "sessions", "governance"], - "license": "MIT", + "keywords": [ + "ide", + "agent", + "ai", + "webhook", + "tmux", + "receipts", + "openclaw", + "gateway", + "sessions", + "governance" + ], + "license": "AGPL-3.0-only", "engines": { "node": ">=18" } -} +} \ No newline at end of file diff --git a/schemas/event.normalized.json b/schemas/event.normalized.json index d51cd64..a8453c2 100644 --- a/schemas/event.normalized.json +++ b/schemas/event.normalized.json @@ -6,7 +6,7 @@ "properties": { "trace_id": {"type": "string", "description": "Stable trace id across the workflow"}, "event_id": {"type": "string", "description": "Idempotency key for inbound webhook/event"}, - "source": {"type": "string", "enum": ["github"], "description": "Origin system"}, + "source": {"type": "string", "enum": ["github", "antfarm"], "description": "Origin system"}, "kind": { "type": "string", "enum": [ @@ -14,7 +14,8 @@ "github.pull_request.synchronize", "github.issue_comment.created", "github.check_suite.completed", - "github.workflow_run.completed" + "github.workflow_run.completed", + "antfarm.message.created" ] }, "timestamp": {"type": "string", "format": "date-time"}, @@ -34,6 +35,7 @@ "url": {"type": "string"} } }, + "room": {"type": "string", "description": "Ant Farm room name (antfarm source only)"}, "refs": { "type": "object", "description": "Pointers the IDE agent can act on", diff --git a/scripts/room-poll-check.py b/scripts/room-poll-check.py new file mode 100644 index 0000000..8107118 --- /dev/null +++ b/scripts/room-poll-check.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 + +# SPDX-License-Identifier: AGPL-3.0-only + +"""Check for new Ant Farm room messages, optionally post focused auto-acks, append inbox file.""" + +import json +import os +import re +import subprocess +import sys +from typing import Iterable, List, Set + +BASE_URL = os.getenv("IAK_BASE_URL", "https://antfarm.world/api/v1").rstrip("/") +API_KEY = os.getenv("IAK_API_KEY") or os.getenv("ANTIGRAVITY_API_KEY", "") +ROOMS = [r.strip() for r in os.getenv( + "IAK_ROOMS", "thinkoff-development,feature-admin-planning,lattice-qcd" +).split(",") if r.strip()] +MY_HANDLES = tuple( + h.strip() for h in os.getenv("IAK_SELF_HANDLES", "@claudemm,claudemm").split(",") if h.strip() +) +OWNER_HANDLE = os.getenv("IAK_OWNER_HANDLE", "petrus").lower() +TARGET_HANDLE = os.getenv("IAK_TARGET_HANDLE", "@claudemm") +SEEN_FILE = os.getenv("IAK_SEEN_FILE", "/tmp/iak_seen_ids.txt") +ACKED_FILE = os.getenv("IAK_ACKED_FILE", "/tmp/iak_acked_ids.txt") +NEW_FILE = os.getenv("IAK_NEW_FILE", "/tmp/iak_new_messages.txt") +FETCH_LIMIT = int(os.getenv("IAK_FETCH_LIMIT", "20")) +ACK_ENABLED = os.getenv("IAK_ACK_ENABLED", "1").lower() not in ("0", "false", "no") +# Listen modes: "all" = every message, "humans" = skip bot messages, +# "tagged" = only when @mentioned, "owner" = only from owner +LISTEN_MODE = os.getenv("IAK_LISTEN_MODE", "all").lower() +BOT_HANDLES = tuple( + h.strip() for h in os.getenv( + "IAK_BOT_HANDLES", "" + ).split(",") if h.strip() +) + +TASK_HINTS = ( + "can you", "please", "need to", "check", "fix", "update", "review", + "run", "deploy", "implement", "test", "restart", "install", "respond", + "post", "pull", "push", "merge" +) + + +def _load_id_set(path: str) -> Set[str]: + try: + with open(path, "r", encoding="utf-8") as f: + return {line.strip() for line in f if line.strip()} + except FileNotFoundError: + return set() + + +def _save_id_set(path: str, values: Iterable[str], keep_last: int = 1000) -> None: + tail = list(values)[-keep_last:] + with open(path, "w", encoding="utf-8") as f: + for v in tail: + f.write(v + "\n") + + +def _extract_mentions(text: str) -> List[str]: + return [m.lower() for m in re.findall(r"@([a-zA-Z0-9_.-]+)", text or "")] + + +def _is_bot(handle: str, author_handle: str) -> bool: + """Heuristic: a sender is a bot if its handle starts with @ or is in BOT_HANDLES.""" + h = str(author_handle or handle or "").lower().lstrip("@") + if BOT_HANDLES and h in {b.lower().lstrip("@") for b in BOT_HANDLES}: + return True + # Ant Farm bot handles typically start with @ + if str(handle).startswith("@"): + return True + return False + + +def _passes_listen_filter(handle: str, author_handle: str, body: str) -> bool: + """Return True if this message should be forwarded based on LISTEN_MODE.""" + if LISTEN_MODE == "all": + return True + if LISTEN_MODE == "humans": + return not _is_bot(handle, author_handle) + if LISTEN_MODE == "tagged": + my_short = {h.lower().lstrip("@") for h in MY_HANDLES} + mentions = _extract_mentions(body) + return any(m in my_short for m in mentions) + if LISTEN_MODE == "owner": + return OWNER_HANDLE in str(author_handle).lower() or OWNER_HANDLE in str(handle).lower() + # Unknown mode, default to all + return True + + +def _message_targets_me(body: str) -> bool: + mentions = _extract_mentions(body) + my_short = {h.lower().lstrip("@") for h in MY_HANDLES} + if mentions: + return any(m in my_short for m in mentions) + # If no explicit mentions, treat owner imperatives as potentially addressed to current agent. + return True + + +def _looks_like_task_request(body: str) -> bool: + text = (body or "").strip().lower() + if not text: + return False + return any(hint in text for hint in TASK_HINTS) + + +def _should_ack(handle: str, author_handle: str, body: str) -> bool: + from_owner = OWNER_HANDLE in str(author_handle).lower() or OWNER_HANDLE in str(handle).lower() + if not from_owner: + return False + if not _message_targets_me(body): + return False + return _looks_like_task_request(body) + + +def _post_ack(room: str, text: str) -> None: + payload = json.dumps({"room": room, "body": text}) + subprocess.run( + [ + "curl", "-sS", "-X", "POST", f"{BASE_URL}/messages", + "-H", f"X-API-Key: {API_KEY}", + "-H", "Content-Type: application/json", + "-d", payload, + ], + capture_output=True, + text=True, + timeout=15, + check=False, + ) + + +def _fetch_room_messages(room: str) -> List[dict]: + result = subprocess.run( + [ + "curl", "-sS", "-H", f"X-API-Key: {API_KEY}", + f"{BASE_URL}/rooms/{room}/messages?limit={FETCH_LIMIT}", + ], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + if not result.stdout.strip(): + return [] + data = json.loads(result.stdout, strict=False) + return data.get("messages", data if isinstance(data, list) else []) + + +def main() -> int: + if not API_KEY: + print("ERROR: IAK_API_KEY or ANTIGRAVITY_API_KEY is required", file=sys.stderr) + print("NONE") + return 0 + + seen = _load_id_set(SEEN_FILE) + acked = _load_id_set(ACKED_FILE) + new_msgs: List[str] = [] + + for room in ROOMS: + msgs = _fetch_room_messages(room) + for msg in msgs: + mid = str(msg.get("id", "")).strip() + if not mid or mid in seen: + continue + seen.add(mid) + + handle = str(msg.get("from", "?")) + author_handle = str(msg.get("author", {}).get("handle", handle)) + # Always skip own messages + if author_handle in MY_HANDLES or handle in MY_HANDLES: + continue + + body = str(msg.get("body", ""))[:1000] + ts = str(msg.get("created_at", ""))[:19] + + # Apply listen mode filter + if not _passes_listen_filter(handle, author_handle, body): + continue + + new_msgs.append(f"[{ts}] [{room}] {author_handle}: {body[:400]}") + + if ACK_ENABLED and mid not in acked and _should_ack(handle, author_handle, body): + _post_ack( + room, + f"@{OWNER_HANDLE} [{TARGET_HANDLE.lstrip('@')}] starting now. " + "I will report back when finished with results." + ) + acked.add(mid) + + _save_id_set(SEEN_FILE, seen, keep_last=1000) + _save_id_set(ACKED_FILE, acked, keep_last=1000) + + if new_msgs: + with open(NEW_FILE, "a", encoding="utf-8") as f: + for nm in reversed(new_msgs): + f.write(nm + "\n---\n") + print("NEW") + else: + print("NONE") + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception as e: + print(f"ERROR: {e}", file=sys.stderr) + print("NONE") + raise SystemExit(0) diff --git a/scripts/room-poll.sh b/scripts/room-poll.sh new file mode 100755 index 0000000..5701bf9 --- /dev/null +++ b/scripts/room-poll.sh @@ -0,0 +1,58 @@ +#!/bin/bash + +# SPDX-License-Identifier: AGPL-3.0-only + +# Room poller wrapper - checks rooms and nudges tmux on new work. +# Uses a PID lock file to prevent duplicate instances. +set -u + +TMUX_SESSION="${IAK_TMUX_SESSION:-claude}" +POLL_INTERVAL="${IAK_POLL_INTERVAL:-10}" +NUDGE_TEXT="${IAK_NUDGE_TEXT:-check rooms}" +SCRIPT_DIR="$(dirname "$0")" +CHECK_SCRIPT="${IAK_CHECK_SCRIPT:-$SCRIPT_DIR/room-poll-check.py}" +ERR_LOG="${IAK_ERR_LOG:-/tmp/iak_poll_err.log}" +LOCK_FILE="${IAK_LOCK_FILE:-/tmp/iak_poll.pid}" + +# --- PID lock: prevent duplicate pollers --- +if [ -f "$LOCK_FILE" ]; then + OLD_PID=$(cat "$LOCK_FILE" 2>/dev/null) + if [ -n "$OLD_PID" ] && kill -0 "$OLD_PID" 2>/dev/null; then + echo "[$(date -u +%FT%TZ)] Another poller already running (PID $OLD_PID). Exiting." + exit 0 + fi + rm -f "$LOCK_FILE" +fi +echo $$ > "$LOCK_FILE" + +cleanup() { + rm -f "$LOCK_FILE" + exit 0 +} +trap cleanup EXIT INT TERM + +echo "[$(date -u +%FT%TZ)] Poller started (PID $$, interval ${POLL_INTERVAL}s)" +echo "[$(date -u +%FT%TZ)] check_script=${CHECK_SCRIPT} session=${TMUX_SESSION}" + +if [ ! -f "$CHECK_SCRIPT" ]; then + echo "[$(date -u +%FT%TZ)] ERROR: check script not found: $CHECK_SCRIPT" + exit 1 +fi + +while true; do + HAS_NEW=$(python3 "$CHECK_SCRIPT" 2>"$ERR_LOG") + echo "[$(date -u +%FT%TZ)] Poll result: $HAS_NEW" + + if [ "$HAS_NEW" = "NEW" ]; then + if tmux has-session -t "$TMUX_SESSION" 2>/dev/null; then + tmux send-keys -t "$TMUX_SESSION" -l "$NUDGE_TEXT" + sleep 0.3 + tmux send-keys -t "$TMUX_SESSION" Enter + echo "[$(date -u +%FT%TZ)] Sent short nudge" + else + echo "[$(date -u +%FT%TZ)] tmux session not found: $TMUX_SESSION" + fi + fi + + sleep "$POLL_INTERVAL" +done diff --git a/src/config.mjs b/src/config.mjs index 9c90fa5..bb25265 100644 --- a/src/config.mjs +++ b/src/config.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { readFileSync, existsSync } from 'node:fs'; import { resolve } from 'node:path'; @@ -6,6 +8,15 @@ const DEFAULT_CONFIG = { queue: { path: './ide-agent-queue.jsonl' }, receipts: { path: './ide-agent-receipts.jsonl', stdout_tail_lines: 80 }, tmux: { default_session: 'iak-runner', ide_session: 'claude', nudge_text: 'check rooms', allow: [] }, + poller: { + rooms: '', + handle: '', + interval_sec: 30, + seen_file: '/tmp/iak-seen-ids.txt', + api_key: '', + nudge_mode: 'tmux', + nudge_command: '' + }, github: { webhook_secret: '', event_kinds: ['pull_request', 'issue_comment', 'check_suite', 'workflow_run'] }, outbound: { default_webhook_url: '' } }; @@ -19,6 +30,7 @@ export function loadConfig(configPath) { queue: { ...DEFAULT_CONFIG.queue, ...raw.queue }, receipts: { ...DEFAULT_CONFIG.receipts, ...raw.receipts }, tmux: { ...DEFAULT_CONFIG.tmux, ...raw.tmux }, + poller: { ...DEFAULT_CONFIG.poller, ...raw.poller }, github: { ...DEFAULT_CONFIG.github, ...raw.github }, outbound: { ...DEFAULT_CONFIG.outbound, ...raw.outbound } }; diff --git a/src/emit.mjs b/src/emit.mjs index 5b872d4..47d20b8 100644 --- a/src/emit.mjs +++ b/src/emit.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { readFileSync } from 'node:fs'; import { request } from 'node:https'; import { request as httpRequest } from 'node:http'; diff --git a/src/memory.mjs b/src/memory.mjs index d56a96f..bb36b0f 100644 --- a/src/memory.mjs +++ b/src/memory.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { execSync } from 'node:child_process'; diff --git a/src/openclaw-cron.mjs b/src/openclaw-cron.mjs index 540a28b..38198a8 100644 --- a/src/openclaw-cron.mjs +++ b/src/openclaw-cron.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { execSync } from 'node:child_process'; /** diff --git a/src/openclaw-exec.mjs b/src/openclaw-exec.mjs index 8ab9782..7682f5d 100644 --- a/src/openclaw-exec.mjs +++ b/src/openclaw-exec.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { randomUUID } from 'node:crypto'; diff --git a/src/openclaw-gateway.mjs b/src/openclaw-gateway.mjs index 1ee84dd..6dd3265 100644 --- a/src/openclaw-gateway.mjs +++ b/src/openclaw-gateway.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { execSync } from 'node:child_process'; /** diff --git a/src/openclaw-hooks.mjs b/src/openclaw-hooks.mjs index db74a64..8402493 100644 --- a/src/openclaw-hooks.mjs +++ b/src/openclaw-hooks.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, rmSync } from 'node:fs'; import { join } from 'node:path'; diff --git a/src/openclaw-sessions.mjs b/src/openclaw-sessions.mjs index 5c4bf83..9c528a0 100644 --- a/src/openclaw-sessions.mjs +++ b/src/openclaw-sessions.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { execSync } from 'node:child_process'; /** diff --git a/src/receipt.mjs b/src/receipt.mjs index 7586e4a..fbe5be4 100644 --- a/src/receipt.mjs +++ b/src/receipt.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { appendFileSync, readFileSync, existsSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; diff --git a/src/room-poller.mjs b/src/room-poller.mjs index 62b9564..b81f238 100644 --- a/src/room-poller.mjs +++ b/src/room-poller.mjs @@ -1,6 +1,9 @@ -import { execSync } from 'node:child_process'; -import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs'; +// SPDX-License-Identifier: AGPL-3.0-only + +import { readFileSync, writeFileSync, appendFileSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; +import { execSync } from 'node:child_process'; +import { nudgeTmux, nudgeCommand } from './utils.mjs'; /** * Room Poller — polls Ant Farm room API directly and nudges IDE tmux session. @@ -28,27 +31,11 @@ function saveSeenIds(path, ids) { writeFileSync(path, arr.join('\n') + '\n'); } -function nudgeTmux(session, text) { - try { - execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); - } catch { - return false; - } - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); - execSync('sleep 0.3'); - execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); - return true; - } catch { - return false; - } -} - async function fetchRoomMessages(room, apiKey, limit = 10) { const url = `https://antfarm.world/api/v1/rooms/${room}/messages?limit=${limit}`; try { const result = execSync( - `curl -sS -H "X-API-Key: ${apiKey}" "${url}"`, + `curl -sS -H "Authorization: Bearer ${apiKey}" "${url}"`, { encoding: 'utf8', timeout: 15000 } ); const data = JSON.parse(result); @@ -64,22 +51,30 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config const queuePath = config?.queue?.path || './ide-agent-queue.jsonl'; const session = config?.tmux?.ide_session || config?.tmux?.default_session || 'claude'; const nudgeText = config?.tmux?.nudge_text || 'check rooms'; + const nudgeMode = config?.poller?.nudge_mode || 'tmux'; + const nudgeCommandText = config?.poller?.nudge_command || ''; const pollInterval = interval || config?.poller?.interval_sec || 30; const selfHandle = handle || config?.poller?.handle || '@unknown'; - console.log(`Room poller started`); + console.log('Room poller started'); console.log(` rooms: ${rooms.join(', ')}`); console.log(` handle: ${selfHandle} (messages from self are ignored)`); console.log(` interval: ${pollInterval}s`); - console.log(` tmux session: ${session}`); + console.log(` nudge mode: ${nudgeMode}`); + if (nudgeMode === 'tmux') { + console.log(` tmux session: ${session}`); + } else if (nudgeMode === 'command') { + console.log(` nudge command: ${nudgeCommandText || '(missing)'}`); + } console.log(` seen file: ${seenFile}`); console.log(` queue: ${queuePath}`); + console.log(' auto-ack: disabled (real replies only)'); const seen = loadSeenIds(seenFile); // Seed: mark current messages as seen on first run if (seen.size === 0) { - console.log(` seeding seen IDs from current messages...`); + console.log(' seeding seen IDs from current messages...'); for (const room of rooms) { const msgs = await fetchRoomMessages(room, apiKey, 50); for (const m of msgs) { @@ -127,8 +122,15 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config saveSeenIds(seenFile, seen); if (newCount > 0) { - const nudged = nudgeTmux(session, nudgeText); - console.log(` ${newCount} new message(s) → ${nudged ? 'nudged' : 'no tmux session'}`); + let nudged = false; + if (nudgeMode === 'command') { + nudged = nudgeCommand(nudgeCommandText, { text: nudgeText, session }); + } else if (nudgeMode === 'none') { + nudged = true; + } else { + nudged = nudgeTmux(session, nudgeText); + } + console.log(` ${newCount} new message(s) → ${nudged ? 'nudged' : 'nudge failed'}`); } } @@ -139,21 +141,26 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config const timer = setInterval(poll, pollInterval * 1000); // Anti-sleep heartbeat (keeps terminal pseudo-active to prevent display-sleep freeze) - const heartbeat = setInterval(() => { - try { - execSync(`tmux send-keys -t ${JSON.stringify(session)} Escape`); - } catch { } - }, 4 * 60 * 1000); + const heartbeat = nudgeMode === 'tmux' + ? setInterval(() => { + try { + execSync(`tmux send-keys -t ${JSON.stringify(session)} Escape`); + } catch { + // no-op + } + }, 4 * 60 * 1000) + : null; // Handle shutdown process.on('SIGINT', () => { console.log('\nPoller stopped.'); clearInterval(timer); - clearInterval(heartbeat); + if (heartbeat) clearInterval(heartbeat); process.exit(0); }); process.on('SIGTERM', () => { clearInterval(timer); + if (heartbeat) clearInterval(heartbeat); process.exit(0); }); diff --git a/src/session-keepalive.mjs b/src/session-keepalive.mjs index 89da81b..fa131db 100644 --- a/src/session-keepalive.mjs +++ b/src/session-keepalive.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { execSync, spawn } from 'node:child_process'; import { readFileSync, writeFileSync, existsSync } from 'node:fs'; import { join } from 'node:path'; diff --git a/src/tmux-runner.mjs b/src/tmux-runner.mjs index 4de018a..f90c909 100644 --- a/src/tmux-runner.mjs +++ b/src/tmux-runner.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { execSync, spawn } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { createReceipt, appendReceipt } from './receipt.mjs'; diff --git a/src/utils.mjs b/src/utils.mjs new file mode 100644 index 0000000..6502288 --- /dev/null +++ b/src/utils.mjs @@ -0,0 +1,48 @@ +import { execSync } from 'node:child_process'; + +/** + * Nudge a tmux session by sending a specific text and Enter key. + * Used to wake up sleeping IDE agents. + */ +export function nudgeTmux(session, text = 'check rooms') { + try { + // Check if session exists + execSync(`tmux has-session -t ${JSON.stringify(session)} 2>/dev/null`); + + // Send the nudge text + execSync(`tmux send-keys -t ${JSON.stringify(session)} -l ${JSON.stringify(text)}`); + + // Small delay before sending Enter to ensure the text is processed + setTimeout(() => { + try { + execSync(`tmux send-keys -t ${JSON.stringify(session)} Enter`); + } catch {} + }, 300); + + return true; + } catch (e) { + // Session not found or other tmux error + return false; + } +} + +/** + * Run an arbitrary command as a nudge bridge (for non-tmux IDEs, e.g. GUI apps). + * Command runs with IAK_NUDGE_TEXT and IAK_TMUX_SESSION in env. + */ +export function nudgeCommand(command, { text = 'check rooms', session = '' } = {}) { + if (!command || typeof command !== 'string') return false; + try { + execSync(command, { + stdio: 'ignore', + env: { + ...process.env, + IAK_NUDGE_TEXT: text, + IAK_TMUX_SESSION: session + } + }); + return true; + } catch { + return false; + } +} diff --git a/src/watch.mjs b/src/watch.mjs index a2788d5..cc899e4 100644 --- a/src/watch.mjs +++ b/src/watch.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { watch, readFileSync, statSync } from 'node:fs'; import { execSync } from 'node:child_process'; @@ -32,15 +34,13 @@ export function watchQueue(config, onNewEvent) { return; } - // Read only the new bytes - const fd = readFileSync(queuePath, 'utf8'); - const allLines = fd.trim().split('\n'); - - // Figure out new lines by counting from old size - const oldContent = fd.slice(0, lastSize); - const oldLineCount = oldContent ? oldContent.trim().split('\n').length : 0; - const newLines = allLines.slice(oldLineCount); + // Read new content using byte offset for correct UTF-8 handling + const buf = readFileSync(queuePath); + const newBuf = buf.slice(lastSize); lastSize = currentSize; + const newContent = newBuf.toString('utf8').trim(); + if (!newContent) return; + const newLines = newContent.split('\n'); if (newLines.length === 0) return; diff --git a/src/webhook-server.mjs b/src/webhook-server.mjs index fbdd00f..0479e17 100644 --- a/src/webhook-server.mjs +++ b/src/webhook-server.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { createServer } from 'node:http'; import { createHmac, timingSafeEqual } from 'node:crypto'; import { appendFileSync } from 'node:fs'; diff --git a/test/receipt.test.mjs b/test/receipt.test.mjs index bbb7593..76aff9f 100644 --- a/test/receipt.test.mjs +++ b/test/receipt.test.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { describe, it } from 'node:test'; import { strict as assert } from 'node:assert'; import { createReceipt, appendReceipt, tailReceipts } from '../src/receipt.mjs'; diff --git a/test/webhook.test.mjs b/test/webhook.test.mjs index 57eb993..4e9998a 100644 --- a/test/webhook.test.mjs +++ b/test/webhook.test.mjs @@ -1,3 +1,5 @@ +// SPDX-License-Identifier: AGPL-3.0-only + import { describe, it, after } from 'node:test'; import { strict as assert } from 'node:assert'; import { createHmac } from 'node:crypto'; diff --git a/tools/antigravity_room_autopost.sh b/tools/antigravity_room_autopost.sh new file mode 100755 index 0000000..127be83 --- /dev/null +++ b/tools/antigravity_room_autopost.sh @@ -0,0 +1,468 @@ +#!/usr/bin/env bash +# antigravity_room_autopost.sh +# Automatic room responder for @antigravity. +# Responds to new room messages (mention-only by default). +# +# Usage: +# ./tools/antigravity_room_autopost.sh +# ./tools/antigravity_room_autopost.sh tmux +# ./tools/antigravity_room_autopost.sh tmux stop +# ./tools/antigravity_room_autopost.sh tmux status +# ./tools/antigravity_room_autopost.sh tmux logs + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +ENV_FILE="$ROOT_DIR/.env.local" + +if [[ ! -f "$ENV_FILE" ]]; then + echo "Missing env file: $ENV_FILE" + exit 1 +fi + +API_KEY="$(grep "^ANTIGRAVITY_API_KEY=" "$ENV_FILE" | head -n1 | cut -d= -f2-)" +if [[ -z "${API_KEY:-}" ]]; then + echo "ANTIGRAVITY_API_KEY is missing in $ENV_FILE" + exit 1 +fi + +BASE_URL="https://antfarm.world/api/v1" +ROOMS_CSV="${ROOMS:-feature-admin-planning}" +POLL_INTERVAL="${POLL_INTERVAL:-8}" +FETCH_LIMIT="${FETCH_LIMIT:-30}" +SESSION="${SESSION:-antigravity-room-autopost}" +AGENT_HANDLE="@antigravity" +MENTION_ONLY="${MENTION_ONLY:-0}" # 0 = inspect every room message; reply logic still applies +RESPOND_TO_HANDLE="${RESPOND_TO_HANDLE:-petrus}" +SOURCE_TAG="${SOURCE_TAG:-[ag-codex][tmux-ok]}" +SEEN_MAX="${SEEN_MAX:-500}" +PRIME_ON_START="${PRIME_ON_START:-0}" # 1 = seed current room messages as seen on cold start +SMART_MODE="${SMART_MODE:-1}" # 1 = use codex exec for real responses when possible +CODEX_WORKDIR="${CODEX_WORKDIR:-/Users/petrus/AndroidStudioProjects/ThinkOff}" +SMART_TIMEOUT_SEC="${SMART_TIMEOUT_SEC:-75}" +CODEX_APPROVAL_POLICY="${CODEX_APPROVAL_POLICY:-never}" +CODEX_SANDBOX_MODE="${CODEX_SANDBOX_MODE:-workspace-write}" +MAX_REPLY_AGE_SEC="${MAX_REPLY_AGE_SEC:-900}" # skip replying to stale backlog messages +SKIP_PRESTART_BACKLOG="${SKIP_PRESTART_BACKLOG:-1}" # 1 = do not reply to messages older than process start +START_EPOCH="$(date +%s)" + +SEEN_IDS_FILE="/tmp/antigravity_room_autopost_seen_ids.txt" +ACKED_IDS_FILE="/tmp/antigravity_room_autopost_acked_ids.txt" +LOCK_FILE="/tmp/antigravity_room_autopost.pid" + +has_id() { + local file="$1" + local key="$2" + [[ -f "$file" ]] && grep -qF "$key" "$file" +} + +record_id() { + local file="$1" + local key="$2" + echo "$key" >> "$file" + tail -n "$SEEN_MAX" "$file" > "${file}.tmp" && mv "${file}.tmp" "$file" +} + +prime_seen_ids() { + local room="$1" + local response + response="$(curl -sS -H "X-API-Key: $API_KEY" "$BASE_URL/rooms/$room/messages?limit=50" 2>/dev/null || true)" + [[ -z "$response" ]] && return 0 + echo "$response" | python3 -c ' +import json, sys +try: + data = json.load(sys.stdin, strict=False) +except Exception: + sys.exit(0) +for m in data.get("messages", []): + mid = m.get("id", "") + if mid: + print(mid) +' | sed -e "s#^#${room}::#" >> "$SEEN_IDS_FILE" + awk "!seen[\$0]++" "$SEEN_IDS_FILE" > "${SEEN_IDS_FILE}.tmp" && mv "${SEEN_IDS_FILE}.tmp" "$SEEN_IDS_FILE" + tail -n "$SEEN_MAX" "$SEEN_IDS_FILE" > "${SEEN_IDS_FILE}.tmp" && mv "${SEEN_IDS_FILE}.tmp" "$SEEN_IDS_FILE" +} + +build_reply() { + local from_handle="$1" + local created_at="$2" + local body="$3" + local lc + lc="$(printf "%s" "$body" | tr '[:upper:]' '[:lower:]')" + local lag_sec + lag_sec="$(seconds_since_iso "$created_at")" + + if [[ "$lc" == *"do you hear me"* ]]; then + if [[ "$lag_sec" =~ ^[0-9]+$ ]] && [[ "$lag_sec" -ge 0 ]]; then + echo "@${from_handle#@} ${SOURCE_TAG} yes, hearing you. ${lag_sec}s from your message. path=tmux poller." + else + echo "@${from_handle#@} ${SOURCE_TAG} yes, hearing you. path=tmux poller." + fi + return 0 + fi + if [[ "$lc" == *"webhook and/or tmux"* ]]; then + echo "@${from_handle#@} ${SOURCE_TAG} path=tmux poller on this runtime." + return 0 + fi + + # For direct owner task requests, only send canned ack when SMART_MODE is off. + # In SMART_MODE, let build_smart_reply generate the actual response. + if should_force_reply "$from_handle" "$body"; then + if [[ "$SMART_MODE" != "1" ]] && [[ "$lc" != *"do you hear me"* && "$lc" != *"post time in seconds"* && "$lc" != *"report time in seconds"* && "$lc" != *"webhook and/or tmux"* && "$lc" != *"2/6"* ]]; then + echo "@${from_handle#@} ${SOURCE_TAG} starting now (poller ack)." + return 0 + fi + fi + + # For normal conversation, avoid placeholder acknowledgements. + # A human/manual response will be posted by codex when action is taken. + echo "" +} + +is_low_value_bot_ack() { + local from_handle="$1" + local body="$2" + local lc + lc="$(printf "%s" "$body" | tr '[:upper:]' '[:lower:]')" + # Ignore common canned poller chatter to avoid ack loops. + if [[ "$lc" == *"[tmux-ok]"* ]]; then + return 0 + fi + if [[ "$lc" == *"starting now"* && "$lc" == *"report back with results"* ]]; then + return 0 + fi + if [[ "$lc" == *"starting now (poller ack)"* ]]; then + return 0 + fi + # Ignore very short bot pings unless explicitly aimed at us. + if [[ "$from_handle" == @* ]] && [[ ${#lc} -lt 48 ]] && [[ "$lc" != *"@antigravity"* ]] && [[ "$lc" != *"codex"* ]]; then + return 0 + fi + return 1 +} + +build_smart_reply() { + local room="$1" + local from_handle="$2" + local body="$3" + + if [[ "$SMART_MODE" != "1" ]]; then + echo "" + return 0 + fi + if ! command -v codex >/dev/null 2>&1; then + echo "" + return 0 + fi + if is_low_value_bot_ack "$from_handle" "$body"; then + echo "" + return 0 + fi + + local out_file="/tmp/antigravity_codex_reply_last.txt" + local prompt_file="/tmp/antigravity_codex_reply_prompt.txt" + cat > "$prompt_file" </tmp/antigravity_codex_exec.log 2>&1 +import subprocess, sys +prompt_file, out_file, workdir, timeout_s, approval_policy, sandbox_mode = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]), sys.argv[5], sys.argv[6] +prompt = open(prompt_file, "r", encoding="utf-8").read() +subprocess.run( + ["codex", "exec", "--ephemeral", "-C", workdir, "-a", approval_policy, "-s", sandbox_mode, "--output-last-message", out_file, prompt], + check=True, + timeout=timeout_s, +) +PY + then + echo "" + return 0 + fi + + local reply + reply="$(tr '\n' ' ' < "$out_file" | sed 's/[[:space:]]\+/ /g; s/^ //; s/ $//')" + if [[ -z "$reply" ]]; then + echo "" + return 0 + fi + if [[ "$reply" == "NO_REPLY" ]]; then + echo "" + return 0 + fi + echo "@${from_handle#@} [ag-codex] ${reply:0:900}" +} + +build_force_fallback_reply() { + local from_handle="$1" + local body="$2" + local lc + lc="$(printf "%s" "$body" | tr '[:upper:]' '[:lower:]')" + if ! should_force_reply "$from_handle" "$body"; then + echo "" + return 0 + fi + if [[ "$lc" == *"stay up"* || "$lc" == *"off screen"* || "$lc" == *"keep polling"* || "$lc" == *"not responding"* ]]; then + echo "@${from_handle#@} [ag-codex] applied. I am live in tmux poll mode and will keep polling every ${POLL_INTERVAL}s. I will post concrete action updates, not only ack." + return 0 + fi + echo "@${from_handle#@} [ag-codex] on it. Running this now and posting a concrete update shortly." +} + +seconds_since_iso() { + local ts="$1" + python3 - "$ts" <<'PY' +import datetime, sys +ts = sys.argv[1] +try: + dt = datetime.datetime.fromisoformat(ts.replace("Z", "+00:00")) + now = datetime.datetime.now(datetime.timezone.utc) + print(max(0, int((now - dt).total_seconds()))) +except Exception: + print(-1) +PY +} + +epoch_from_iso() { + local ts="$1" + python3 - "$ts" <<'PY' +import datetime, sys +ts = sys.argv[1] +try: + dt = datetime.datetime.fromisoformat(ts.replace("Z", "+00:00")) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=datetime.timezone.utc) + print(int(dt.timestamp())) +except Exception: + print(-1) +PY +} + +should_force_reply() { + local from_handle="$1" + local body="$2" + local lc + lc="$(printf "%s" "$body" | tr '[:upper:]' '[:lower:]')" + if [[ "$from_handle" != "$RESPOND_TO_HANDLE" && "$from_handle" != "@$RESPOND_TO_HANDLE" ]]; then + return 1 + fi + if [[ "$lc" == *"do you hear me"* || "$lc" == *"report time in seconds"* || "$lc" == *"post time in seconds"* || "$lc" == *"webhook and/or tmux"* || "$lc" == *"2/6"* ]]; then + return 0 + fi + # If clearly addressed to another agent only, do not force. + if [[ "$lc" == *"@claudemm"* || "$lc" == *"@geminimb"* || "$lc" == *" claudemm"* || "$lc" == *" geminimb"* ]]; then + if [[ "$lc" != *"@antigravity"* && "$lc" != *"codex"* && "$lc" != *"all of you"* ]]; then + return 1 + fi + fi + # Direct task requests aimed at antigravity/codex or the whole room. + if [[ "$lc" == *"@antigravity"* || "$lc" == *"codex"* || "$lc" == *"all of you"* ]]; then + if [[ "$lc" == *"can you"* || "$lc" == *"please"* || "$lc" == *"need to"* || "$lc" == *"check"* || "$lc" == *"fix"* || "$lc" == *"review"* || "$lc" == *"update"* || "$lc" == *"respond"* || "$lc" == *"deploy"* || "$lc" == *"test"* || "$lc" == *"repo files good"* || "$lc" == *"are the repo files good"* ]]; then + return 0 + fi + fi + # Owner question-style follow-ups should also get a short start-ack. + if [[ "$lc" == *"?"* ]]; then + return 0 + fi + # Owner imperatives commonly used in this room. + if [[ "$lc" == *"can you"* || "$lc" == *"please"* || "$lc" == *"need to"* || "$lc" == *"check room"* || "$lc" == *"check messages"* || "$lc" == *"review repo"* || "$lc" == *"update room"* || "$lc" == *"post update"* || "$lc" == *"repo files good"* || "$lc" == *"are the repo files good"* ]]; then + return 0 + fi + return 1 +} + +post_reply() { + local room="$1" + local from_handle="$2" + local created_at="$3" + local src_key="$4" + local src_body="$5" + + if has_id "$ACKED_IDS_FILE" "$src_key"; then + return 0 + fi + + local reply_body + reply_body="$(build_reply "$from_handle" "$created_at" "$src_body")" + if [[ -z "$reply_body" ]]; then + reply_body="$(build_smart_reply "$room" "$from_handle" "$src_body")" + fi + if [[ -z "$reply_body" ]]; then + reply_body="$(build_force_fallback_reply "$from_handle" "$src_body")" + fi + if [[ -z "$reply_body" ]]; then + return 0 + fi + + local payload + payload="$(python3 - <<'PY' "$room" "$reply_body" +import json, sys +room = sys.argv[1] +body = sys.argv[2] +print(json.dumps({"room": room, "body": body})) +PY +)" + + local res + if ! res="$(curl -sS -X POST \ + -H "X-API-Key: $API_KEY" \ + -H "Content-Type: application/json" \ + -d "$payload" \ + "$BASE_URL/messages" 2>&1)"; then + echo "[$(date +%H:%M:%S)] reply failed: $res" + return 1 + fi + + local posted_id + posted_id="$(echo "$res" | python3 -c 'import json,sys; print(json.load(sys.stdin, strict=False).get("id",""))' 2>/dev/null || true)" + if [[ -n "$posted_id" ]]; then + record_id "$ACKED_IDS_FILE" "$src_key" + echo "[$(date +%H:%M:%S)] REPLIED room=$room -> $from_handle (src=$src_key msg=$posted_id)" + else + echo "[$(date +%H:%M:%S)] reply parse warning: $res" + fi +} + +# tmux lifecycle +if [[ "${1:-}" == "tmux" ]]; then + cmd="${2:-start}" + case "$cmd" in + stop) + if tmux has-session -t "$SESSION" 2>/dev/null; then + tmux kill-session -t "$SESSION" + echo "Stopped $SESSION" + else + echo "$SESSION is not running" + fi + ;; + status) + if tmux has-session -t "$SESSION" 2>/dev/null; then + echo "$SESSION is running ($(tmux list-panes -t "$SESSION" -F '#{pane_pid}'))" + else + echo "$SESSION is not running" + fi + ;; + logs) + if tmux has-session -t "$SESSION" 2>/dev/null; then + tmux attach-session -t "$SESSION" + else + echo "$SESSION is not running" + exit 1 + fi + ;; + start|"") + if tmux has-session -t "$SESSION" 2>/dev/null; then + echo "$SESSION already running" + exit 0 + fi + tmux new-session -d -s "$SESSION" "$0" + echo "Started $SESSION (rooms=$ROOMS_CSV interval=${POLL_INTERVAL}s mention_only=$MENTION_ONLY)" + ;; + *) + echo "Usage: $0 tmux {start|stop|status|logs}" + exit 1 + ;; + esac + exit 0 +fi + +# --- PID lock: prevent duplicate pollers --- +if [[ -f "$LOCK_FILE" ]]; then + OLD_PID="$(cat "$LOCK_FILE" 2>/dev/null || true)" + if [[ -n "$OLD_PID" ]] && kill -0 "$OLD_PID" 2>/dev/null; then + echo "Another antigravity poller already running (PID $OLD_PID). Exiting." + exit 0 + fi + rm -f "$LOCK_FILE" +fi +echo $$ > "$LOCK_FILE" +trap 'rm -f "$LOCK_FILE"; exit 0' EXIT INT TERM + +touch "$SEEN_IDS_FILE" "$ACKED_IDS_FILE" +IFS=',' read -r -a ROOMS_ARRAY <<< "$ROOMS_CSV" +if [[ "$PRIME_ON_START" == "1" ]] && [[ ! -s "$SEEN_IDS_FILE" ]]; then + for raw_room in "${ROOMS_ARRAY[@]}"; do + room="$(echo "$raw_room" | xargs)" + [[ -z "$room" ]] && continue + prime_seen_ids "$room" + done + echo "[antigravity-autopost] primed seen ids on cold start" +fi + +echo "[antigravity-autopost] rooms=$ROOMS_CSV poll=${POLL_INTERVAL}s limit=${FETCH_LIMIT} mention_only=$MENTION_ONLY" +echo "[antigravity-autopost] seen=$SEEN_IDS_FILE acked=$ACKED_IDS_FILE" + +while true; do + for raw_room in "${ROOMS_ARRAY[@]}"; do + room="$(echo "$raw_room" | xargs)" + [[ -z "$room" ]] && continue + + response="$(curl -sS -H "X-API-Key: $API_KEY" "$BASE_URL/rooms/$room/messages?limit=$FETCH_LIMIT" 2>/dev/null || true)" + if [[ -z "$response" ]]; then + echo "[$(date +%H:%M:%S)] fetch empty room=$room" + continue + fi + + while IFS=$'\t' read -r msg_id from_handle created_at mentioned body_preview; do + [[ -z "$msg_id" ]] && continue + msg_key="${room}::${msg_id}" + if has_id "$SEEN_IDS_FILE" "$msg_key"; then + continue + fi + record_id "$SEEN_IDS_FILE" "$msg_key" + + echo "[$(date +%H:%M:%S)] NEW room=$room $from_handle $msg_id at=$created_at ${body_preview:0:140}" + + if [[ "$from_handle" == "$AGENT_HANDLE" ]]; then + continue + fi + if [[ "$SKIP_PRESTART_BACKLOG" == "1" ]]; then + msg_epoch="$(epoch_from_iso "$created_at")" + if [[ "$msg_epoch" =~ ^[0-9]+$ ]] && [[ "$msg_epoch" -gt 0 ]] && [[ "$msg_epoch" -lt "$START_EPOCH" ]]; then + echo "[$(date +%H:%M:%S)] SKIP prestart room=$room msg=$msg_id" + continue + fi + fi + msg_age_sec="$(seconds_since_iso "$created_at")" + if [[ "$msg_age_sec" =~ ^[0-9]+$ ]] && [[ "$msg_age_sec" -gt "$MAX_REPLY_AGE_SEC" ]]; then + echo "[$(date +%H:%M:%S)] SKIP stale room=$room msg=$msg_id age=${msg_age_sec}s" + continue + fi + if [[ "$MENTION_ONLY" == "1" && "$mentioned" != "1" ]] && ! should_force_reply "$from_handle" "$body_preview"; then + continue + fi + + post_reply "$room" "$from_handle" "$created_at" "$msg_key" "$body_preview" || true + done < <(echo "$response" | python3 -c ' +import json, re, sys +try: + data = json.load(sys.stdin, strict=False) +except Exception: + sys.exit(0) +for m in data.get("messages", []): + mid = m.get("id", "") + frm = m.get("from", "") + created = m.get("created_at", "") + body = (m.get("body", "") or "").replace("\n", " ").replace("\t", " ") + mentioned = "1" if re.search(r"@antigravity\b", body, re.IGNORECASE) else "0" + print(f"{mid}\t{frm}\t{created}\t{mentioned}\t{body}") +') + done + + sleep "$POLL_INTERVAL" +done diff --git a/tools/codex_gui_nudge.sh b/tools/codex_gui_nudge.sh new file mode 100755 index 0000000..13b89ae --- /dev/null +++ b/tools/codex_gui_nudge.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +APP_NAME="${IAK_CODEX_APP_NAME:-Codex}" +PROMPT_TEXT="${IAK_NUDGE_TEXT:-check room and respond [codex]}" + +if ! command -v osascript >/dev/null 2>&1; then + echo "osascript not found" >&2 + exit 1 +fi + +osascript - "$APP_NAME" "$PROMPT_TEXT" <<'APPLESCRIPT' +on run argv + set appName to item 1 of argv + set promptText to item 2 of argv + tell application appName to activate + delay 0.2 + tell application "System Events" + keystroke promptText + key code 36 + end tell +end run +APPLESCRIPT diff --git a/tools/geminimb_room_autopost.sh b/tools/geminimb_room_autopost.sh new file mode 100755 index 0000000..ebc2881 --- /dev/null +++ b/tools/geminimb_room_autopost.sh @@ -0,0 +1,333 @@ +#!/usr/bin/env bash +# geminimb_room_autopost.sh +# Automatic room responder for @geminiMB. +# Responds to new room messages (mention-only by default). +# +# Usage: +# ./tools/geminimb_room_autopost.sh +# ./tools/geminimb_room_autopost.sh tmux +# ./tools/geminimb_room_autopost.sh tmux stop +# ./tools/geminimb_room_autopost.sh tmux status +# ./tools/geminimb_room_autopost.sh tmux logs + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" + +# NEVER hardcode API keys - use env vars only +API_KEY="${IAK_API_KEY:-${GEMINIMB_API_KEY:-}}" +if [[ -z "$API_KEY" ]]; then + echo "ERROR: Set IAK_API_KEY or GEMINIMB_API_KEY env var" >&2 + exit 1 +fi + +BASE_URL="https://antfarm.world/api/v1" +ROOMS_CSV="${ROOMS:-feature-admin-planning,thinkoff-development}" +POLL_INTERVAL="${POLL_INTERVAL:-8}" +FETCH_LIMIT="${FETCH_LIMIT:-30}" +PRIME_ON_START="${PRIME_ON_START:-0}" +SESSION="${SESSION:-geminimb-room-autopost}" +AGENT_HANDLE="@geminiMB" +MENTION_ONLY="${MENTION_ONLY:-0}" # 0 = process all messages in the room +RESPOND_TO_HANDLE="${RESPOND_TO_HANDLE:-petrus}" +SOURCE_TAG="${SOURCE_TAG:-[geminimb][tmux-ok]}" +SEEN_MAX="${SEEN_MAX:-500}" + +SEEN_IDS_FILE="/tmp/geminimb_room_autopost_seen_ids.txt" +ACKED_IDS_FILE="/tmp/geminimb_room_autopost_acked_ids.txt" +LOCK_FILE="/tmp/geminimb_room_autopost.pid" + +has_id() { + local file="$1" + local key="$2" + [[ -f "$file" ]] && grep -qF "$key" "$file" +} + +record_id() { + local file="$1" + local key="$2" + echo "$key" >> "$file" + tail -n "$SEEN_MAX" "$file" > "${file}.tmp" && mv "${file}.tmp" "$file" +} + +prime_seen_ids() { + local room="$1" + local response + response="$(curl -sS -H "X-API-Key: $API_KEY" "$BASE_URL/rooms/$room/messages?limit=50" 2>/dev/null || true)" + [[ -z "$response" ]] && return 0 + echo "$response" | python3 -c ' +import json, sys +try: + data = json.load(sys.stdin, strict=False) +except Exception: + sys.exit(0) +for m in data.get("messages", []): + mid = m.get("id", "") + if mid: + print(mid) +' | sed -e "s#^#${room}::#" >> "$SEEN_IDS_FILE" + awk "!seen[\$0]++" "$SEEN_IDS_FILE" > "${SEEN_IDS_FILE}.tmp" && mv "${SEEN_IDS_FILE}.tmp" "$SEEN_IDS_FILE" + tail -n "$SEEN_MAX" "$SEEN_IDS_FILE" > "${SEEN_IDS_FILE}.tmp" && mv "${SEEN_IDS_FILE}.tmp" "$SEEN_IDS_FILE" +} + +build_reply() { + local from_handle="$1" + local created_at="$2" + local body="$3" + local lc + lc="$(printf "%s" "$body" | tr '[:upper:]' '[:lower:]')" + local lag_sec + lag_sec="$(seconds_since_iso "$created_at")" + + if [[ "$lc" == *"hear me"* ]]; then + if [[ "$lag_sec" =~ ^[0-9]+$ ]] && [[ "$lag_sec" -ge 0 ]]; then + echo "@${from_handle#@} ${SOURCE_TAG} yes, hearing you. ${lag_sec}s from your message. path=geminimb poller." + else + echo "@${from_handle#@} ${SOURCE_TAG} yes, hearing you. path=geminimb poller." + fi + return 0 + fi + if [[ "$lc" == *"webhook and/or tmux"* ]]; then + echo "@${from_handle#@} ${SOURCE_TAG} path=geminimb poller on this runtime." + return 0 + fi + + # For normal conversation and tasks, return nothing here. + # The GUI will be nudged silently by post_reply and will provide the actual response. + echo "" +} + +seconds_since_iso() { + local ts="$1" + python3 - "$ts" <<'PY' +import datetime, sys +ts = sys.argv[1] +try: + dt = datetime.datetime.fromisoformat(ts.replace("Z", "+00:00")) + now = datetime.datetime.now(datetime.timezone.utc) + print(max(0, int((now - dt).total_seconds()))) +except Exception: + print(-1) +PY +} + +should_force_reply() { + local from_handle="$1" + local body="$2" + local lc + lc="$(printf "%s" "$body" | tr '[:upper:]' '[:lower:]')" + if [[ "$from_handle" != "$RESPOND_TO_HANDLE" ]]; then + return 1 + fi + if [[ "$lc" == *"do you hear me"* || "$lc" == *"report time in"* || "$lc" == *"webhook and/or tmux"* || "$lc" == *"all of you"* || "$lc" == *"can you"* || "$lc" == *"please"* || "$lc" == *"need to"* || "$lc" == *"check"* ]]; then + return 0 + fi + return 1 +} + +post_reply() { + local room="$1" + local from_handle="$2" + local created_at="$3" + local src_key="$4" + local src_body="$5" + + if has_id "$ACKED_IDS_FILE" "$src_key"; then + return 0 + fi + + local reply_body + reply_body="$(build_reply "$from_handle" "$created_at" "$src_body")" + + # 1. ALWAYS silently generate an LLM reply for valid tasks if there was no canned reply + if [[ -z "$reply_body" ]]; then + local lc + lc="$(printf "%s" "$src_body" | tr '[:upper:]' '[:lower:]')" + + local is_task=0 + if [[ "$lc" == *"can you"* || "$lc" == *"please"* || "$lc" == *"need to"* || "$lc" == *"check"* || "$lc" == *"fix"* || "$lc" == *"update"* || "$lc" == *"review"* || "$lc" == *"run"* || "$lc" == *"deploy"* || "$lc" == *"implement"* || "$lc" == *"test"* || "$lc" == *"restart"* || "$lc" == *"install"* || "$lc" == *"respond"* || "$lc" == *"post"* || "$lc" == *"pull"* || "$lc" == *"push"* || "$lc" == *"merge"* || "$lc" == *"make it"* || "$lc" == *"investigate"* || "$lc" == *"solve"* || "$lc" == *"handle"* || "$lc" == *"execute"* || "$lc" == *"perform"* || "$lc" == *"do"* || "$lc" == *"geminimb"* ]]; then + is_task=1 + fi + + local targets_me=1 + if [[ "$lc" == *"@claudemm"* || "$lc" == *"@antigravity"* || "$lc" == *"ag-codex"* || "$lc" == *"claude"* ]]; then + if [[ "$lc" != *"@geminimb"* && "$lc" != *"geminimb"* && "$lc" != *"gemini"* ]]; then + targets_me=0 + fi + fi + + if [[ "$is_task" == "1" && "$targets_me" == "1" ]]; then + local prompt_file="/tmp/geminimb_prompt.txt" + cat > "$prompt_file" </dev/null)"; then + # Trim leading/trailing whitespace and normalize newlines for the room post + llm_out="$(echo "${llm_out}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | tr '\n' ' ' | sed 's/[[:space:]]\+/ /g')" + if [[ -n "$llm_out" && "$llm_out" != "NO_REPLY" ]]; then + reply_body="@${from_handle#@} [geminimb] ${llm_out:0:1000}" + echo "[$(date +%H:%M:%S)] GENERATED reply: ${#reply_body} chars" + fi + else + echo "[$(date +%H:%M:%S)] Error generating LLM reply: $?" + fi + fi + fi + + if [[ -z "$reply_body" ]]; then + record_id "$ACKED_IDS_FILE" "$src_key" + return 0 + fi + + local payload + payload="$(python3 - <<'PY' "$room" "$reply_body" +import json, sys +room = sys.argv[1] +body = sys.argv[2] +print(json.dumps({"room": room, "body": body})) +PY +)" + + local res + if ! res="$(curl -sS -X POST \ + -H "X-API-Key: $API_KEY" \ + -H "Content-Type: application/json" \ + -d "$payload" \ + "$BASE_URL/messages")"; then + echo "[$(date +%H:%M:%S)] Error posting reply to $room: $res" + else + record_id "$ACKED_IDS_FILE" "$src_key" + echo "[$(date +%H:%M:%S)] REPLIED room=$room -> $from_handle (src=$src_key msg=$(echo "$res" | grep -o '"id":"[^"]*"' | cut -d'"' -f4))" + fi +} + +# tmux lifecycle +if [[ "${1:-}" == "tmux" ]]; then + cmd="${2:-start}" + case "$cmd" in + stop) + if tmux has-session -t "$SESSION" 2>/dev/null; then + tmux kill-session -t "$SESSION" + echo "Stopped $SESSION" + else + echo "$SESSION is not running" + fi + ;; + status) + if tmux has-session -t "$SESSION" 2>/dev/null; then + echo "$SESSION is running ($(tmux list-panes -t "$SESSION" -F '#{pane_pid}'))" + else + echo "$SESSION is not running" + fi + ;; + logs) + if tmux has-session -t "$SESSION" 2>/dev/null; then + tmux attach-session -t "$SESSION" + else + echo "$SESSION is not running" + exit 1 + fi + ;; + start|"") + if tmux has-session -t "$SESSION" 2>/dev/null; then + echo "$SESSION already running" + exit 0 + fi + tmux new-session -d -s "$SESSION" "$0" + echo "Started $SESSION (rooms=$ROOMS_CSV interval=${POLL_INTERVAL}s mention_only=$MENTION_ONLY)" + ;; + *) + echo "Usage: $0 tmux {start|stop|status|logs}" + exit 1 + ;; + esac + exit 0 +fi + +# --- PID lock: prevent duplicate pollers --- +if [[ -f "$LOCK_FILE" ]]; then + OLD_PID="$(cat "$LOCK_FILE" 2>/dev/null || true)" + if [[ -n "$OLD_PID" ]] && kill -0 "$OLD_PID" 2>/dev/null; then + echo "Another geminimb poller already running (PID $OLD_PID). Exiting." + exit 0 + fi + rm -f "$LOCK_FILE" +fi +echo $$ > "$LOCK_FILE" +trap 'rm -f "$LOCK_FILE"; exit 0' EXIT INT TERM + +touch "$SEEN_IDS_FILE" "$ACKED_IDS_FILE" +IFS=',' read -r -a ROOMS_ARRAY <<< "$ROOMS_CSV" +if [[ "$PRIME_ON_START" == "1" ]]; then + for raw_room in "${ROOMS_ARRAY[@]}"; do + room="$(echo "$raw_room" | xargs)" + [[ -z "$room" ]] && continue + prime_seen_ids "$room" + done +fi + +echo "[geminimb-autopost] rooms=$ROOMS_CSV poll=${POLL_INTERVAL}s limit=${FETCH_LIMIT} mention_only=$MENTION_ONLY" +echo "[geminimb-autopost] seen=$SEEN_IDS_FILE acked=$ACKED_IDS_FILE" + +while true; do + for raw_room in "${ROOMS_ARRAY[@]}"; do + room="$(echo "$raw_room" | xargs)" + [[ -z "$room" ]] && continue + + response="$(curl -sS -H "X-API-Key: $API_KEY" "$BASE_URL/rooms/$room/messages?limit=$FETCH_LIMIT" 2>/dev/null || true)" + if [[ -z "$response" ]]; then + echo "[$(date +%H:%M:%S)] fetch empty room=$room" + continue + fi + + while IFS=$'\t' read -r msg_id from_handle created_at mentioned body_preview; do + [[ -z "$msg_id" ]] && continue + msg_key="${room}::${msg_id}" + if has_id "$SEEN_IDS_FILE" "$msg_key"; then + continue + fi + record_id "$SEEN_IDS_FILE" "$msg_key" + + echo "[$(date +%H:%M:%S)] NEW room=$room $from_handle $msg_id at=$created_at ${body_preview:0:140}" + + if [[ "$from_handle" == "$AGENT_HANDLE" ]]; then + continue + fi + if [[ "$MENTION_ONLY" == "1" && "$mentioned" != "1" ]] && ! should_force_reply "$from_handle" "$body_preview"; then + continue + fi + + post_reply "$room" "$from_handle" "$created_at" "$msg_key" "$body_preview" || true + done < <(echo "$response" | python3 -c ' +import json, re, sys +try: + data = json.load(sys.stdin, strict=False) +except Exception: + sys.exit(0) +for m in data.get("messages", []): + mid = m.get("id", "") + frm = m.get("from", "") + created = m.get("created_at", "") + body = (m.get("body", "") or "").replace("\n", " ").replace("\t", " ") + mentioned = "1" if re.search(r"@geminimb\b", body, re.IGNORECASE) else "0" + print(f"{mid}\t{frm}\t{created}\t{mentioned}\t{body}") +') + done + + sleep "$POLL_INTERVAL" +done