diff --git a/.gitignore b/.gitignore index c48f6cd61..846e6cf74 100644 --- a/.gitignore +++ b/.gitignore @@ -89,3 +89,4 @@ docs/windows-port/ compound.config.json *.error.log _scratch/ +/odysseus/ diff --git a/LICENSE b/LICENSE index 7087e2d59..0c97efd25 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,235 @@ -MIT License +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 -Copyright (c) 2025 Odysseus Contributors +Copyright (C) 2007 Free Software Foundation, Inc. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + Preamble -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +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 4fae1d76b..a320f0052 100644 --- a/README.md +++ b/README.md @@ -451,7 +451,7 @@ All user data lives in `data/` (gitignored): `app.db` (sessions, messages, docum ## License -MIT -- see [LICENSE](LICENSE) and [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md). +AGPL-3.0-or-later -- see [LICENSE](LICENSE) and [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md). ``` | diff --git a/app.py b/app.py index 22b63cc82..cfd73e83f 100644 --- a/app.py +++ b/app.py @@ -47,6 +47,7 @@ from fastapi.responses import JSONResponse, FileResponse, HTMLResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from starlette.middleware.base import BaseHTTPMiddleware +from starlette.middleware.gzip import GZipMiddleware # Core imports from core.constants import ( @@ -104,6 +105,16 @@ app.add_middleware( ], ) +# ========= RESPONSE COMPRESSION (gzip) ========= +# The frontend's text assets (style.css, index.html, the JS bundles) shipped +# uncompressed on every cold load. gzip cuts CSS/JS/HTML by ~75-85% on the wire +# with no behavioural change. Starlette's GZipMiddleware excludes +# `text/event-stream` by default, so the SSE streams (chat, shell, research, +# model-probe — all served with media_type="text/event-stream") are never +# compressed or buffered; only complete bodies over minimum_size are. The +# security-header middleware composes cleanly on top. +app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=6) + # ========= SECURITY HEADERS MIDDLEWARE ========= app.add_middleware(SecurityHeadersMiddleware) @@ -472,6 +483,10 @@ components = initialize_managers(BASE_DIR, rag_manager) session_manager = components["session_manager"] from src.assistant_log import set_session_manager as _set_asst_sm _set_asst_sm(session_manager) +# Set the global session manager singleton (used by core.models.Session.add_message) +from core.models import set_session_manager_instance +set_session_manager_instance(session_manager) +app.state.session_manager = session_manager memory_manager = components["memory_manager"] memory_vector = components.get("memory_vector") upload_handler = components["upload_handler"] @@ -573,7 +588,7 @@ app.include_router(setup_preset_routes(preset_manager)) # Diagnostics from routes.diagnostics_routes import setup_diagnostics_routes -app.include_router(setup_diagnostics_routes(rag_manager, rag_available, research_handler)) +app.include_router(setup_diagnostics_routes(rag_manager, rag_available, research_handler, memory_vector)) # Cleanup from routes.cleanup_routes import setup_cleanup_routes diff --git a/core/models.py b/core/models.py index 1adae65ed..56f05dc4e 100644 --- a/core/models.py +++ b/core/models.py @@ -11,14 +11,24 @@ from typing import Dict, List, Any, Optional, TYPE_CHECKING if TYPE_CHECKING: from .session_manager import SessionManager -# Module-level session manager reference (set at app startup) -_session_manager: Optional["SessionManager"] = None +# Module-level session manager singleton (single source of truth) +_SESSION_MANAGER_INSTANCE: Optional["SessionManager"] = None -def set_session_manager(manager: "SessionManager"): - """Set the global session manager reference.""" - global _session_manager - _session_manager = manager +def set_session_manager_instance(manager: "SessionManager"): + """Set the global SessionManager singleton.""" + global _SESSION_MANAGER_INSTANCE + _SESSION_MANAGER_INSTANCE = manager + + +def get_session_manager_instance() -> Optional["SessionManager"]: + """Get the global SessionManager singleton.""" + return _SESSION_MANAGER_INSTANCE + + +# Keep legacy name for backward compatibility +set_session_manager = set_session_manager_instance +get_session_manager = get_session_manager_instance @dataclass @@ -42,7 +52,17 @@ class ChatMessage: @dataclass class Session: - """A chat session — pure data container.""" + """A chat session — pure data container. + + ``.history`` is the authoritative mutable message list. Callers may + read, append, pop, or reassign it directly — these changes take + effect immediately. ``_history`` remains a compatibility alias that + always resolves to the authoritative ``history`` list. + + Each session gets its own unique history list at construction time + (the dataclass default is never shared between instances). + """ + id: str name: str endpoint_url: str @@ -56,24 +76,35 @@ class Session: message_count: int = 0 def __post_init__(self): - if self.history is None: - self.history = [] if self.headers is None: self.headers = {} + # Ensure each session gets its OWN list (not the shared dataclass default) + if self.history is None: + self.history = [] + + @property + def _history(self) -> List[ChatMessage]: + """Compatibility alias for callers that still reference ``_history``.""" + return self.history + + @_history.setter + def _history(self, messages: List[ChatMessage]): + self.history = messages def add_message(self, message: ChatMessage): """ Add a message to this session. - Delegates to SessionManager for persistence if available, - otherwise just appends to history. + Appends to the authoritative history list and increments + message_count. Delegates to SessionManager for persistence + if available. """ self.history.append(message) self.message_count = len(self.history) # Delegate to session manager for persistence - if _session_manager: - _session_manager._persist_message(self.id, message) + if _SESSION_MANAGER_INSTANCE: + _SESSION_MANAGER_INSTANCE._persist_message(self.id, message) def get_context_messages(self) -> List[Dict[str, Any]]: """Get messages in format for LLM API. @@ -94,3 +125,7 @@ class Session: def get(self, key: str, default=None): """Dict-like access for compatibility.""" return getattr(self, key, default) + + def __getitem__(self, key: str): + """Allow session['field'] syntax.""" + return getattr(self, key) diff --git a/core/session_manager.py b/core/session_manager.py index ecc23e088..914205a7d 100644 --- a/core/session_manager.py +++ b/core/session_manager.py @@ -17,6 +17,9 @@ from typing import Dict, Optional from .database import Session as DbSession, ChatMessage as DbChatMessage, Document as DbDocument, SessionLocal, utcnow_naive from .models import Session, ChatMessage +# Re-export singleton accessors from models for convenience +from .models import set_session_manager_instance, get_session_manager_instance + logger = logging.getLogger(__name__) @@ -188,12 +191,17 @@ class SessionManager: """ Add a message to a session and persist to database. + Updates the authoritative history list and persists through this + manager directly so tests and temporary managers do not depend on the + process-wide session-manager singleton. + Args: session_id: Session ID message: ChatMessage to add """ session = self.get_session(session_id) session.history.append(message) + session._history = session.history session.message_count = len(session.history) self._persist_message(session_id, message) @@ -232,7 +240,10 @@ class SessionManager: ) db.add(db_message) - db_session.message_count = len(self.sessions.get(session_id, {}).history) if session_id in self.sessions else 0 + if session_id in self.sessions: + db_session.message_count = len(self.sessions[session_id].history) + else: + db_session.message_count = 0 _now = datetime.now(timezone.utc) db_session.last_accessed = _now # Clean "last conversation" timestamp — only bumped here on a @@ -283,6 +294,7 @@ class SessionManager: # Update in-memory session.history = session.history[:keep_count] + session._history = session.history logger.info(f"Truncated session {session_id} to {keep_count} messages") return True @@ -333,6 +345,7 @@ class SessionManager: db.commit() session.history = list(messages) + session._history = session.history session.message_count = len(messages) logger.info("Replaced session %s history with %d messages", session_id, len(messages)) return True @@ -608,24 +621,52 @@ class SessionManager: def save_sessions(self): """No-op for DB compatibility.""" + def ensure_task_session(self, session_id: str, name: str, endpoint_url: str, model: str, owner: str = None, task: object = None) -> Session: + """Create a task session if it doesn't exist, or return the existing one. + + Unlike create_session, this checks the cache first and does NOT + overwrite an existing in-memory session. The task scheduler must + use this instead of direct dict assignment. + """ + if session_id in self.sessions: + return self.sessions[session_id] + + session = self.create_session(session_id, name, endpoint_url, model, owner=owner) + if task is not None: + task.session_id = session_id + return session + # ------------------------------------------------------------------ # Cleanup # ------------------------------------------------------------------ - def cleanup_empty_sessions(self, auto_archive_days: int = 30) -> dict: - """Clean up empty and old sessions.""" + def cleanup_empty_sessions(self, auto_archive_days: int = 30, min_age_hours: int = 1) -> dict: + """Clean up empty and old sessions. + + Args: + auto_archive_days: Age in days before non-important sessions are archived. + min_age_hours: Minimum age in hours before an empty session can be deleted. + Prevents deleting sessions that were just created. + """ db = SessionLocal() stats = {'deleted_empty': 0, 'archived_old': 0, 'total_checked': 0} try: all_sessions = db.query(DbSession).all() cutoff_date = utcnow_naive() - timedelta(days=auto_archive_days) + min_age = utcnow_naive() - timedelta(hours=min_age_hours) for db_session in all_sessions: stats['total_checked'] += 1 - # Delete empty sessions + # Delete empty sessions only if older than min_age_hours if db_session.message_count == 0: + if db_session.created_at is not None: + created = db_session.created_at + if created.tzinfo is None: + created = created.replace(tzinfo=timezone.utc) + if created > min_age: + continue # Too young to delete if db_session.id in self.sessions: del self.sessions[db_session.id] db.delete(db_session) diff --git a/pyproject.toml b/pyproject.toml index 58161958f..da00ee259 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,4 +15,8 @@ markers = [ "area_helpers: self-tests for the shared test helpers in tests/helpers/", "area_unit: pure parser / utility tests that do not clearly belong elsewhere", "area_uncategorized: tests not yet matched by the taxonomy (fallback)", + # Fast-lane marker (issue #3443). Opt-in and orthogonal to the area_*/sub_* + # taxonomy. The fast lane runs `not slow`; mark a test slow only with + # duration evidence (see tests/run_focus.py --durations and tests/README.md). + "slow: opt-in marker for known-slow tests; excluded by the fast lane (not slow)", ] diff --git a/routes/api_token_routes.py b/routes/api_token_routes.py index 05806e420..6f8ac2fc9 100644 --- a/routes/api_token_routes.py +++ b/routes/api_token_routes.py @@ -67,6 +67,7 @@ def _normalize_scopes(scopes: str | list[str] | None = None, profile: str | None ensure_before("calendar:write", "calendar:read") ensure_before("memory:write", "memory:read") ensure_before("email:draft", "email:read") + ensure_before("cookbook:launch", "cookbook:read") return normalized or [DEFAULT_SCOPES] diff --git a/routes/auth_routes.py b/routes/auth_routes.py index 9379bced8..c20860892 100644 --- a/routes/auth_routes.py +++ b/routes/auth_routes.py @@ -7,7 +7,13 @@ import asyncio import logging import os +import json +import re +from pathlib import Path + +from core.atomic_io import atomic_write_json, atomic_write_text from core.auth import AuthManager +from src.constants import DEEP_RESEARCH_DIR, MEMORY_FILE, SKILLS_DIR from src.rate_limiter import RateLimiter from src.settings_scrub import scrub_settings from src.settings import ( @@ -291,9 +297,17 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter: if new_username in auth_manager.users: raise HTTPException(409, "Username already taken") + # Gate on auth first. Every mutation below is contingent on this + # succeeding — doing it last meant a rejected rename (e.g. reserved + # username) left file-backed owner fields already rewritten with no + # way to roll them back. + ok = auth_manager.rename_user(old_username, new_username, user) + if not ok: + raise HTTPException(400, "Cannot rename user") + # Usernames are ownership keys for user data. Rename the common - # owner-scoped DB rows before changing auth so the account keeps - # access to its sessions, docs, email accounts, tasks, etc. + # owner-scoped DB rows so the account keeps access to its sessions, + # docs, email accounts, tasks, etc. try: from sqlalchemy import func from core.database import Base, SessionLocal @@ -335,9 +349,90 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter: except Exception as e: logger.warning("Failed to rename user prefs %s -> %s: %s", old_username, new_username, e) - ok = auth_manager.rename_user(old_username, new_username, user) - if not ok: - raise HTTPException(400, "Cannot rename user") + # deep_research: each completed report is a standalone JSON file with + # an `owner` field. research_routes filters by d.get("owner") == user, + # so a stale owner makes every report invisible to the renamed user. + try: + dr_dir = Path(DEEP_RESEARCH_DIR) + if dr_dir.is_dir(): + for p in dr_dir.glob("*.json"): + try: + d = json.loads(p.read_text(encoding="utf-8")) + if str(d.get("owner", "")).strip().lower() == old_username: + d["owner"] = new_username + atomic_write_json(str(p), d) + except Exception as err: + logger.warning("Failed to update research owner in %s: %s", p.name, err) + except Exception as e: + logger.warning("Failed to rename research owner references %s -> %s: %s", old_username, new_username, e) + + # memory.json: a flat JSON array where each entry carries an `owner` + # field. memory_manager.load(owner=user) filters on it, so stale + # entries disappear from the memory panel. + try: + if os.path.isfile(MEMORY_FILE): + with open(MEMORY_FILE, encoding="utf-8") as fh: + entries = json.loads(fh.read()) + if isinstance(entries, list): + changed = False + for entry in entries: + if isinstance(entry, dict) and str(entry.get("owner", "")).strip().lower() == old_username: + entry["owner"] = new_username + changed = True + if changed: + atomic_write_json(MEMORY_FILE, entries) + except Exception as e: + logger.warning("Failed to rename memory.json owner references %s -> %s: %s", old_username, new_username, e) + + # skills: SKILL.md frontmatter carries owner: ; the usage + # sidecar (_usage.json) keys entries as owner::skill-name. Both must + # be updated or the renamed user's Skills panel goes empty. + try: + skills_root = Path(SKILLS_DIR) + if skills_root.is_dir(): + _owner_re = re.compile( + r'(?m)^(owner:\s*)' + re.escape(old_username) + r'\s*$' + ) + for p in skills_root.rglob("SKILL.md"): + try: + text = p.read_text(encoding="utf-8") + new_text = _owner_re.sub(r'\g<1>' + new_username, text) + if new_text != text: + atomic_write_text(str(p), new_text) + except Exception as err: + logger.warning("Failed to update skill owner in %s: %s", p, err) + usage_path = skills_root / "_usage.json" + if usage_path.is_file(): + try: + usage = json.loads(usage_path.read_text(encoding="utf-8")) + if isinstance(usage, dict): + prefix = old_username + "::" + new_usage = {} + changed = False + for k, v in usage.items(): + if k.startswith(prefix): + new_usage[new_username + "::" + k[len(prefix):]] = v + changed = True + else: + new_usage[k] = v + if changed: + atomic_write_json(str(usage_path), new_usage) + except Exception as err: + logger.warning("Failed to update skills usage keys %s -> %s: %s", old_username, new_username, err) + except Exception as e: + logger.warning("Failed to rename skills owner references %s -> %s: %s", old_username, new_username, e) + + # The in-memory session cache (session_manager.sessions) stores each + # session's owner at load time. Without this patch the renamed user's + # sessions are invisible on the next /api/sessions call because + # get_sessions_for_user does an exact `s.owner == username` comparison + # against stale in-memory values. + sm = getattr(request.app.state, "session_manager", None) + if sm is not None: + for sess in list(getattr(sm, "sessions", {}).values()): + if str(getattr(sess, "owner", None) or "").strip().lower() == old_username: + sess.owner = new_username + # The owner-rename loop above updated ApiToken.owner in the DB, but the # bearer-token cache still maps each token to the OLD owner. Without # refreshing it, the renamed user's API tokens resolve to the old (now diff --git a/routes/backup_routes.py b/routes/backup_routes.py index 5ca403f81..313369370 100644 --- a/routes/backup_routes.py +++ b/routes/backup_routes.py @@ -101,11 +101,17 @@ def setup_backup_routes(memory_manager, preset_manager, skills_manager) -> APIRo # ── Skills ── if "skills" in body and isinstance(body["skills"], list): existing = skills_manager.load_all() - existing_names = {s.get("name") for s in existing if s.get("name")} - existing_ids = {s.get("id") for s in existing if s.get("id")} + # Dedup against THIS user's own skills only. Using every tenant's + # rows (load_all) meant a skill whose id/name/title matched any + # other user's was silently skipped, so the importing user lost + # their own data — same cross-tenant bug fixed for memories above. + # The full store is still saved back below. + own = [s for s in existing if s.get("owner") == user] + existing_names = {s.get("name") for s in own if s.get("name")} + existing_ids = {s.get("id") for s in own if s.get("id")} existing_titles = { (s.get("title") or s.get("description") or "").strip().lower() - for s in existing + for s in own } added = 0 for skill in body["skills"]: diff --git a/routes/calendar_routes.py b/routes/calendar_routes.py index 345280528..7b36df06a 100644 --- a/routes/calendar_routes.py +++ b/routes/calendar_routes.py @@ -851,28 +851,27 @@ def setup_calendar_routes() -> APIRouter: from src.caldav_sync import sync_caldav return await sync_caldav(owner) + @router.delete("/calendars/{cal_id}") - async def delete_calendar(cal_id: str, request: Request): + async def delete_calendar(request: Request, cal_id: str): owner = _require_user(request) db = SessionLocal() try: - cal = db.query(CalendarCal).filter( - CalendarCal.id == cal_id, - CalendarCal.owner == owner, - ).first() - if not cal: - raise HTTPException(404, "Calendar not found") + cal = _get_or_404_calendar(db, cal_id, owner) + db.query(CalendarEvent).filter(CalendarEvent.calendar_id == cal_id).delete() db.delete(cal) db.commit() return {"ok": True} except HTTPException: raise except Exception as e: + db.rollback() logger.error("Failed to delete calendar %s: %s", cal_id, e) raise HTTPException(500, "Failed to delete calendar") finally: db.close() + @router.get("/calendars") async def list_calendars(request: Request): owner = _require_user(request) @@ -1152,23 +1151,6 @@ def setup_calendar_routes() -> APIRouter: finally: db.close() - @router.delete("/calendars/{cal_id}") - async def delete_calendar(request: Request, cal_id: str): - owner = _require_user(request) - db = SessionLocal() - try: - cal = _get_or_404_calendar(db, cal_id, owner) - db.query(CalendarEvent).filter(CalendarEvent.calendar_id == cal_id).delete() - db.delete(cal) - db.commit() - return {"ok": True} - except HTTPException: - raise - except Exception as e: - db.rollback() - return {"error": str(e)} - finally: - db.close() # Hard cap on ICS upload (ICS_MAX_BYTES, default 10 MB). Loading the whole # file into memory is unavoidable with python-icalendar, so an unbounded diff --git a/routes/chat_helpers.py b/routes/chat_helpers.py index 0b1c5d8ba..c32161bb1 100644 --- a/routes/chat_helpers.py +++ b/routes/chat_helpers.py @@ -615,6 +615,26 @@ async def build_chat_context( # Build messages messages = preface + sess.get_context_messages() + # Current date/time — injected as a standalone *user*-role context message + # placed immediately before the latest user turn, NOT folded into the + # system prompt. Its text changes every minute, and local OpenAI-compatible + # backends (llama.cpp / LM Studio) key their KV-cache prefix off the + # system message byte-for-byte; mixing ever-changing timestamp text into + # it would invalidate the cached prefix on every request (issue #2927). + # Placing it at the tail also keeps it out of the stable + # preface+history prefix, so that prefix stays byte-identical turn over + # turn (modulo the genuinely new history entries) and the cache survives. + if not agent_mode: + try: + from src.user_time import current_datetime_context_message + _dt_msg = current_datetime_context_message() + if messages and messages[-1].get("role") == "user": + messages.insert(len(messages) - 1, _dt_msg) + else: + messages.append(_dt_msg) + except Exception: + logger.debug("Failed to add current date/time context", exc_info=True) + # Auto-compact messages, context_length, was_compacted = await maybe_compact( sess, sess.endpoint_url, sess.model, messages, sess.headers, owner=user, @@ -911,6 +931,54 @@ def save_assistant_response( return None +def _is_session_stream_active(session_id: str) -> bool: + """Best-effort check for "is a chat completion currently streaming for + this session?" — used to keep background extraction from overlapping a + main completion and competing for the local backend's processing slots + (issue #2927). Lazily imports the route module's live registry to avoid + a circular import (chat_routes imports this module at load time).""" + try: + from routes import chat_routes as _cr + return session_id in getattr(_cr, "_active_streams", {}) + except Exception: + return False + + +async def _run_extraction_jobs_sequentially(session_id: str, jobs: list, max_wait_s: float = 120.0): + """Run queued background-extraction coroutines one at a time, only once + no chat completion is actively streaming for this session. + + As diagnosed in issue #2927, firing memory/skill extraction concurrently + with the main chat completion (or with each other) makes them compete for + the local backend's limited processing slots, evicting the main + conversation's cached KV-cache checkpoint and forcing a full prompt + re-evaluation on the next turn. Waiting for the stream to go idle and then + running the jobs strictly in sequence keeps at most one "side" request in + flight against the backend at any time, and never alongside the user's + own conversation. + """ + # Wait for the triggering turn's own stream to finish winding down (it + # almost always already has by the time this task gets scheduled — this + # is a small safety margin, not the primary mechanism). + waited = 0.0 + poll = 0.25 + while _is_session_stream_active(session_id) and waited < max_wait_s: + await asyncio.sleep(poll) + waited += poll + + for name, job in jobs: + # Re-check before each job: a fast follow-up message from the user + # may have started a new stream for this session while we waited. + waited = 0.0 + while _is_session_stream_active(session_id) and waited < max_wait_s: + await asyncio.sleep(poll) + waited += poll + try: + await job + except Exception: + logger.warning("[bg-extract] %s extraction job failed for session %s", name, session_id, exc_info=True) + + def run_post_response_tasks( sess, session_manager, @@ -933,7 +1001,22 @@ def run_post_response_tasks( extract_skills: bool = True, allow_background_extraction: bool = True, ): - """Fire background tasks after a completed response: memory extraction, webhooks, auto-name, skill extraction.""" + """Fire background tasks after a completed response: memory extraction, webhooks, auto-name, skill extraction. + + Memory/skill extraction are queued to run *sequentially*, after the main + completion stream for this session has fully wound down — never + concurrently with it or with each other. As diagnosed in issue #2927, + firing these "side" LLM calls in parallel with the main chat completion + makes them compete for the local backend's limited processing slots + (llama.cpp defaults to 4), evicting the main conversation's cached + checkpoint and forcing a full prompt re-evaluation on the next turn. By + the time this function runs the main response is already saved, but the + extraction calls themselves are still async — queuing them through + ``_queue_background_extraction`` keeps them from overlapping the *next* + turn's request too. + """ + _extraction_jobs: list = [] + # Memory extraction — only every 4th message pair to avoid excess LLM calls _msg_count = len(sess.history) if hasattr(sess, 'history') else 0 _should_extract = (_msg_count >= 4) and (_msg_count % 4 == 0) @@ -943,10 +1026,10 @@ def run_post_response_tasks( t_url, t_model, t_headers = resolve_task_endpoint( sess.endpoint_url, sess.model, sess.headers, owner=owner, ) - asyncio.create_task(extract_and_store( + _extraction_jobs.append(("memory", extract_and_store( sess, memory_manager, memory_vector, t_url, t_model, t_headers, - )) + ))) # Skill extraction from complex agent runs. Only when the user actually # chose agent mode — not a chat we auto-escalated for a notes/calendar @@ -982,12 +1065,15 @@ def run_post_response_tasks( sess.endpoint_url, sess.model, sess.headers, owner=owner, ) logger.debug("[skill-extract] dispatching extractor (model=%s)", s_model) - asyncio.create_task(maybe_extract_skill( + _extraction_jobs.append(("skill", maybe_extract_skill( sess, skills_manager, s_url, s_model, s_headers, agent_rounds, agent_tool_calls, owner=owner, - )) + ))) + + if _extraction_jobs: + asyncio.create_task(_run_extraction_jobs_sequentially(session_id, _extraction_jobs)) # Token accumulation if last_metrics: diff --git a/routes/chat_routes.py b/routes/chat_routes.py index 39c17ec6c..3e18bf5c6 100644 --- a/routes/chat_routes.py +++ b/routes/chat_routes.py @@ -400,6 +400,7 @@ def setup_chat_routes( temperature=ctx.preset.temperature, max_tokens=ctx.preset.max_tokens, prompt_type=preset_id, + session_id=session, ) _clean_reply, _clean_md = clean_thinking_for_save(reply, {"model": sess.model}) sess.add_message(ChatMessage("assistant", _clean_reply, metadata=_clean_md)) @@ -456,7 +457,6 @@ def setup_chat_routes( # manual form posts that still send plan_mode=true. plan_mode = False chat_mode = str(form_data.get("mode", "")).lower() # 'chat' or 'agent' - workspace = "" # Plan mode is a modifier on agent mode — it only makes sense with tools. if plan_mode: chat_mode = "agent" @@ -635,7 +635,7 @@ def setup_chat_routes( # leak a doc that belongs to a DIFFERENT session. if not active_doc: try: - from src.tool_implementations import get_active_document + from src.agent_tools.document_tools import get_active_document _mem_id = get_active_document() if _mem_id: _mem_q = _doc_db.query(DBDocument).filter(DBDocument.id == _mem_id) @@ -989,6 +989,7 @@ def setup_chat_routes( max_tokens=ctx.preset.max_tokens, prompt_type=preset_id, tools=None, + session_id=session, ): if chunk.startswith("data: ") and not chunk.startswith("data: [DONE]"): try: @@ -1135,7 +1136,6 @@ def setup_chat_routes( tool_policy=tool_policy, owner=_user, fallbacks=_fallback_candidates, - workspace=None, plan_mode=plan_mode, approved_plan=approved_plan or None, ): diff --git a/routes/cookbook_helpers.py b/routes/cookbook_helpers.py index a450278be..709245287 100644 --- a/routes/cookbook_helpers.py +++ b/routes/cookbook_helpers.py @@ -42,9 +42,16 @@ _SESSION_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$") _SSH_PORT_RE = re.compile(r"^\d{1,5}$") _GPU_LIST_RE = re.compile(r"^\d+(?:,\d+)*$") # A download target directory. Absolute or ~-relative path; safe path glyphs -# only (no quotes, shell metacharacters, or spaces) since it lands in a shell -# command. A leading ~ is expanded to $HOME at command-build time. -_LOCAL_DIR_RE = re.compile(r"^~?/[A-Za-z0-9._/-]*$|^~$") +# only (no quotes or shell metacharacters). Spaces are allowed because command +# builders pass the value through quoted shell/Python contexts. The character +# class uses ``\w`` — Unicode word characters under Python 3's default str +# matching — so non-ASCII folder names pass validation too: Cyrillic, accented +# Latin, CJK, e.g. ``/Volumes/Модели`` or ``D:\AI Models\Модели``. This stays +# shell-safe: none of ``; & | ` $ '' "" () {}`` newlines etc. are in ``[\w. -]``, +# so injection vectors remain rejected. A leading ~ is expanded to $HOME at +# command-build time. (Drive letters stay ASCII: ``[A-Za-z]:``.) +_LOCAL_DIR_RE = re.compile(r"^~?(?:/[\w. -]*)+$|^~$") +_WINDOWS_LOCAL_DIR_RE = re.compile(r"^[A-Za-z]:[\\/](?:[\w. -]+(?:[\\/][\w. -]+)*[\\/]?)?$") _WINDOWS_DRIVE_PATH_RE = re.compile(r"^[A-Za-z]:[\\/]") @@ -97,9 +104,19 @@ def _validate_token(v: str | None) -> str | None: def _validate_local_dir(v: str | None) -> str | None: if v is None or v == "": return None + if len(v) >= 2 and v[0] == v[-1] and v[0] in {"'", '"'}: + v = v[1:-1] v = v.rstrip("/") or "/" - if not _LOCAL_DIR_RE.match(v): - raise HTTPException(400, "Invalid local_dir — must be an absolute or ~ path with no spaces or shell metacharacters") + if not (_LOCAL_DIR_RE.match(v) or _WINDOWS_LOCAL_DIR_RE.match(v)): + raise HTTPException(400, "Invalid local_dir — must be an absolute or ~ path with no shell metacharacters") + # Reject path segments that start with '-' (option injection). '-' is in the + # allowlist, so a dir like ``/models/-rf`` or ``D:\models\-rf`` could be read + # as a CLI flag by hf/etc. — and quoting does NOT stop a value from being + # parsed as an option. This is the one residual that command-build-time + # quoting can't cover, so the guard lives here, keeping the safety wholly + # inside the validator rather than relying on consumers. + if any(seg.startswith("-") for seg in re.split(r"[\\/]", v) if seg): + raise HTTPException(400, "Invalid local_dir — path segments cannot start with '-'") return v @@ -125,7 +142,7 @@ def _validate_gpus(v: str | None) -> str | None: def _shell_path(p: str) -> str: """Render a validated path for a double-quoted shell context, expanding a leading ~ to $HOME (single quotes wouldn't expand it). Safe because - _validate_local_dir already restricts the charset.""" + _validate_local_dir already rejects quotes and shell metacharacters.""" if p == "~": return '"$HOME"' if p.startswith("~/"): @@ -386,6 +403,7 @@ def _cached_model_scan_script(model_dirs: list[str] | None = None, add_hf_cache: " for root, dirs, fns in safe_walk(base):", " for fn in sorted(fns):", " if not fn.lower().endswith('.gguf'): continue", + " if fn.startswith('._'): continue # macOS AppleDouble sidecar, not a real GGUF", " fp = os.path.join(root, fn)", " try: size = os.path.getsize(fp)", " except Exception: size = 0", diff --git a/routes/cookbook_routes.py b/routes/cookbook_routes.py index 081638cae..4a4764232 100644 --- a/routes/cookbook_routes.py +++ b/routes/cookbook_routes.py @@ -15,6 +15,7 @@ from pathlib import Path from fastapi import APIRouter, HTTPException, Request, Depends from src.auth_helpers import require_user +from src.constants import COOKBOOK_STATE_FILE from pydantic import BaseModel from core.middleware import require_admin @@ -54,7 +55,7 @@ _HF_TOKEN_STATUS_SNIPPET = ( def setup_cookbook_routes() -> APIRouter: router = APIRouter(tags=["cookbook"]) - _cookbook_state_path = Path(os.environ.get("DATA_DIR", "data")) / "cookbook_state.json" + _cookbook_state_path = Path(COOKBOOK_STATE_FILE) def _mask_secret(value: str) -> str: if not value: diff --git a/routes/diagnostics_routes.py b/routes/diagnostics_routes.py index daebef8d2..d6763798d 100644 --- a/routes/diagnostics_routes.py +++ b/routes/diagnostics_routes.py @@ -16,9 +16,18 @@ def setup_diagnostics_routes( rag_manager, rag_available: bool, research_handler, + memory_vector=None, ) -> APIRouter: router = APIRouter(tags=["diagnostics"]) + @router.get("/api/diagnostics/services") + async def get_service_health(request: Request) -> Dict[str, Any]: + """Consolidated degraded-state report for ChromaDB, SearXNG, email, + ntfy, and provider endpoints. Non-intrusive probes — safe to poll.""" + require_admin(request) + from src.service_health import collect_service_health + return await collect_service_health(rag_manager, memory_vector) + @router.get("/api/db/stats") async def get_database_stats(request: Request) -> Dict[str, Any]: require_admin(request) diff --git a/routes/document_routes.py b/routes/document_routes.py index cb41108e0..e4598d925 100644 --- a/routes/document_routes.py +++ b/routes/document_routes.py @@ -108,10 +108,10 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter: # to markdown for prose. language = req.language if not language: - from src.tool_implementations import _looks_like_email_document, _sniff_doc_language + from src.agent_tools.document_tools import _looks_like_email_document, _sniff_doc_language language = _sniff_doc_language(req.content) else: - from src.tool_implementations import _looks_like_email_document + from src.agent_tools.document_tools import _looks_like_email_document if _looks_like_email_document(req.content, req.title): language = "email" @@ -643,7 +643,7 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter: # in-memory active-doc pointer so the last-resort injection # path doesn't re-surface this doc in a later chat (#1160). try: - from src.tool_implementations import clear_active_document + from src.agent_tools.document_tools import clear_active_document clear_active_document(doc_id) except Exception: pass @@ -672,7 +672,7 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter: # Closed/deleted — drop the in-memory active-doc pointer so it isn't # re-injected into a later, unrelated chat (#1160). try: - from src.tool_implementations import clear_active_document + from src.agent_tools.document_tools import clear_active_document clear_active_document(doc_id) except Exception: pass diff --git a/routes/email_helpers.py b/routes/email_helpers.py index 890680a87..7626b58c2 100644 --- a/routes/email_helpers.py +++ b/routes/email_helpers.py @@ -762,10 +762,14 @@ def _open_imap_connection(host: str, port: int, *, starttls: bool, timeout: int imaplib._MAXLINE = 50_000_000 return conn -def _imap_connect(account_id: str | None = None, owner: str = ""): +def _imap_connect(account_id: str | None = None, owner: str = "", + timeout: int = _IMAP_TIMEOUT_SECONDS): # SECURITY: passing `owner` scopes the fallback config lookup so a brand # new user doesn't get connected against another user's default mailbox # when they have no account configured. + # + # `timeout` is overridable so short-lived callers (e.g. the service-health + # probe) can impose a tighter budget than the default IMAP timeout. cfg = _get_email_config(account_id, owner=owner) # Connection mode: # STARTTLS on → plain + upgrade @@ -778,7 +782,7 @@ def _imap_connect(account_id: str | None = None, owner: str = ""): cfg["imap_host"], cfg["imap_port"], starttls=bool(cfg.get("imap_starttls")), - timeout=_IMAP_TIMEOUT_SECONDS, + timeout=timeout, ) try: conn.login(cfg["imap_user"], cfg["imap_password"]) diff --git a/routes/gallery_helpers.py b/routes/gallery_helpers.py index 5cab62791..e4005b8a7 100644 --- a/routes/gallery_helpers.py +++ b/routes/gallery_helpers.py @@ -11,6 +11,7 @@ from typing import Dict, Any, Optional from pydantic import BaseModel from core.database import GalleryImage +from src.auth_helpers import _auth_disabled logger = logging.getLogger(__name__) @@ -120,19 +121,18 @@ def _image_to_dict(img: GalleryImage, session_name: str = None) -> Dict[str, Any } -def _owner_filter(q, user): +def _owner_filter(q, user, model_cls=GalleryImage): """Apply owner filtering to a gallery query. - When auth is disabled (single-user mode) get_current_user returns None - and there is no per-user scoping. The main library list and stats already - treat None as "show everything" (`if user is not None`), so this helper - must too — otherwise the tag/model filter sidebars come back empty and the - tag-cleanup endpoints (clear-user-tags, clear-ai-tags, dedupe-tags) - silently affect zero rows in the most common self-hosted deployment. + ``get_current_user`` returns None both in auth-disabled single-user mode + and when auth is enabled but no current user was resolved. Preserve the + single-user behavior, but fail closed for auth-enabled null-user states. """ - if user is None: + if user is not None: + return q.filter(model_cls.owner == user) + if _auth_disabled(): return q - return q.filter(GalleryImage.owner == user) + return q.filter(False) diff --git a/routes/gallery_routes.py b/routes/gallery_routes.py index 43999344e..feadc2ec8 100644 --- a/routes/gallery_routes.py +++ b/routes/gallery_routes.py @@ -476,8 +476,7 @@ def setup_gallery_routes() -> APIRouter: .outerjoin(DbSession, GalleryImage.session_id == DbSession.id) .filter(GalleryImage.is_active == True) ) - if user is not None: - q = q.filter(GalleryImage.owner == user) + q = _owner_filter(q, user) # Search filter (prompt + tags + ai_tags) if search: @@ -579,28 +578,26 @@ def setup_gallery_routes() -> APIRouter: db = SessionLocal() try: q = db.query(GalleryAlbum) - if user: - q = q.filter(GalleryAlbum.owner == user) + q = _owner_filter(q, user, GalleryAlbum) albums = q.order_by(GalleryAlbum.created_at.desc()).all() result = [] for a in albums: _count_q = db.query(GalleryImage).filter( GalleryImage.album_id == a.id, GalleryImage.is_active == True ) - if user: - _count_q = _count_q.filter(GalleryImage.owner == user) + _count_q = _owner_filter(_count_q, user) count = _count_q.count() cover_url = None if a.cover_id: - cover = db.query(GalleryImage).filter(GalleryImage.id == a.cover_id).first() + cover_q = db.query(GalleryImage).filter(GalleryImage.id == a.cover_id) + cover = _owner_filter(cover_q, user).first() if cover: cover_url = f"/api/generated-image/{cover.filename}" elif count > 0: _cover_q = db.query(GalleryImage).filter( GalleryImage.album_id == a.id, GalleryImage.is_active == True ) - if user: - _cover_q = _cover_q.filter(GalleryImage.owner == user) + _cover_q = _owner_filter(_cover_q, user) first = _cover_q.order_by(GalleryImage.created_at.desc()).first() if first: cover_url = f"/api/generated-image/{first.filename}" @@ -643,10 +640,9 @@ def setup_gallery_routes() -> APIRouter: base = db.query(GalleryImage).filter(GalleryImage.is_active == True) size_q = db.query(func.sum(GalleryImage.file_size)).filter(GalleryImage.is_active == True) album_q = db.query(GalleryAlbum) - if user: - base = base.filter(GalleryImage.owner == user) - size_q = size_q.filter(GalleryImage.owner == user) - album_q = album_q.filter(GalleryAlbum.owner == user) + base = _owner_filter(base, user) + size_q = _owner_filter(size_q, user) + album_q = _owner_filter(album_q, user, GalleryAlbum) total = base.count() total_size = size_q.scalar() or 0 fav_count = base.filter(GalleryImage.favorite == True).count() @@ -674,8 +670,7 @@ def setup_gallery_routes() -> APIRouter: GalleryImage.is_active == True, (GalleryImage.ai_tags == None) | (GalleryImage.ai_tags == ""), ) - if user: - q = q.filter(GalleryImage.owner == user) + q = _owner_filter(q, user) if album_id: q = q.filter(GalleryImage.album_id == album_id) untagged = q.count() diff --git a/routes/model_routes.py b/routes/model_routes.py index 864035884..b88fa3ef1 100644 --- a/routes/model_routes.py +++ b/routes/model_routes.py @@ -283,6 +283,7 @@ _HOST_TO_CURATED = ( ("fireworks.ai", "fireworks"), ("googleapis.com", "google"), ("x.ai", "xai"), + ("nvidia.com", "nvidia"), ("openrouter.ai", "openrouter"), ("ollama.com", "ollama"), ) @@ -477,10 +478,17 @@ _NON_CHAT_PREFIXES = ( "dall-e", "tts-", "whisper", "text-embedding", "embedding", "davinci", "babbage", "moderation", "omni-moderation", "sora", "gpt-image", "chatgpt-image", + # embedding / retrieval / non-chat models (common across providers) + "snowflake/arctic-embed", "nvidia/nv-embed", "embed", ) _NON_CHAT_CONTAINS = ( "-realtime", "-transcribe", "-tts", "-codex", - "codex-", + "codex-", "content-safety", "-safety", "-reward", "nvclip", + "kosmos", "fuyu", "deplot", "vila", "neva", + "gliner", "riva", "-parse", "-embedqa", "-nemoretriever", + "topic-control", "calibration", + "ai-synthetic-video", "cosmos-reason2", + "bge", "llama-guard", ) _NON_CHAT_EXACT_PREFIXES = ( "gpt-audio", # gpt-audio, gpt-audio-mini etc. (not gpt-4o-audio-preview which is chat) @@ -731,7 +739,7 @@ def _probe_endpoint(base_url: str, api_key: str = None, timeout: int = 5) -> Lis for _e in _PROVIDER_CURATED.get(_ck, []): if _e not in set(models) and not any(m.startswith(_e) for m in models): models.append(_e) - return models + return [m for m in models if _is_chat_model(m)] except httpx.HTTPStatusError as e: if api_key: status = e.response.status_code if e.response is not None else "unknown" @@ -755,7 +763,7 @@ def _probe_endpoint(base_url: str, api_key: str = None, timeout: int = 5) -> Lis data = r.json() models = [m.get("name") or m.get("model") for m in (data.get("models") or []) if m.get("name") or m.get("model")] if models: - return models + return [m for m in models if _is_chat_model(m)] except Exception as e: logger.debug(f"Ollama /api/tags probe failed for {base}: {e}") # Fall back to curated list if the provider has a URL-based match (e.g. z.ai has no /models endpoint) diff --git a/services/research/research_handler.py b/services/research/research_handler.py index bd4c6bb15..2521f61e1 100644 --- a/services/research/research_handler.py +++ b/services/research/research_handler.py @@ -285,6 +285,7 @@ class ResearchHandler: query, report, stats, elapsed, findings=researcher.findings, evolving_report=researcher.evolving_report, + analyzed_urls=getattr(researcher, "analyzed_urls", None), ) except Exception as e: @@ -331,7 +332,8 @@ class ResearchHandler: def _format_research_report( self, query: str, full_report: str, stats: dict, elapsed: float, - findings: list = None, evolving_report: str = None, + findings: Optional[list] = None, evolving_report: Optional[str] = None, + analyzed_urls: Optional[list] = None, ) -> str: """Format research report with sources list and expandable raw findings.""" summary_lines = [ @@ -342,20 +344,34 @@ class ResearchHandler: ] summary_text = " | ".join(summary_lines) - # Build sources list with clickable links + # Build sources list with clickable links. Keep the curated Sources + # section filtered for citation quality, but also list every unique URL + # the research run inspected so the "URLs Analyzed" count is auditable. sources_section = "" - if findings: + analyzed_urls_section = "" + url_items = analyzed_urls if analyzed_urls is not None else findings + if findings or url_items: seen_urls = set() source_lines = [] - for f in findings: + analyzed_seen = set() + analyzed_lines = [] + for f in findings or []: url = f.get("url", "") title = f.get("title", "") or url summary = f.get("summary", "") or f.get("evidence", "") if url and url not in seen_urls and not is_low_quality(summary): seen_urls.add(url) source_lines.append(f"- [{title}]({url})") + for item in url_items or []: + url = item.get("url", "") + title = item.get("title", "") or url + if url and url not in analyzed_seen: + analyzed_seen.add(url) + analyzed_lines.append(f"{len(analyzed_lines) + 1}. [{title}]({url})") if source_lines: sources_section = "\n### Sources\n\n" + "\n".join(source_lines) + "\n" + if analyzed_lines: + analyzed_urls_section = "\n### Analyzed URLs\n\n" + "\n".join(analyzed_lines) + "\n" # Build raw findings section (individual extractions per source) raw_findings_section = "" @@ -391,6 +407,7 @@ class ResearchHandler: {full_report} {sources_section} +{analyzed_urls_section} {collected_section} --- diff --git a/src/agent_loop.py b/src/agent_loop.py index 88617ef39..052d92c49 100644 --- a/src/agent_loop.py +++ b/src/agent_loop.py @@ -855,7 +855,7 @@ def _build_system_prompt( _ov_sig = _hl.sha256(_json.dumps(get_builtin_overrides() or {}, sort_keys=True).encode()).hexdigest() except Exception: _ov_sig = "" - cache_key = (frozenset(disabled_tools or []), bool(mcp_mgr), needs_admin, _rt_key, compact, _ov_sig, suppress_local_context) + cache_key = (frozenset(disabled_tools or []), bool(mcp_mgr), needs_admin, _rt_key, compact, _ov_sig, owner, suppress_local_context) if _cached_base_prompt and _cached_base_prompt_key == cache_key and not active_document: agent_prompt = _cached_base_prompt # Skill index is user-editable (name + description), so it must never @@ -863,7 +863,7 @@ def _build_system_prompt( # when the cache hits. _, _skill_index_block = _build_base_prompt( disabled_tools, mcp_mgr, needs_admin, relevant_tools, - mcp_disabled_map=mcp_disabled_map, compact=compact, + mcp_disabled_map=mcp_disabled_map, compact=compact, owner=owner, suppress_local_context=suppress_local_context, ) else: @@ -874,6 +874,7 @@ def _build_system_prompt( relevant_tools, mcp_disabled_map=mcp_disabled_map, compact=compact, + owner=owner, suppress_local_context=suppress_local_context, ) if not active_document: @@ -889,9 +890,20 @@ def _build_system_prompt( # Current date/time for every agent request. This is user-local when the # browser provided timezone headers, with a server-local fallback. + # + # IMPORTANT: this is intentionally NOT prepended into agent_prompt (the + # system message) anymore. Its text changes every minute, and local + # OpenAI-compatible backends (llama.cpp / LM Studio) key their KV-cache + # prefix off the system message byte-for-byte — mixing ever-changing + # timestamp text into the (already large, tool-laden) agent system prompt + # would invalidate the cached prefix on every single request, forcing a + # full prompt re-evaluation each turn (issue #2927). It's built here as a + # standalone *user*-role message and inserted near the end of the array, + # right alongside _doc_message / _skills_message, below. + _datetime_message = None try: - from src.user_time import current_datetime_prompt - agent_prompt = current_datetime_prompt() + agent_prompt + from src.user_time import current_datetime_context_message + _datetime_message = current_datetime_context_message() except Exception: pass @@ -1228,6 +1240,9 @@ def _build_system_prompt( last_user_idx += 1 # the document message is now at last_user_idx if _skills_message: merged.insert(last_user_idx, _skills_message) + last_user_idx += 1 + if _datetime_message: + merged.insert(last_user_idx, _datetime_message) return merged, mcp_schemas @@ -1246,6 +1261,7 @@ def _build_base_prompt( relevant_tools=None, mcp_disabled_map=None, compact: bool = False, + owner: Optional[str] = None, suppress_local_context: bool = False, ): """Build the agent prompt with only relevant tools included. @@ -1299,7 +1315,7 @@ def _build_base_prompt( from src.constants import DATA_DIR _sm = SkillsManager(DATA_DIR) active_tools = list(set(TOOL_SECTIONS.keys()) - set(disabled or [])) - skill_idx = _sm.index_for(owner=None, active_toolsets=active_tools) + skill_idx = _sm.index_for(owner=owner, active_toolsets=active_tools) if skill_idx: lines = ["## Available skills", "Procedures the assistant should consult before doing domain work. " @@ -1707,7 +1723,6 @@ async def stream_agent_loop( owner: Optional[str] = None, relevant_tools: Optional[Set[str]] = None, fallbacks: Optional[List[tuple]] = None, - workspace: Optional[str] = None, plan_mode: bool = False, approved_plan: Optional[str] = None, tool_policy: Optional[ToolPolicy] = None, @@ -1935,27 +1950,6 @@ async def stream_agent_loop( owner=owner, suppress_local_context=guide_only, ) - if workspace and not guide_only: - # PREPEND (not append) so it dominates the large base prompt — appended - # at the end, small models ignored it and asked the user for code. The - # folder IS the project; the agent must explore it, not ask. - _ws_note = ( - f"## ACTIVE WORKSPACE — READ FIRST\n" - f"The user is working in this folder: {workspace}\n" - f"It IS the project. bash/python run with cwd set here and " - f"read_file/write_file are confined to it (paths outside are rejected).\n" - f"When the user says \"the code\" / \"this project\" / \"the workspace\" " - f"or asks to review/find/edit something WITHOUT a path, they mean THIS " - f"folder. Do NOT ask the user for code or a path, and do NOT read a file " - f"literally named \"workspace\". ALWAYS start by exploring it yourself: " - f"run `bash` → `git ls-files` (or `ls -R`) to see the files, then " - f"read_file the relevant ones by path RELATIVE to the workspace." - ) - if messages and messages[0].get("role") == "system": - messages[0]["content"] = _ws_note + "\n\n" + (messages[0].get("content") or "") - else: - messages.insert(0, {"role": "system", "content": _ws_note}) - logger.info("[workspace] active for this turn: %s", workspace) if plan_mode and not guide_only: # Steer the model to investigate-then-propose. Hard tool gating handles # every write path except shell; this directive is what keeps the @@ -2178,6 +2172,7 @@ async def stream_agent_loop( prompt_type=prompt_type if round_num == 1 else None, tools=all_tool_schemas if all_tool_schemas else None, timeout=agent_stream_timeout, + session_id=session_id, ): if time.time() > _round_deadline: logger.warning(f"[agent] round {round_num} stream exceeded wall-clock deadline; cutting off") @@ -2649,7 +2644,6 @@ async def stream_agent_loop( tool_policy=tool_policy, owner=owner, progress_cb=_push_progress, - workspace=workspace, ) finally: # Sentinel so the drainer knows to stop. diff --git a/src/agent_tools.py b/src/agent_tools/__init__.py similarity index 78% rename from src/agent_tools.py rename to src/agent_tools/__init__.py index c7eea4541..4db923a9a 100644 --- a/src/agent_tools.py +++ b/src/agent_tools/__init__.py @@ -18,6 +18,29 @@ from src.tool_utils import _truncate, get_mcp_manager, set_mcp_manager logger = logging.getLogger(__name__) +from .subprocess_tools import BashTool, PythonTool +from .web_tools import WebSearchTool, WebFetchTool +from .filesystem_tools import ReadFileTool, WriteFileTool, EditFileTool, LsTool, GlobTool, GrepTool +from .document_tools import CreateDocumentTool, UpdateDocumentTool, EditDocumentTool, SuggestDocumentTool, ManageDocumentTool + +TOOL_HANDLERS = { + "bash": BashTool().execute, + "python": PythonTool().execute, + "web_search": WebSearchTool().execute, + "web_fetch": WebFetchTool().execute, + "read_file": ReadFileTool().execute, + "write_file": WriteFileTool().execute, + "edit_file": EditFileTool().execute, + "ls": LsTool().execute, + "glob": GlobTool().execute, + "grep": GrepTool().execute, + "create_document": CreateDocumentTool().execute, + "update_document": UpdateDocumentTool().execute, + "edit_document": EditDocumentTool().execute, + "suggest_document": SuggestDocumentTool().execute, + "manage_documents": ManageDocumentTool().execute, +} + # --------------------------------------------------------------------------- # Constants (re-exported for backward compatibility — single source of truth # is src.constants; always prefer importing from there for new code) @@ -92,15 +115,14 @@ from src.tool_execution import ( # noqa: E402, F401 format_tool_result, ) +# Document functions +from .document_tools import ( + set_active_document, + set_active_model +) + # Implementations from src.tool_implementations import ( # noqa: E402, F401 - set_active_document, - set_active_model, - get_active_document, - do_create_document, - do_update_document, - do_edit_document, - do_suggest_document, do_search_chats, do_manage_skills, do_manage_tasks, @@ -108,7 +130,6 @@ from src.tool_implementations import ( # noqa: E402, F401 do_manage_mcp, do_manage_webhooks, do_manage_tokens, - do_manage_documents, do_manage_settings, do_api_call, ) diff --git a/src/agent_tools/document_tools.py b/src/agent_tools/document_tools.py new file mode 100644 index 000000000..33b10c8d3 --- /dev/null +++ b/src/agent_tools/document_tools.py @@ -0,0 +1,644 @@ +from typing import Any, Dict, List, Optional +import logging +import re +import json +from src.constants import MAX_READ_CHARS + +logger = logging.getLogger(__name__) + +# --------------------------------------------------------------------------- +# Active document state +# --------------------------------------------------------------------------- + +_active_document_id: Optional[str] = None +_active_model: Optional[str] = None + + +def set_active_document(doc_id: Optional[str]): + """Set the active document ID for document tool execution.""" + global _active_document_id + _active_document_id = doc_id + + +def set_active_model(model: Optional[str]): + """Set the current model name for version summaries.""" + global _active_model + _active_model = model + + +def get_active_document(): + return _active_document_id + + +def clear_active_document(doc_id: Optional[str] = None) -> bool: + """Clear the in-memory active-document pointer. + + With ``doc_id`` given, only clears when it matches the current pointer, so a + different active document is left untouched. Returns True if it was cleared. + + Called when a document is detached from its session or deleted (its tab is + closed): without this, the stale pointer makes the last-resort doc-injection + path re-surface a closed document in a later, unrelated chat — even one whose + session no longer matches — because an unlinked doc has session_id NULL (#1160). + """ + global _active_document_id + if doc_id is None or _active_document_id == doc_id: + _active_document_id = None + return True + return False + + +def _owned_document_query(query, Document, owner: Optional[str]): + if owner is None: + # A bare Python `False` is not a valid SQL expression — SQLAlchemy 1.4 + # deprecates it and 2.0 raises ArgumentError. Use the SQL `false()` + # literal to return zero rows for an unscoped (owner-less) query. + from sqlalchemy import false + return query.filter(false()) + return query.filter(Document.owner == owner) + + +def _get_owned_document(db, Document, doc_id: str, owner: Optional[str], active_only: bool = False): + q = db.query(Document).filter(Document.id == doc_id) + if active_only: + q = q.filter(Document.is_active == True) + q = _owned_document_query(q, Document, owner) + return q.first() + + +def _most_recent_owned_document(db, Document, owner: Optional[str], active_only: bool = False): + q = db.query(Document) + if active_only: + q = q.filter(Document.is_active == True) + q = _owned_document_query(q, Document, owner) + return q.order_by(Document.updated_at.desc()).first() + + +# --------------------------------------------------------------------------- +# Document tools — create/update/edit/suggest living documents +# --------------------------------------------------------------------------- + +def _sniff_doc_language(text: str) -> str: + """Best-effort detect a document's language from its content when the model + didn't specify one. Defaults to 'markdown' (prose). Recognizes the common + markup/code types the editor supports so e.g. an SVG isn't saved as markdown.""" + import json as _json, re as _re2 + s = (text or "").strip() + if not s: + return "markdown" + head = s[:600] + hl = head.lower() + if _looks_like_email_document(s): + return "email" + # Markup (unambiguous) + if " bool: + import re as _re + title_l = (title or "").strip().lower() + if title_l in {"new email", "new mail", "new message"}: + return True + s = (text or "").lstrip() + if "\n---\n" in s and _re.search(r"(?im)^To:\s*", s) and _re.search(r"(?im)^Subject:\s*", s): + return True + return bool(_re.search(r"(?im)^To:\s*", s) and _re.search(r"(?im)^Subject:\s*", s)) + +def _coerce_email_document_content(existing: str, incoming: str) -> str: + """Keep email docs in the To/Subject/---/body shape even if a model writes + only the body or dumps header labels without the separator.""" + import re as _re + old = existing or "" + new = (incoming or "").strip() + if "\n---\n" in new: + return new + header = old.split("\n---\n", 1)[0] if "\n---\n" in old else "To: \nSubject: " + if _looks_like_email_document(new): + lines = new.splitlines() + last_header_idx = -1 + header_re = _re.compile(r"^(To|Cc|Bcc|Subject|In-Reply-To|References|X-Source-UID|X-Source-Folder|X-Attachments):", _re.I) + for i, line in enumerate(lines): + if header_re.match(line.strip()): + last_header_idx = i + body_lines = lines[last_header_idx + 1:] if last_header_idx >= 0 else lines + while body_lines and not body_lines[0].strip(): + body_lines.pop(0) + body = "\n".join(body_lines).strip() + else: + body = new + return header.rstrip() + "\n---\n" + body + +def _parse_tool_args(content): + """Parse a tool-call argument blob. + + Accepts either a JSON string or an already-decoded dict. Unwraps the + common `{"body": {...}}` envelope that smaller models emit when they + read tool descriptions like "Body is JSON: {...}" literally — they + pass `body` as a field name rather than treating it as a noun. + + Returns a dict on success, raises ValueError on bad JSON. + """ + if isinstance(content, str): + try: + args = json.loads(content) if content.strip() else {} + except (json.JSONDecodeError, TypeError) as e: + raise ValueError(str(e)) + elif isinstance(content, dict): + args = content + else: + args = {} + # Unwrap {"body": {...}} envelope — but only if `body` is the sole key + # and points at a dict. We don't want to clobber a legitimate `body` + # field on tools where it's a real arg (e.g. send_email body text). + if ( + isinstance(args, dict) + and len(args) == 1 + and "body" in args + and isinstance(args["body"], dict) + and "action" in args["body"] # extra safety: only unwrap if the inner dict looks like a tool call + ): + args = args["body"] + return args + +def parse_edit_blocks(content: str) -> list: + """Parse <<>>...<<>>...<<>> blocks.""" + edits = [] + pattern = r'<<>>\n(.*?)\n<<>>\n(.*?)\n<<>>' + for m in re.finditer(pattern, content, re.DOTALL): + edits.append({"find": m.group(1), "replace": m.group(2)}) + return edits + +def parse_suggest_blocks(content: str) -> list: + """Parse <<>>...<<>>...<<>>...<<>> blocks.""" + suggestions = [] + _skip_phrases = ["no change", "clear", "fine as", "looks good", "no improvement", "keep as"] + pattern = r'<<>>\n(.*?)\n<<>>\n(.*?)\n<<>>\n(.*?)\n<<>>' + for m in re.finditer(pattern, content, re.DOTALL): + find_text = m.group(1) + replace_text = m.group(2) + reason = m.group(3).strip() + # Skip no-op suggestions where find == replace or reason says no change + if find_text.strip() == replace_text.strip(): + continue + if any(phrase in reason.lower() for phrase in _skip_phrases): + continue + suggestions.append({ + "id": f"sugg-{len(suggestions)+1}", + "find": find_text, + "replace": replace_text, + "reason": reason, + }) + return suggestions + + +class CreateDocumentTool: + async def execute(self, content: str, ctx: dict) -> dict: + """Create a new document. Supports two formats: + 1) Line-based: line 1 = title, line 2 (optional) = language, rest = content + 2) XML-like tags: ......... + Some models mix them — strip any XML-style tags and fall back to line parsing.""" + import uuid, re as _re + from src.database import SessionLocal, Document, DocumentVersion, Session as DbSession + + raw = content or "" + session_id = ctx.get("session_id") + owner = ctx.get("owner") + + # Known languages the editor understands (match the in HTML) - _KNOWN_LANGS = { - "python", "javascript", "typescript", "html", "css", "markdown", "json", - "yaml", "bash", "sql", "rust", "go", "java", "c", "cpp", "xml", "toml", - "ini", "ruby", "php", "csv", "email", "text", "plain", "svg", - } - - # Try XML tag extraction first - title = None - language = None - content = None - mt = _re.search(r"\s*(.*?)\s*", raw, _re.DOTALL | _re.IGNORECASE) - ml = _re.search(r"\s*(.*?)\s*", raw, _re.DOTALL | _re.IGNORECASE) - mc = _re.search(r"\s*(.*?)\s*", raw, _re.DOTALL | _re.IGNORECASE) - if mt or mc: - title = mt.group(1).strip() if mt else None - language = ml.group(1).strip().lower() if ml else None - content = mc.group(1) if mc else None - - # Fall back to line-based parsing. First strip any stray XML-ish tags. - if title is None or content is None: - cleaned = _re.sub(r"", "", raw) - lines = cleaned.strip().split("\n") - if title is None: - title = lines[0].strip() if lines else "Untitled" - lines = lines[1:] - # Only consume second line as language if it looks like a valid short lang token - if language is None and lines: - candidate = lines[0].strip().lower() - if candidate and len(candidate) < 20 and " " not in candidate and candidate in _KNOWN_LANGS: - language = candidate - lines = lines[1:] - if content is None: - content = "\n".join(lines) - - # Validate language: must be in known set, else default based on content - if language and language not in _KNOWN_LANGS: - language = None - if not language: - # No explicit language — sniff it from the content so an SVG / HTML / JSON - # / code document isn't silently saved as markdown. Prose → markdown. - language = _sniff_doc_language(content) - if _looks_like_email_document(content, title): - language = "email" - - if not title: - title = "Untitled" - - if not session_id: - return {"error": "No session context for document creation"} - - db = SessionLocal() - try: - doc_id = str(uuid.uuid4()) - ver_id = str(uuid.uuid4()) - - # Inherit ownership from the chat session so the doc survives that - # session later being deleted (session_id → NULL). - _sess = db.query(DbSession).filter(DbSession.id == session_id).first() - if owner is not None and (not _sess or _sess.owner != owner): - return {"error": "Cannot create document in another user's session"} - _owner = _sess.owner if _sess else None - - doc = Document( - id=doc_id, - session_id=session_id, - title=title, - language=language, - current_content=content, - version_count=1, - is_active=True, - owner=_owner, - ) - ver = DocumentVersion( - id=ver_id, - document_id=doc_id, - version_number=1, - content=content, - summary=f"Created by {_active_model or 'AI'}", - source="ai", - ) - db.add(doc) - db.add(ver) - db.commit() - - set_active_document(doc_id) - try: - from src.event_bus import fire_event - fire_event("document_created", _owner) - except Exception: - logger.debug("document_created event dispatch failed", exc_info=True) - - return { - "action": "create", - "doc_id": doc_id, - "title": title, - "language": language, - "content": content, - "version": 1, - } - except Exception as e: - db.rollback() - return {"error": f"Failed to create document: {e}"} - finally: - db.close() - - -async def do_update_document(content: str, doc_id: Optional[str] = None, owner: Optional[str] = None) -> Dict: - """Update an existing document. Content = full new document text.""" - import uuid - from src.database import SessionLocal, Document, DocumentVersion - - target_id = doc_id or _active_document_id - - db = SessionLocal() - try: - doc = None - if target_id: - doc = _get_owned_document(db, Document, target_id, owner) - if not doc: - doc = _most_recent_owned_document(db, Document, owner) - if doc: - target_id = doc.id - set_active_document(target_id) - logger.info(f"update_document: fell back to most recent doc id={target_id}") - if not doc: - return {"error": "No documents exist to update"} - - is_email_doc = doc.language == "email" or _looks_like_email_document(doc.current_content or "", doc.title or "") - new_content = _coerce_email_document_content(doc.current_content or "", content) if is_email_doc else content.strip() - if is_email_doc: - doc.language = "email" - - new_ver = doc.version_count + 1 - ver = DocumentVersion( - id=str(uuid.uuid4()), - document_id=target_id, - version_number=new_ver, - content=new_content, - summary=f"Updated by {_active_model or 'AI'}", - source="ai", - ) - doc.current_content = new_content - doc.version_count = new_ver - db.add(ver) - db.commit() - - return { - "action": "update", - "doc_id": target_id, - "title": doc.title, - "language": doc.language, - "content": new_content, - "version": new_ver, - } - except Exception as e: - db.rollback() - return {"error": f"Failed to update document: {e}"} - finally: - db.close() - - -def parse_edit_blocks(content: str) -> list: - """Parse <<>>...<<>>...<<>> blocks.""" - edits = [] - pattern = r'<<>>\n(.*?)\n<<>>\n(.*?)\n<<>>' - for m in re.finditer(pattern, content, re.DOTALL): - edits.append({"find": m.group(1), "replace": m.group(2)}) - return edits - - -async def do_edit_document(content: str, doc_id: Optional[str] = None, owner: Optional[str] = None) -> Dict: - """Apply targeted FIND/REPLACE edits to an existing document.""" - import uuid - from src.database import SessionLocal, Document, DocumentVersion - - target_id = doc_id or _active_document_id - - edits = parse_edit_blocks(content) - if not edits: - return {"error": "No valid <<>>...<<>>...<<>> blocks found"} - - db = SessionLocal() - try: - doc = None - if target_id: - doc = _get_owned_document(db, Document, target_id, owner) - if not doc: - # Fallback: most recently updated document. Avoids "no active doc" errors - # after server restart or when the agent loses track of which doc to edit. - doc = _most_recent_owned_document(db, Document, owner) - if doc: - target_id = doc.id - set_active_document(target_id) - logger.info(f"edit_document: fell back to most recent doc id={target_id} title={doc.title!r}") - if not doc: - return {"error": "No documents exist to edit"} - - updated_content = doc.current_content - applied = 0 - skipped = 0 - for edit in edits: - _find = edit["find"] - if _find in updated_content: - updated_content = updated_content.replace(_find, edit["replace"], 1) - applied += 1 - else: - # Defensive: the active-doc context shows a "N\t" line-number - # gutter for reference. Weaker models sometimes copy that prefix - # into FIND. If the exact match failed, retry with a leading - # "" stripped from each FIND line — but only use it - # when that stripped form actually matches, so we never corrupt a - # legitimately tab-prefixed document. - _stripped = "\n".join(re.sub(r"^\d+\t", "", _l) for _l in _find.split("\n")) - if _stripped != _find and _stripped in updated_content: - updated_content = updated_content.replace(_stripped, edit["replace"], 1) - applied += 1 - logger.info("edit_document: matched after stripping line-number gutter from FIND") - else: - logger.warning(f"edit_document: FIND text not found, skipping: {_find[:80]!r}") - skipped += 1 - - if applied == 0: - return {"error": f"No edits applied — none of the FIND blocks matched the document content (skipped {skipped})"} - - new_ver = doc.version_count + 1 - ver = DocumentVersion( - id=str(uuid.uuid4()), - document_id=target_id, - version_number=new_ver, - content=updated_content, - summary=f"Edited by {_active_model or 'AI'} ({applied} edit(s))", - source="ai", - ) - doc.current_content = updated_content - doc.version_count = new_ver - db.add(ver) - db.commit() - - return { - "action": "edit", - "doc_id": target_id, - "title": doc.title, - "language": doc.language, - "content": updated_content, - "version": new_ver, - "applied": applied, - "skipped": skipped, - } - except Exception as e: - db.rollback() - return {"error": f"Failed to edit document: {e}"} - finally: - db.close() - - -def parse_suggest_blocks(content: str) -> list: - """Parse <<>>...<<>>...<<>>...<<>> blocks.""" - suggestions = [] - _skip_phrases = ["no change", "clear", "fine as", "looks good", "no improvement", "keep as"] - pattern = r'<<>>\n(.*?)\n<<>>\n(.*?)\n<<>>\n(.*?)\n<<>>' - for m in re.finditer(pattern, content, re.DOTALL): - find_text = m.group(1) - replace_text = m.group(2) - reason = m.group(3).strip() - # Skip no-op suggestions where find == replace or reason says no change - if find_text.strip() == replace_text.strip(): - continue - if any(phrase in reason.lower() for phrase in _skip_phrases): - continue - suggestions.append({ - "id": f"sugg-{len(suggestions)+1}", - "find": find_text, - "replace": replace_text, - "reason": reason, - }) - return suggestions - - -async def do_suggest_document(content: str, doc_id: str = None, owner: Optional[str] = None) -> Dict: - """Create inline suggestions for the active document WITHOUT modifying it.""" - from src.database import SessionLocal, Document - - target_id = doc_id or _active_document_id - if not target_id: - return {"error": "No active document to suggest on"} - - suggestions = parse_suggest_blocks(content) - if not suggestions: - return {"error": "No valid <<>>...<<>>...<<>>...<<>> blocks found"} - - db = SessionLocal() - try: - doc = _get_owned_document(db, Document, target_id, owner) - if not doc: - return {"error": f"Document {target_id} not found"} - - # Validate that FIND text exists in document - valid = [] - for s in suggestions: - if s["find"] in doc.current_content: - valid.append(s) - else: - logger.warning(f"suggest_document: FIND text not found, skipping: {s['find'][:80]!r}") - - if not valid: - return {"error": "No suggestions matched the document content"} - - return { - "action": "suggest", - "doc_id": target_id, - "suggestions": valid, - "count": len(valid), - } - finally: - db.close() - - # --------------------------------------------------------------------------- # Search chats # --------------------------------------------------------------------------- @@ -1361,129 +881,6 @@ async def do_manage_tokens(content: str, owner: Optional[str] = None) -> Dict: finally: db.close() - -# --------------------------------------------------------------------------- -# Document management tool (delete, list, organize) -# --------------------------------------------------------------------------- - -async def do_manage_documents(content: str, owner: Optional[str] = None) -> Dict: - """Manage documents: list, read/view/open, delete, tidy. - - Output format mirrors `manage_session`: list rows include a - clickable `[Title](#document-)` anchor + relative timestamps - so the user can click straight from chat to open the editor. - """ - from core.database import SessionLocal, Document - from datetime import datetime, timezone - - try: - args = _parse_tool_args(content) - except ValueError: - return {"error": "Invalid JSON arguments", "exit_code": 1} - - action = args.get("action", "list") - db = SessionLocal() - - def _rel(ts): - if not ts: - return 'never' - try: - now = datetime.now(timezone.utc) if ts.tzinfo is not None else datetime.utcnow() - diff = (now - ts).total_seconds() - except Exception: - return 'unknown' - if diff < 60: return 'just now' - if diff < 3600: return f'{int(diff / 60)}m ago' - if diff < 86400: return f'{int(diff / 3600)}h ago' - if diff < 86400 * 7: return f'{int(diff / 86400)}d ago' - return ts.strftime('%Y-%m-%d') - - try: - if action == "list": - q = db.query(Document).filter(Document.is_active == True) - q = _owned_document_query(q, Document, owner) - if args.get("search"): - q = q.filter(Document.title.ilike(f"%{args['search']}%")) - if args.get("language"): - q = q.filter(Document.language == args["language"]) - docs = q.order_by(Document.updated_at.desc()).limit(args.get("limit", 50)).all() - if not docs: - msg = "No documents found" + (f" matching '{args['search']}'" if args.get("search") else "") + "." - return {"response": msg, "documents": [], "exit_code": 0} - lines = [] - items = [] - for i, d in enumerate(docs): - size = len(d.current_content or "") - lang = d.language or "text" - ts = getattr(d, 'updated_at', None) or getattr(d, 'created_at', None) - marker = " ← most recent" if i == 0 else "" - lines.append( - f"- [{d.title}](#document-{d.id}) — {lang}, {size} chars, updated {_rel(ts)}{marker}" - ) - items.append({"id": d.id, "title": d.title, "language": lang, "size": size}) - header = f"Found {len(docs)} document(s), sorted most-recent first. Click a title to open:" - return { - "response": header + "\n" + "\n".join(lines), - "documents": items, - "exit_code": 0, - } - - elif action in ("read", "view", "open", "get"): - doc_id = args.get("document_id") or args.get("id") or args.get("uid") - if not doc_id: - return {"error": "Need document_id (use action=list to find one)", "exit_code": 1} - doc = _get_owned_document(db, Document, doc_id, owner, active_only=True) - if not doc: - return {"error": f"Document '{doc_id}' not found", "exit_code": 1} - body = doc.current_content or "" - preview_limit = int(args.get("limit", MAX_READ_CHARS)) - truncated = len(body) > preview_limit - preview = body[:preview_limit] + (f"\n... (truncated, {len(body)} chars total)" if truncated else "") - anchor = f"[{doc.title}](#document-{doc.id})" - return { - "response": f"{anchor} — click to open in editor.\n\n```{doc.language or ''}\n{preview}\n```", - "document": { - "id": doc.id, - "title": doc.title, - "language": doc.language, - "size": len(body), - "content": preview, - "truncated": truncated, - }, - "exit_code": 0, - } - - elif action == "delete": - doc_id = args.get("document_id") or args.get("id") or args.get("uid") or _active_document_id - doc = None - if doc_id: - doc = _get_owned_document(db, Document, doc_id, owner) - if not doc: - # Fallback: most recently updated doc (likely what the user means) - doc = _most_recent_owned_document(db, Document, owner, active_only=True) - if not doc: - return {"error": "No document to delete", "exit_code": 1} - title = doc.title - doc.is_active = False - db.commit() - if _active_document_id == doc.id: - set_active_document(None) - return {"response": f"Deleted document '{title}'", "exit_code": 0} - - elif action == "tidy": - from src.document_actions import run_document_tidy - result = await run_document_tidy(owner or "") - return {"response": result, "exit_code": 0} - - else: - return {"error": f"Unknown action: {action}", "exit_code": 1} - except Exception as e: - logger.error(f"manage_documents error: {e}") - return {"error": str(e), "exit_code": 1} - finally: - db.close() - - # --------------------------------------------------------------------------- # Settings/preferences management tool # --------------------------------------------------------------------------- @@ -2684,7 +2081,7 @@ async def _ensure_served_endpoint( try: async with httpx.AsyncClient(timeout=30) as client: resp = await client.post( - f"{_COOKBOOK_BASE}/api/model-endpoints", + f"{_INTERNAL_BASE}/api/model-endpoints", data=payload, headers=_internal_headers(), ) diff --git a/src/user_time.py b/src/user_time.py index 44519c0fb..d3dee5eb7 100644 --- a/src/user_time.py +++ b/src/user_time.py @@ -9,7 +9,7 @@ from __future__ import annotations import re from contextvars import ContextVar from datetime import datetime, timedelta, timezone -from typing import Optional +from typing import Dict, Optional _USER_TZ_OFFSET_MIN: ContextVar[Optional[int]] = ContextVar("user_tz_offset_min", default=None) @@ -136,3 +136,26 @@ def current_datetime_prompt(now_utc: Optional[datetime] = None) -> str: "When scheduling a task with manage_tasks, scheduled_time is in UTC: " "convert the user's stated local time using the UTC offset above.\n\n" ) + + +def current_datetime_context_message(now_utc: Optional[datetime] = None) -> Dict[str, str]: + """Build the current-date/time context as a standalone chat message. + + This intentionally returns a ``user``-role message rather than a + ``system``-role one. The text changes every turn (it embeds the current + clock time down to the minute), and local OpenAI-compatible backends + (llama.cpp / LM Studio) key their KV-cache prefix off the system message + byte-for-byte — folding ever-changing timestamp text into the system + message would invalidate the cached prefix on every single request (see + issue #2927). Keeping it as a separate message placed near the end of the + array (right before the latest user turn) lets the static system prompt + stay byte-identical across turns while the model still gets fresh + date/time grounding for relative-date reasoning. + """ + return { + "role": "user", + "content": ( + "[Context — current date/time, refreshed each turn; not part of " + "your instructions]\n" + current_datetime_prompt(now_utc) + ), + } diff --git a/start-macos.sh b/start-macos.sh index b9f06f2bf..f324625c6 100755 --- a/start-macos.sh +++ b/start-macos.sh @@ -182,6 +182,35 @@ else echo "▶ Non-ARM macOS detected; skipping Apfel server bootstrap." fi +# ChromaDB backs the tool index and vector RAG. chromadb ships in the venv, so +# start a local server before launching. Skip when one is already reachable, or +# when CHROMADB_HOST points at a remote host. +CHROMA_PID="" +CHROMA_HOST="${CHROMADB_HOST:-localhost}" # what the app connects to +CHROMA_PORT="${CHROMADB_PORT:-8100}" +# Bind + probe on IPv4 loopback: the app's "localhost" resolves to 127.0.0.1, +# but binding chroma to the literal "localhost" can land on IPv6 ::1, which the +# app can't then reach. Pin both to 127.0.0.1. +CHROMA_BIN="$(dirname "$VENV_PY")/chroma" +case "$CHROMA_HOST" in + localhost|127.0.0.1) CHROMA_BIND="127.0.0.1" ;; + 0.0.0.0) CHROMA_BIND="0.0.0.0" ;; + *) CHROMA_BIND="" ;; # remote host - don't start locally +esac +if (exec 3<>"/dev/tcp/127.0.0.1/$CHROMA_PORT") 2>/dev/null; then + echo "▶ ChromaDB already running on 127.0.0.1:$CHROMA_PORT - using it." +elif [ -z "$CHROMA_BIND" ]; then + echo "▶ CHROMADB_HOST=$CHROMA_HOST is remote - not starting a local ChromaDB." +elif [ -x "$CHROMA_BIN" ]; then + CHROMA_LOG="${TMPDIR:-/tmp}/odysseus-chromadb.log" + echo "▶ Starting ChromaDB in the background on $CHROMA_BIND:$CHROMA_PORT…" + echo " logging to $CHROMA_LOG" + nohup "$CHROMA_BIN" run --host "$CHROMA_BIND" --port "$CHROMA_PORT" --path "$PWD/data/chroma" >"$CHROMA_LOG" 2>&1 & + CHROMA_PID=$! +else + echo "▶ ChromaDB CLI not found in venv; skipping (tool index will be degraded)." +fi + # 5. Launch. Bind to loopback by default; opt into LAN/Tailscale with # ODYSSEUS_HOST=0.0.0.0. URL_HOST="$HOST" @@ -224,7 +253,7 @@ fi # Setup is done — drop the setup-failure handler, and clean up the background # opener when the server exits or the user presses Ctrl+C. trap - ERR -trap '[ -n "$POLLER_PID" ] && kill "$POLLER_PID" 2>/dev/null; [ -n "$APFEL_PID" ] && kill "$APFEL_PID" 2>/dev/null' EXIT INT TERM +trap '[ -n "$POLLER_PID" ] && kill "$POLLER_PID" 2>/dev/null; [ -n "$APFEL_PID" ] && kill "$APFEL_PID" 2>/dev/null; [ -n "$CHROMA_PID" ] && kill "$CHROMA_PID" 2>/dev/null' EXIT INT TERM echo echo "▶ Starting Odysseus — it will open in your browser at $URL" diff --git a/static/index.html b/static/index.html index 4ca33c072..60a2764d9 100644 --- a/static/index.html +++ b/static/index.html @@ -2095,6 +2095,7 @@ +