mirror of
https://github.com/pewdiepie-archdaemon/odysseus.git
synced 2026-06-17 18:25:26 -04:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4371425514 | |||
| fbed9027b0 | |||
| d9141c6e56 | |||
| 8ae2b5f58c | |||
| 637a34515d | |||
| f605bb3864 |
@@ -1,235 +1,21 @@
|
|||||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
MIT License
|
||||||
Version 3, 19 November 2007
|
|
||||||
|
Copyright (c) 2025 Odysseus Contributors
|
||||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
Preamble
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
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.
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
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.
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
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.
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
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.
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
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.
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
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.
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
|
||||||
|
|
||||||
The precise terms and conditions for copying, distribution and modification follow.
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
0. Definitions.
|
|
||||||
|
|
||||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
|
||||||
|
|
||||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
|
||||||
|
|
||||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
|
||||||
|
|
||||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
|
||||||
|
|
||||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
|
||||||
|
|
||||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
|
||||||
|
|
||||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
|
||||||
|
|
||||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
|
||||||
|
|
||||||
1. Source Code.
|
|
||||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
|
||||||
|
|
||||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
|
||||||
|
|
||||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
|
||||||
|
|
||||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
|
||||||
subprograms and other parts of the work.
|
|
||||||
|
|
||||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
|
||||||
|
|
||||||
The Corresponding Source for a work in source code form is that same work.
|
|
||||||
|
|
||||||
2. Basic Permissions.
|
|
||||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
|
||||||
|
|
||||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
|
||||||
|
|
||||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
|
||||||
|
|
||||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
|
||||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
|
||||||
|
|
||||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
|
||||||
|
|
||||||
4. Conveying Verbatim Copies.
|
|
||||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
|
||||||
|
|
||||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
|
||||||
|
|
||||||
5. Conveying Modified Source Versions.
|
|
||||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
|
||||||
|
|
||||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
|
||||||
|
|
||||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
|
||||||
|
|
||||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
|
||||||
|
|
||||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
|
||||||
|
|
||||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
|
||||||
|
|
||||||
6. Conveying Non-Source Forms.
|
|
||||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
|
||||||
|
|
||||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
|
||||||
|
|
||||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
|
||||||
|
|
||||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
|
||||||
|
|
||||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
|
||||||
|
|
||||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
|
||||||
|
|
||||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
|
||||||
|
|
||||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
|
||||||
|
|
||||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
|
||||||
|
|
||||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
|
||||||
|
|
||||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
|
||||||
|
|
||||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
|
||||||
|
|
||||||
7. Additional Terms.
|
|
||||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
|
||||||
|
|
||||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
|
||||||
|
|
||||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
|
||||||
|
|
||||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
|
||||||
|
|
||||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
|
||||||
|
|
||||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
|
||||||
|
|
||||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
|
||||||
|
|
||||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
|
||||||
|
|
||||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
|
||||||
|
|
||||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
|
||||||
|
|
||||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
|
||||||
|
|
||||||
8. Termination.
|
|
||||||
|
|
||||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
|
||||||
|
|
||||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
|
||||||
|
|
||||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
|
||||||
|
|
||||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
|
||||||
|
|
||||||
9. Acceptance Not Required for Having Copies.
|
|
||||||
|
|
||||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
|
||||||
|
|
||||||
10. Automatic Licensing of Downstream Recipients.
|
|
||||||
|
|
||||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
|
||||||
|
|
||||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
|
||||||
|
|
||||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
|
||||||
|
|
||||||
11. Patents.
|
|
||||||
|
|
||||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
|
||||||
|
|
||||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
|
||||||
|
|
||||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
|
||||||
|
|
||||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
|
||||||
|
|
||||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
|
||||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
|
||||||
|
|
||||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
|
||||||
|
|
||||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
|
||||||
|
|
||||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
|
||||||
|
|
||||||
12. No Surrender of Others' Freedom.
|
|
||||||
|
|
||||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
|
||||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
|
||||||
|
|
||||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
|
||||||
|
|
||||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
|
||||||
|
|
||||||
14. Revised Versions of this License.
|
|
||||||
|
|
||||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
|
||||||
|
|
||||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
|
||||||
|
|
||||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
|
||||||
|
|
||||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
|
||||||
|
|
||||||
15. Disclaimer of Warranty.
|
|
||||||
|
|
||||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
|
||||||
|
|
||||||
16. Limitation of Liability.
|
|
||||||
|
|
||||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
|
||||||
|
|
||||||
17. Interpretation of Sections 15 and 16.
|
|
||||||
|
|
||||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
How to Apply These Terms to Your New Programs
|
|
||||||
|
|
||||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
|
||||||
|
|
||||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
|
||||||
|
|
||||||
<one line to give the program's name and a brief idea of what it does.>
|
|
||||||
Copyright (C) <year> <name of author>
|
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
|
||||||
|
|
||||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
|
||||||
|
|
||||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
Also add information on how to contact you by electronic and paper mail.
|
|
||||||
|
|
||||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
|
||||||
|
|
||||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
|
||||||
|
|||||||
@@ -451,7 +451,7 @@ All user data lives in `data/` (gitignored): `app.db` (sessions, messages, docum
|
|||||||
</a>
|
</a>
|
||||||
|
|
||||||
## License
|
## License
|
||||||
AGPL-3.0-or-later -- see [LICENSE](LICENSE) and [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md).
|
MIT -- see [LICENSE](LICENSE) and [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md).
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
|
|
||||||
|
|||||||
@@ -102,7 +102,6 @@ python3 ~/.claude/skills/odysseus/scripts/odysseus_api.py POST /api/codex/memory
|
|||||||
|
|
||||||
## Email draft + send
|
## Email draft + send
|
||||||
|
|
||||||
- Prefer `POST /api/codex/emails/draft-document` for agent-written email replies. It creates an editable Odysseus Document with `language: "email"` and does not touch IMAP/send.
|
|
||||||
- `POST /api/codex/emails/draft` — body matches `SendEmailRequest` (`to`, `cc`, `bcc`, `subject`, `body`, `body_html`, `attachments`, `account_id`, `in_reply_to`, `references`). Requires `email:draft` (or `email:send`).
|
- `POST /api/codex/emails/draft` — body matches `SendEmailRequest` (`to`, `cc`, `bcc`, `subject`, `body`, `body_html`, `attachments`, `account_id`, `in_reply_to`, `references`). Requires `email:draft` (or `email:send`).
|
||||||
- `POST /api/codex/emails/send` — same body. Requires `email:send`. Never send without explicit user instruction.
|
- `POST /api/codex/emails/send` — same body. Requires `email:send`. Never send without explicit user instruction.
|
||||||
|
|
||||||
|
|||||||
@@ -17,11 +17,6 @@ def _usage() -> int:
|
|||||||
print(" odysseus_api.py todos add TITLE", file=sys.stderr)
|
print(" odysseus_api.py todos add TITLE", file=sys.stderr)
|
||||||
print(" odysseus_api.py emails list [limit]", file=sys.stderr)
|
print(" odysseus_api.py emails list [limit]", file=sys.stderr)
|
||||||
print(" odysseus_api.py emails read UID", file=sys.stderr)
|
print(" odysseus_api.py emails read UID", file=sys.stderr)
|
||||||
print(" odysseus_api.py emails draft-doc JSON_PAYLOAD", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py documents list [limit]", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py documents read DOC_ID", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py documents create JSON_PAYLOAD", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py documents delete DOC_ID", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py cookbook tasks", file=sys.stderr)
|
print(" odysseus_api.py cookbook tasks", file=sys.stderr)
|
||||||
print(" odysseus_api.py cookbook servers", file=sys.stderr)
|
print(" odysseus_api.py cookbook servers", file=sys.stderr)
|
||||||
print(" odysseus_api.py cookbook cached [HOST]", file=sys.stderr)
|
print(" odysseus_api.py cookbook cached [HOST]", file=sys.stderr)
|
||||||
@@ -84,33 +79,6 @@ def main() -> int:
|
|||||||
method = "GET"
|
method = "GET"
|
||||||
path = f"/api/codex/emails/{sys.argv[3]}"
|
path = f"/api/codex/emails/{sys.argv[3]}"
|
||||||
body = None
|
body = None
|
||||||
elif action in ("draft-doc", "draft_document") and len(sys.argv) >= 4:
|
|
||||||
method = "POST"
|
|
||||||
path = "/api/codex/emails/draft-document"
|
|
||||||
body = " ".join(sys.argv[3:])
|
|
||||||
else:
|
|
||||||
return _usage()
|
|
||||||
elif command in ("documents", "docs"):
|
|
||||||
if len(sys.argv) < 3:
|
|
||||||
return _usage()
|
|
||||||
action = sys.argv[2].lower()
|
|
||||||
if action == "list":
|
|
||||||
method = "GET"
|
|
||||||
limit = sys.argv[3] if len(sys.argv) >= 4 else "50"
|
|
||||||
path = f"/api/codex/documents?limit={limit}"
|
|
||||||
body = None
|
|
||||||
elif action == "read" and len(sys.argv) >= 4:
|
|
||||||
method = "GET"
|
|
||||||
path = f"/api/codex/documents/{sys.argv[3]}"
|
|
||||||
body = None
|
|
||||||
elif action == "create" and len(sys.argv) >= 4:
|
|
||||||
method = "POST"
|
|
||||||
path = "/api/codex/documents"
|
|
||||||
body = " ".join(sys.argv[3:])
|
|
||||||
elif action == "delete" and len(sys.argv) >= 4:
|
|
||||||
method = "DELETE"
|
|
||||||
path = f"/api/codex/documents/{sys.argv[3]}"
|
|
||||||
body = None
|
|
||||||
else:
|
else:
|
||||||
return _usage()
|
return _usage()
|
||||||
elif command == "cookbook":
|
elif command == "cookbook":
|
||||||
|
|||||||
@@ -17,11 +17,6 @@ def _usage() -> int:
|
|||||||
print(" odysseus_api.py todos add TITLE", file=sys.stderr)
|
print(" odysseus_api.py todos add TITLE", file=sys.stderr)
|
||||||
print(" odysseus_api.py emails list [limit]", file=sys.stderr)
|
print(" odysseus_api.py emails list [limit]", file=sys.stderr)
|
||||||
print(" odysseus_api.py emails read UID", file=sys.stderr)
|
print(" odysseus_api.py emails read UID", file=sys.stderr)
|
||||||
print(" odysseus_api.py emails draft-doc JSON_PAYLOAD", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py documents list [limit]", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py documents read DOC_ID", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py documents create JSON_PAYLOAD", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py documents delete DOC_ID", file=sys.stderr)
|
|
||||||
print(" odysseus_api.py cookbook tasks", file=sys.stderr)
|
print(" odysseus_api.py cookbook tasks", file=sys.stderr)
|
||||||
print(" odysseus_api.py cookbook servers", file=sys.stderr)
|
print(" odysseus_api.py cookbook servers", file=sys.stderr)
|
||||||
print(" odysseus_api.py cookbook cached [HOST]", file=sys.stderr)
|
print(" odysseus_api.py cookbook cached [HOST]", file=sys.stderr)
|
||||||
@@ -84,33 +79,6 @@ def main() -> int:
|
|||||||
method = "GET"
|
method = "GET"
|
||||||
path = f"/api/codex/emails/{sys.argv[3]}"
|
path = f"/api/codex/emails/{sys.argv[3]}"
|
||||||
body = None
|
body = None
|
||||||
elif action in ("draft-doc", "draft_document") and len(sys.argv) >= 4:
|
|
||||||
method = "POST"
|
|
||||||
path = "/api/codex/emails/draft-document"
|
|
||||||
body = " ".join(sys.argv[3:])
|
|
||||||
else:
|
|
||||||
return _usage()
|
|
||||||
elif command in ("documents", "docs"):
|
|
||||||
if len(sys.argv) < 3:
|
|
||||||
return _usage()
|
|
||||||
action = sys.argv[2].lower()
|
|
||||||
if action == "list":
|
|
||||||
method = "GET"
|
|
||||||
limit = sys.argv[3] if len(sys.argv) >= 4 else "50"
|
|
||||||
path = f"/api/codex/documents?limit={limit}"
|
|
||||||
body = None
|
|
||||||
elif action == "read" and len(sys.argv) >= 4:
|
|
||||||
method = "GET"
|
|
||||||
path = f"/api/codex/documents/{sys.argv[3]}"
|
|
||||||
body = None
|
|
||||||
elif action == "create" and len(sys.argv) >= 4:
|
|
||||||
method = "POST"
|
|
||||||
path = "/api/codex/documents"
|
|
||||||
body = " ".join(sys.argv[3:])
|
|
||||||
elif action == "delete" and len(sys.argv) >= 4:
|
|
||||||
method = "DELETE"
|
|
||||||
path = f"/api/codex/documents/{sys.argv[3]}"
|
|
||||||
body = None
|
|
||||||
else:
|
else:
|
||||||
return _usage()
|
return _usage()
|
||||||
elif command == "cookbook":
|
elif command == "cookbook":
|
||||||
|
|||||||
@@ -102,7 +102,6 @@ python3 integrations/codex/scripts/odysseus_api.py POST /api/codex/memory '{"tex
|
|||||||
|
|
||||||
## Email draft + send
|
## Email draft + send
|
||||||
|
|
||||||
- Prefer `POST /api/codex/emails/draft-document` for Codex-written email replies. It creates an editable Odysseus Document with `language: "email"` and does not touch IMAP/send.
|
|
||||||
- `POST /api/codex/emails/draft` — body matches `SendEmailRequest` (`to`, `cc`, `bcc`, `subject`, `body`, `body_html`, `attachments`, `account_id`, `in_reply_to`, `references`). Requires `email:draft` (or `email:send`).
|
- `POST /api/codex/emails/draft` — body matches `SendEmailRequest` (`to`, `cc`, `bcc`, `subject`, `body`, `body_html`, `attachments`, `account_id`, `in_reply_to`, `references`). Requires `email:draft` (or `email:send`).
|
||||||
- `POST /api/codex/emails/send` — same body. Requires `email:send`. Never send without explicit user instruction.
|
- `POST /api/codex/emails/send` — same body. Requires `email:send`. Never send without explicit user instruction.
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,6 @@ ALLOWED_SCOPES = {
|
|||||||
TOKEN_PROFILES = {
|
TOKEN_PROFILES = {
|
||||||
"chat": ["chat"],
|
"chat": ["chat"],
|
||||||
"codex_todos": ["todos:read", "todos:write"],
|
"codex_todos": ["todos:read", "todos:write"],
|
||||||
"codex_documents": ["documents:read", "documents:write"],
|
|
||||||
"codex_email_drafts": ["email:read", "email:draft", "documents:read", "documents:write"],
|
"codex_email_drafts": ["email:read", "email:draft", "documents:read", "documents:write"],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -101,11 +101,17 @@ def setup_backup_routes(memory_manager, preset_manager, skills_manager) -> APIRo
|
|||||||
# ── Skills ──
|
# ── Skills ──
|
||||||
if "skills" in body and isinstance(body["skills"], list):
|
if "skills" in body and isinstance(body["skills"], list):
|
||||||
existing = skills_manager.load_all()
|
existing = skills_manager.load_all()
|
||||||
existing_names = {s.get("name") for s in existing if s.get("name")}
|
# Dedup against THIS user's own skills only. Using every tenant's
|
||||||
existing_ids = {s.get("id") for s in existing if s.get("id")}
|
# 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 = {
|
existing_titles = {
|
||||||
(s.get("title") or s.get("description") or "").strip().lower()
|
(s.get("title") or s.get("description") or "").strip().lower()
|
||||||
for s in existing
|
for s in own
|
||||||
}
|
}
|
||||||
added = 0
|
added = 0
|
||||||
for skill in body["skills"]:
|
for skill in body["skills"]:
|
||||||
|
|||||||
@@ -456,7 +456,6 @@ def setup_chat_routes(
|
|||||||
# manual form posts that still send plan_mode=true.
|
# manual form posts that still send plan_mode=true.
|
||||||
plan_mode = False
|
plan_mode = False
|
||||||
chat_mode = str(form_data.get("mode", "")).lower() # 'chat' or 'agent'
|
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.
|
# Plan mode is a modifier on agent mode — it only makes sense with tools.
|
||||||
if plan_mode:
|
if plan_mode:
|
||||||
chat_mode = "agent"
|
chat_mode = "agent"
|
||||||
@@ -1135,7 +1134,6 @@ def setup_chat_routes(
|
|||||||
tool_policy=tool_policy,
|
tool_policy=tool_policy,
|
||||||
owner=_user,
|
owner=_user,
|
||||||
fallbacks=_fallback_candidates,
|
fallbacks=_fallback_candidates,
|
||||||
workspace=None,
|
|
||||||
plan_mode=plan_mode,
|
plan_mode=plan_mode,
|
||||||
approved_plan=approved_plan or None,
|
approved_plan=approved_plan or None,
|
||||||
):
|
):
|
||||||
|
|||||||
+1
-65
@@ -75,20 +75,6 @@ def _scope_owner(request: Request, allowed: set[str]) -> str:
|
|||||||
return require_user(request)
|
return require_user(request)
|
||||||
|
|
||||||
|
|
||||||
def _scope_owner_all(request: Request, required: set[str]) -> str:
|
|
||||||
"""Return owner only when an API token has every required scope."""
|
|
||||||
if getattr(request.state, "api_token", False):
|
|
||||||
scopes = set(getattr(request.state, "api_token_scopes", []) or [])
|
|
||||||
missing = required - scopes
|
|
||||||
if missing:
|
|
||||||
raise HTTPException(403, f"API token missing required scope: {' and '.join(sorted(missing))}")
|
|
||||||
owner = getattr(request.state, "api_token_owner", None)
|
|
||||||
if not owner:
|
|
||||||
raise HTTPException(403, "API token has no owner")
|
|
||||||
return owner
|
|
||||||
return require_user(request)
|
|
||||||
|
|
||||||
|
|
||||||
def _find_endpoint(router: APIRouter | None, method: str, path: str):
|
def _find_endpoint(router: APIRouter | None, method: str, path: str):
|
||||||
if router is None:
|
if router is None:
|
||||||
return None
|
return None
|
||||||
@@ -136,7 +122,7 @@ def setup_codex_routes(
|
|||||||
"read": scoped(EMAIL_READ_SCOPES),
|
"read": scoped(EMAIL_READ_SCOPES),
|
||||||
"draft": scoped(EMAIL_DRAFT_SCOPES),
|
"draft": scoped(EMAIL_DRAFT_SCOPES),
|
||||||
"send": scoped(EMAIL_SEND_SCOPES),
|
"send": scoped(EMAIL_SEND_SCOPES),
|
||||||
"actions": ["list", "read", "draft_document", "draft", "send"],
|
"actions": ["list", "read", "draft", "send"],
|
||||||
},
|
},
|
||||||
"memory": {
|
"memory": {
|
||||||
"read": scoped(MEMORY_READ_SCOPES),
|
"read": scoped(MEMORY_READ_SCOPES),
|
||||||
@@ -260,56 +246,6 @@ def setup_codex_routes(
|
|||||||
# Both handlers in routes/email_routes.py already accept `owner=` via
|
# Both handlers in routes/email_routes.py already accept `owner=` via
|
||||||
# FastAPI Depends, so we call them directly without patching state.
|
# FastAPI Depends, so we call them directly without patching state.
|
||||||
|
|
||||||
def _email_draft_document_content(body: dict[str, Any]) -> str:
|
|
||||||
def clean(v: Any) -> str:
|
|
||||||
if isinstance(v, list):
|
|
||||||
return ", ".join(str(x).strip() for x in v if str(x).strip())
|
|
||||||
return str(v or "").strip()
|
|
||||||
|
|
||||||
to = clean(body.get("to"))
|
|
||||||
cc = clean(body.get("cc"))
|
|
||||||
bcc = clean(body.get("bcc"))
|
|
||||||
subject = clean(body.get("subject"))
|
|
||||||
in_reply_to = clean(body.get("in_reply_to"))
|
|
||||||
references = clean(body.get("references"))
|
|
||||||
body_text = str(body.get("body") or body.get("body_html") or "").strip()
|
|
||||||
lines = [
|
|
||||||
f"To: {to}",
|
|
||||||
]
|
|
||||||
if cc:
|
|
||||||
lines.append(f"Cc: {cc}")
|
|
||||||
if bcc:
|
|
||||||
lines.append(f"Bcc: {bcc}")
|
|
||||||
lines.append(f"Subject: {subject}")
|
|
||||||
if in_reply_to:
|
|
||||||
lines.append(f"In-Reply-To: {in_reply_to}")
|
|
||||||
if references:
|
|
||||||
lines.append(f"References: {references}")
|
|
||||||
lines.extend(["---", body_text])
|
|
||||||
return "\n".join(lines).rstrip() + "\n"
|
|
||||||
|
|
||||||
@router.post("/emails/draft-document")
|
|
||||||
async def codex_email_draft_document(request: Request, body: dict[str, Any] = Body(default_factory=dict)):
|
|
||||||
owner = _scope_owner_all(request, {"email:draft", "documents:write"})
|
|
||||||
if documents_create_endpoint is None:
|
|
||||||
raise HTTPException(503, "Documents integration is not available")
|
|
||||||
from routes.document_routes import DocumentCreate
|
|
||||||
|
|
||||||
subject = str(body.get("subject") or "Email draft").strip() or "Email draft"
|
|
||||||
title = str(body.get("title") or subject).strip() or "Email draft"
|
|
||||||
req = DocumentCreate(
|
|
||||||
session_id=body.get("session_id"),
|
|
||||||
title=title,
|
|
||||||
language="email",
|
|
||||||
content=_email_draft_document_content(body),
|
|
||||||
)
|
|
||||||
result = await _as_owner(request, owner, documents_create_endpoint, request, req)
|
|
||||||
if isinstance(result, dict):
|
|
||||||
result = dict(result)
|
|
||||||
result["draft_type"] = "document"
|
|
||||||
result["send_required_confirmation"] = True
|
|
||||||
return result
|
|
||||||
|
|
||||||
@router.post("/emails/draft")
|
@router.post("/emails/draft")
|
||||||
async def codex_email_draft(request: Request, body: dict[str, Any] = Body(default_factory=dict)):
|
async def codex_email_draft(request: Request, body: dict[str, Any] = Body(default_factory=dict)):
|
||||||
owner = _scope_owner(request, EMAIL_DRAFT_SCOPES)
|
owner = _scope_owner(request, EMAIL_DRAFT_SCOPES)
|
||||||
|
|||||||
@@ -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}$")
|
_SSH_PORT_RE = re.compile(r"^\d{1,5}$")
|
||||||
_GPU_LIST_RE = re.compile(r"^\d+(?:,\d+)*$")
|
_GPU_LIST_RE = re.compile(r"^\d+(?:,\d+)*$")
|
||||||
# A download target directory. Absolute or ~-relative path; safe path glyphs
|
# A download target directory. Absolute or ~-relative path; safe path glyphs
|
||||||
# only (no quotes, shell metacharacters, or spaces) since it lands in a shell
|
# only (no quotes or shell metacharacters). Spaces are allowed because command
|
||||||
# command. A leading ~ is expanded to $HOME at command-build time.
|
# builders pass the value through quoted shell/Python contexts. The character
|
||||||
_LOCAL_DIR_RE = re.compile(r"^~?/[A-Za-z0-9._/-]*$|^~$")
|
# 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]:[\\/]")
|
_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:
|
def _validate_local_dir(v: str | None) -> str | None:
|
||||||
if v is None or v == "":
|
if v is None or v == "":
|
||||||
return None
|
return None
|
||||||
|
if len(v) >= 2 and v[0] == v[-1] and v[0] in {"'", '"'}:
|
||||||
|
v = v[1:-1]
|
||||||
v = v.rstrip("/") or "/"
|
v = v.rstrip("/") or "/"
|
||||||
if not _LOCAL_DIR_RE.match(v):
|
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 spaces or shell metacharacters")
|
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
|
return v
|
||||||
|
|
||||||
|
|
||||||
@@ -125,7 +142,7 @@ def _validate_gpus(v: str | None) -> str | None:
|
|||||||
def _shell_path(p: str) -> str:
|
def _shell_path(p: str) -> str:
|
||||||
"""Render a validated path for a double-quoted shell context, expanding a
|
"""Render a validated path for a double-quoted shell context, expanding a
|
||||||
leading ~ to $HOME (single quotes wouldn't expand it). Safe because
|
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 == "~":
|
if p == "~":
|
||||||
return '"$HOME"'
|
return '"$HOME"'
|
||||||
if p.startswith("~/"):
|
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 root, dirs, fns in safe_walk(base):",
|
||||||
" for fn in sorted(fns):",
|
" for fn in sorted(fns):",
|
||||||
" if not fn.lower().endswith('.gguf'): continue",
|
" if not fn.lower().endswith('.gguf'): continue",
|
||||||
|
" if fn.startswith('._'): continue # macOS AppleDouble sidecar, not a real GGUF",
|
||||||
" fp = os.path.join(root, fn)",
|
" fp = os.path.join(root, fn)",
|
||||||
" try: size = os.path.getsize(fp)",
|
" try: size = os.path.getsize(fp)",
|
||||||
" except Exception: size = 0",
|
" except Exception: size = 0",
|
||||||
|
|||||||
@@ -134,9 +134,10 @@ _NEWS_HINTS = ("news", "nyheter", "headlines", "breaking", "latest", "today", "i
|
|||||||
_GENERAL_ENGINES = os.environ.get("SEARXNG_GENERAL_ENGINES", "bing,mojeek,presearch")
|
_GENERAL_ENGINES = os.environ.get("SEARXNG_GENERAL_ENGINES", "bing,mojeek,presearch")
|
||||||
|
|
||||||
|
|
||||||
def searxng_search_api(query: str, count: int = 10, categories: str = "general",
|
def searxng_search_api(query: str, count: Optional[int] = None, categories: str = "general",
|
||||||
time_filter: Optional[str] = None) -> List[dict]:
|
time_filter: Optional[str] = None) -> List[dict]:
|
||||||
"""Search using SearXNG JSON API. Returns list of {title, url, snippet}."""
|
"""Search using SearXNG JSON API. Returns list of {title, url, snippet}."""
|
||||||
|
count = count if count is not None else _get_result_count()
|
||||||
instance = _get_search_instance()
|
instance = _get_search_instance()
|
||||||
api_key = ""
|
api_key = ""
|
||||||
headers = {"User-Agent": "Mozilla/5.0"}
|
headers = {"User-Agent": "Mozilla/5.0"}
|
||||||
@@ -282,8 +283,9 @@ def searxng_search(query, max_results=10):
|
|||||||
|
|
||||||
# ── Brave ──
|
# ── Brave ──
|
||||||
|
|
||||||
def brave_search(query: str, count: int = 10, time_filter: Optional[str] = None) -> List[dict]:
|
def brave_search(query: str, count: Optional[int] = None, time_filter: Optional[str] = None) -> List[dict]:
|
||||||
"""Search using Brave API with key from admin settings or env var."""
|
"""Search using Brave API with key from admin settings or env var."""
|
||||||
|
count = count if count is not None else _get_result_count()
|
||||||
api_key = _get_provider_key("brave") or os.environ.get("DATA_BRAVE_API_KEY") or ""
|
api_key = _get_provider_key("brave") or os.environ.get("DATA_BRAVE_API_KEY") or ""
|
||||||
return _brave_search_impl(query, count, time_filter, search_config={"brave_api_key": api_key})
|
return _brave_search_impl(query, count, time_filter, search_config={"brave_api_key": api_key})
|
||||||
|
|
||||||
@@ -381,9 +383,9 @@ def _resolve_ddg_redirect(raw: str) -> str:
|
|||||||
return resolved
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
def duckduckgo_search(query: str, count: int = 10, time_filter: Optional[str] = None) -> List[dict]:
|
def duckduckgo_search(query: str, count: Optional[int] = None, time_filter: Optional[str] = None) -> List[dict]:
|
||||||
"""Search using DuckDuckGo via the duckduckgo-search library. No API key needed."""
|
"""Search using DuckDuckGo via the duckduckgo-search library. No API key needed."""
|
||||||
|
count = count if count is not None else _get_result_count()
|
||||||
def _html_fallback() -> List[dict]:
|
def _html_fallback() -> List[dict]:
|
||||||
try:
|
try:
|
||||||
response = httpx.get(
|
response = httpx.get(
|
||||||
@@ -452,7 +454,7 @@ def duckduckgo_search(query: str, count: int = 10, time_filter: Optional[str] =
|
|||||||
|
|
||||||
# ── Google Programmable Search Engine ──
|
# ── Google Programmable Search Engine ──
|
||||||
|
|
||||||
def google_pse_search(query: str, count: int = 10, time_filter: Optional[str] = None) -> List[dict]:
|
def google_pse_search(query: str, count: Optional[int] = None, time_filter: Optional[str] = None) -> List[dict]:
|
||||||
"""Search using Google PSE (Custom Search JSON API).
|
"""Search using Google PSE (Custom Search JSON API).
|
||||||
|
|
||||||
Requires two keys in settings:
|
Requires two keys in settings:
|
||||||
@@ -460,6 +462,7 @@ def google_pse_search(query: str, count: int = 10, time_filter: Optional[str] =
|
|||||||
- google_pse_cx: Programmable Search Engine ID (cx)
|
- google_pse_cx: Programmable Search Engine ID (cx)
|
||||||
Or env vars GOOGLE_API_KEY and GOOGLE_PSE_CX.
|
Or env vars GOOGLE_API_KEY and GOOGLE_PSE_CX.
|
||||||
"""
|
"""
|
||||||
|
count = count if count is not None else _get_result_count()
|
||||||
settings = _get_search_settings()
|
settings = _get_search_settings()
|
||||||
api_key = _get_provider_key("google_pse") or os.environ.get("GOOGLE_API_KEY", "")
|
api_key = _get_provider_key("google_pse") or os.environ.get("GOOGLE_API_KEY", "")
|
||||||
cx = (settings.get("google_pse_cx") or "").strip() or os.environ.get("GOOGLE_PSE_CX", "")
|
cx = (settings.get("google_pse_cx") or "").strip() or os.environ.get("GOOGLE_PSE_CX", "")
|
||||||
@@ -522,8 +525,9 @@ def google_pse_search(query: str, count: int = 10, time_filter: Optional[str] =
|
|||||||
|
|
||||||
# ── Tavily ──
|
# ── Tavily ──
|
||||||
|
|
||||||
def tavily_search(query: str, count: int = 10, time_filter: Optional[str] = None) -> List[dict]:
|
def tavily_search(query: str, count: Optional[int] = None, time_filter: Optional[str] = None) -> List[dict]:
|
||||||
"""Search using Tavily API. Requires search_api_key or TAVILY_API_KEY env var."""
|
"""Search using Tavily API. Requires search_api_key or TAVILY_API_KEY env var."""
|
||||||
|
count = count if count is not None else _get_result_count()
|
||||||
api_key = _get_provider_key("tavily") or os.environ.get("TAVILY_API_KEY", "")
|
api_key = _get_provider_key("tavily") or os.environ.get("TAVILY_API_KEY", "")
|
||||||
if not api_key:
|
if not api_key:
|
||||||
logger.warning("Tavily: no API key configured")
|
logger.warning("Tavily: no API key configured")
|
||||||
@@ -580,8 +584,9 @@ def tavily_search(query: str, count: int = 10, time_filter: Optional[str] = None
|
|||||||
|
|
||||||
# ── Serper.dev ──
|
# ── Serper.dev ──
|
||||||
|
|
||||||
def serper_search(query: str, count: int = 10, time_filter: Optional[str] = None) -> List[dict]:
|
def serper_search(query: str, count: Optional[int] = None, time_filter: Optional[str] = None) -> List[dict]:
|
||||||
"""Search using Serper.dev API. Requires search_api_key or SERPER_API_KEY env var."""
|
"""Search using Serper.dev API. Requires search_api_key or SERPER_API_KEY env var."""
|
||||||
|
count = count if count is not None else _get_result_count()
|
||||||
api_key = _get_provider_key("serper") or os.environ.get("SERPER_API_KEY", "")
|
api_key = _get_provider_key("serper") or os.environ.get("SERPER_API_KEY", "")
|
||||||
if not api_key:
|
if not api_key:
|
||||||
logger.warning("Serper: no API key configured")
|
logger.warning("Serper: no API key configured")
|
||||||
|
|||||||
@@ -1707,7 +1707,6 @@ async def stream_agent_loop(
|
|||||||
owner: Optional[str] = None,
|
owner: Optional[str] = None,
|
||||||
relevant_tools: Optional[Set[str]] = None,
|
relevant_tools: Optional[Set[str]] = None,
|
||||||
fallbacks: Optional[List[tuple]] = None,
|
fallbacks: Optional[List[tuple]] = None,
|
||||||
workspace: Optional[str] = None,
|
|
||||||
plan_mode: bool = False,
|
plan_mode: bool = False,
|
||||||
approved_plan: Optional[str] = None,
|
approved_plan: Optional[str] = None,
|
||||||
tool_policy: Optional[ToolPolicy] = None,
|
tool_policy: Optional[ToolPolicy] = None,
|
||||||
@@ -1935,27 +1934,6 @@ async def stream_agent_loop(
|
|||||||
owner=owner,
|
owner=owner,
|
||||||
suppress_local_context=guide_only,
|
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:
|
if plan_mode and not guide_only:
|
||||||
# Steer the model to investigate-then-propose. Hard tool gating handles
|
# Steer the model to investigate-then-propose. Hard tool gating handles
|
||||||
# every write path except shell; this directive is what keeps the
|
# every write path except shell; this directive is what keeps the
|
||||||
@@ -2649,7 +2627,6 @@ async def stream_agent_loop(
|
|||||||
tool_policy=tool_policy,
|
tool_policy=tool_policy,
|
||||||
owner=owner,
|
owner=owner,
|
||||||
progress_cb=_push_progress,
|
progress_cb=_push_progress,
|
||||||
workspace=workspace,
|
|
||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
# Sentinel so the drainer knows to stop.
|
# Sentinel so the drainer knows to stop.
|
||||||
|
|||||||
@@ -276,6 +276,24 @@ def _is_ollama_native_url(url: str) -> bool:
|
|||||||
return local_ollama_host and (path == "" or path == "/api" or path.startswith("/api/"))
|
return local_ollama_host and (path == "" or path == "/api" or path.startswith("/api/"))
|
||||||
|
|
||||||
|
|
||||||
|
def _is_ollama_openai_compat_url(url: str) -> bool:
|
||||||
|
"""Return True for local Ollama's OpenAI-compatible /v1 surface.
|
||||||
|
|
||||||
|
Mirrors the host detection used by ``_is_ollama_native_url`` so that the
|
||||||
|
two helpers stay in lockstep: a localhost Ollama on a non-default port
|
||||||
|
(custom ``OLLAMA_HOST``, reverse proxy, container port remap) is treated
|
||||||
|
the same way here as it is on the native ``/api`` path.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
parsed = urlparse(url or "")
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
host = parsed.hostname or ""
|
||||||
|
path = (parsed.path or "").rstrip("/")
|
||||||
|
local_ollama_host = host in {"localhost", "127.0.0.1", "0.0.0.0", "::1"} or parsed.port == 11434
|
||||||
|
return local_ollama_host and (path == "/v1" or path.startswith("/v1/"))
|
||||||
|
|
||||||
|
|
||||||
def _ollama_api_root(url: str) -> str:
|
def _ollama_api_root(url: str) -> str:
|
||||||
"""Return a native Ollama API root such as https://ollama.com/api."""
|
"""Return a native Ollama API root such as https://ollama.com/api."""
|
||||||
url = (url or "").strip().rstrip("/")
|
url = (url or "").strip().rstrip("/")
|
||||||
@@ -1344,6 +1362,9 @@ async def llm_call_async(
|
|||||||
if max_tokens and max_tokens > 0:
|
if max_tokens and max_tokens > 0:
|
||||||
tok_key = "max_completion_tokens" if _uses_max_completion_tokens(model) else "max_tokens"
|
tok_key = "max_completion_tokens" if _uses_max_completion_tokens(model) else "max_tokens"
|
||||||
payload[tok_key] = max_tokens
|
payload[tok_key] = max_tokens
|
||||||
|
# Suppress thinking for qwen3/gemma4 on Ollama /v1 — same as stream_llm.
|
||||||
|
if _is_ollama_openai_compat_url(url) and _supports_thinking(model):
|
||||||
|
payload["think"] = False
|
||||||
|
|
||||||
if _is_host_dead(target_url):
|
if _is_host_dead(target_url):
|
||||||
raise HTTPException(503, f"Upstream {_host_key(target_url)} marked unreachable (cooldown active)")
|
raise HTTPException(503, f"Upstream {_host_key(target_url)} marked unreachable (cooldown active)")
|
||||||
@@ -1461,6 +1482,11 @@ async def stream_llm(url: str, model: str, messages: List[Dict], temperature: fl
|
|||||||
payload[tok_key] = max_tokens
|
payload[tok_key] = max_tokens
|
||||||
if tools:
|
if tools:
|
||||||
payload["tools"] = tools
|
payload["tools"] = tools
|
||||||
|
# For Ollama's OpenAI-compat /v1 endpoint with thinking models (qwen3,
|
||||||
|
# gemma4, etc.), suppress thinking so tool calls aren't swallowed inside
|
||||||
|
# <think> blocks. Ollama /v1 accepts "think": false as a top-level param.
|
||||||
|
if _is_ollama_openai_compat_url(url) and _supports_thinking(model):
|
||||||
|
payload["think"] = False
|
||||||
h = _provider_headers(provider, headers)
|
h = _provider_headers(provider, headers)
|
||||||
if provider == "copilot":
|
if provider == "copilot":
|
||||||
from src.copilot import apply_request_headers
|
from src.copilot import apply_request_headers
|
||||||
|
|||||||
+19
-67
@@ -67,13 +67,12 @@ def _unified_diff(old: str, new: str, path: str) -> Optional[Dict[str, Any]]:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async def _do_edit_file(content: str, workspace: Optional[str] = None) -> Dict[str, Any]:
|
async def _do_edit_file(content: str) -> Dict[str, Any]:
|
||||||
"""Exact string-replacement edit of an on-disk file.
|
"""Exact string-replacement edit of an on-disk file.
|
||||||
|
|
||||||
content is JSON: {"path", "old_string", "new_string", "replace_all"?}.
|
content is JSON: {"path", "old_string", "new_string", "replace_all"?}.
|
||||||
Fails if old_string is missing or non-unique (unless replace_all) so the
|
Fails if old_string is missing or non-unique (unless replace_all) so the
|
||||||
model can't silently edit the wrong place. Returns a unified diff for the UI.
|
model can't silently edit the wrong place. Returns a unified diff for the UI.
|
||||||
Confined to the workspace when one is set (same policy as write_file).
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
args = json.loads(content) if content.strip().startswith("{") else {}
|
args = json.loads(content) if content.strip().startswith("{") else {}
|
||||||
@@ -85,11 +84,9 @@ async def _do_edit_file(content: str, workspace: Optional[str] = None) -> Dict[s
|
|||||||
replace_all = bool(args.get("replace_all", False))
|
replace_all = bool(args.get("replace_all", False))
|
||||||
if not raw_path:
|
if not raw_path:
|
||||||
return {"error": "edit_file: path required", "exit_code": 1}
|
return {"error": "edit_file: path required", "exit_code": 1}
|
||||||
# Confine to the workspace when set, else the same allowlist + sensitive-file
|
# Allowlist + sensitive-file policy as read/write_file.
|
||||||
# policy as read/write_file.
|
|
||||||
try:
|
try:
|
||||||
path = (_resolve_tool_path_in_workspace(workspace, raw_path)
|
path = _resolve_tool_path(raw_path)
|
||||||
if workspace else _resolve_tool_path(raw_path))
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return {"error": f"edit_file: {e}", "exit_code": 1}
|
return {"error": f"edit_file: {e}", "exit_code": 1}
|
||||||
if old == "":
|
if old == "":
|
||||||
@@ -272,39 +269,6 @@ def _resolve_tool_path(raw_path: str) -> str:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _resolve_tool_path_in_workspace(workspace: str, raw_path: str) -> str:
|
|
||||||
"""Confine a model-supplied path to the active workspace.
|
|
||||||
|
|
||||||
Layered on top of upstream's path policy: the workspace is the allowed
|
|
||||||
root (relative paths resolve under it; paths that escape it are rejected),
|
|
||||||
and the sensitive-file deny list (.ssh, .gnupg, id_rsa, …) still applies
|
|
||||||
inside it. When no workspace is set, callers use _resolve_tool_path (the
|
|
||||||
default data/tmp allowlist) instead.
|
|
||||||
"""
|
|
||||||
if raw_path is None or not str(raw_path).strip():
|
|
||||||
raise ValueError("path is required")
|
|
||||||
base = os.path.realpath(workspace)
|
|
||||||
expanded = os.path.expanduser(str(raw_path).strip())
|
|
||||||
candidate = expanded if os.path.isabs(expanded) else os.path.join(base, expanded)
|
|
||||||
resolved = os.path.realpath(candidate)
|
|
||||||
if _is_sensitive_path(resolved):
|
|
||||||
raise ValueError(
|
|
||||||
f"path '{raw_path}' is inside a sensitive directory "
|
|
||||||
f"(e.g. .ssh, .gnupg) or matches a sensitive filename"
|
|
||||||
)
|
|
||||||
if resolved != base:
|
|
||||||
# normcase so containment holds on case-insensitive filesystems
|
|
||||||
# (Windows, default macOS): it lowercases on Windows and is a no-op on
|
|
||||||
# POSIX. commonpath raises ValueError across Windows drives (C: vs D:)
|
|
||||||
# or mixed abs/rel — both mean "outside", so the except rejects them.
|
|
||||||
nbase = os.path.normcase(base)
|
|
||||||
try:
|
|
||||||
if os.path.commonpath([os.path.normcase(resolved), nbase]) != nbase:
|
|
||||||
raise ValueError
|
|
||||||
except ValueError:
|
|
||||||
raise ValueError(f"path '{raw_path}' is outside the workspace ({workspace})")
|
|
||||||
return resolved
|
|
||||||
|
|
||||||
# Bash + python tools used to share a single 60s timeout. That's
|
# Bash + python tools used to share a single 60s timeout. That's
|
||||||
# enough for one-shot commands but starves real workloads (pip
|
# enough for one-shot commands but starves real workloads (pip
|
||||||
# install, ffmpeg conversions, etc.) — and worse, the agent saw the
|
# install, ffmpeg conversions, etc.) — and worse, the agent saw the
|
||||||
@@ -341,19 +305,13 @@ _CODENAV_MAX_HITS = 200
|
|||||||
_CODENAV_MAX_LINE = 400
|
_CODENAV_MAX_LINE = 400
|
||||||
|
|
||||||
|
|
||||||
def _resolve_search_root(raw_path: str, workspace: Optional[str] = None) -> str:
|
def _resolve_search_root(raw_path: str) -> str:
|
||||||
"""Resolve + confine a code-nav path (grep/glob/ls).
|
"""Resolve + confine a code-nav path (grep/glob/ls).
|
||||||
|
|
||||||
With a workspace set, the workspace folder is the root and supplied paths are
|
An empty path defaults to the agent's primary root (project data dir) and a
|
||||||
confined inside it (same policy as read_file). Without one, an empty path
|
supplied path is confined by the global allowlist + sensitive-file policy.
|
||||||
defaults to the agent's primary root (project data dir) and a supplied path
|
|
||||||
is confined by the global allowlist + sensitive-file policy.
|
|
||||||
"""
|
"""
|
||||||
raw = (raw_path or "").strip()
|
raw = (raw_path or "").strip()
|
||||||
if workspace:
|
|
||||||
if not raw:
|
|
||||||
return os.path.realpath(workspace)
|
|
||||||
return _resolve_tool_path_in_workspace(workspace, raw)
|
|
||||||
if not raw:
|
if not raw:
|
||||||
roots = _tool_path_roots()
|
roots = _tool_path_roots()
|
||||||
return roots[0] if roots else os.path.realpath(".")
|
return roots[0] if roots else os.path.realpath(".")
|
||||||
@@ -564,12 +522,11 @@ async def _call_mcp_tool(
|
|||||||
tool: str,
|
tool: str,
|
||||||
content: str,
|
content: str,
|
||||||
progress_cb: Optional[Callable[[Dict], Awaitable[None]]] = None,
|
progress_cb: Optional[Callable[[Dict], Awaitable[None]]] = None,
|
||||||
workspace: Optional[str] = None,
|
|
||||||
) -> Dict:
|
) -> Dict:
|
||||||
"""Route a legacy tool call through the MCP manager, with direct fallbacks."""
|
"""Route a legacy tool call through the MCP manager, with direct fallbacks."""
|
||||||
mcp = get_mcp_manager()
|
mcp = get_mcp_manager()
|
||||||
if not mcp:
|
if not mcp:
|
||||||
return await _direct_fallback(tool, content, progress_cb=progress_cb, workspace=workspace) or {"error": f"MCP manager not available for tool '{tool}'", "exit_code": 1}
|
return await _direct_fallback(tool, content, progress_cb=progress_cb) or {"error": f"MCP manager not available for tool '{tool}'", "exit_code": 1}
|
||||||
|
|
||||||
server_id, tool_name = _MCP_TOOL_MAP[tool]
|
server_id, tool_name = _MCP_TOOL_MAP[tool]
|
||||||
qualified = f"mcp__{server_id}__{tool_name}"
|
qualified = f"mcp__{server_id}__{tool_name}"
|
||||||
@@ -578,7 +535,7 @@ async def _call_mcp_tool(
|
|||||||
|
|
||||||
# If MCP server not connected, try direct fallback
|
# If MCP server not connected, try direct fallback
|
||||||
if isinstance(result, dict) and result.get("exit_code") == 1 and "not connected" in result.get("error", ""):
|
if isinstance(result, dict) and result.get("exit_code") == 1 and "not connected" in result.get("error", ""):
|
||||||
fallback = await _direct_fallback(tool, content, progress_cb=progress_cb, workspace=workspace)
|
fallback = await _direct_fallback(tool, content, progress_cb=progress_cb)
|
||||||
if fallback:
|
if fallback:
|
||||||
return fallback
|
return fallback
|
||||||
|
|
||||||
@@ -636,7 +593,6 @@ async def _direct_fallback(
|
|||||||
tool: str,
|
tool: str,
|
||||||
content: str,
|
content: str,
|
||||||
progress_cb: Optional[Callable[[Dict], Awaitable[None]]] = None,
|
progress_cb: Optional[Callable[[Dict], Awaitable[None]]] = None,
|
||||||
workspace: Optional[str] = None,
|
|
||||||
) -> Optional[Dict]:
|
) -> Optional[Dict]:
|
||||||
"""In-process execution path for the eight tools that used to live as
|
"""In-process execution path for the eight tools that used to live as
|
||||||
stdio MCP servers under mcp_servers/. Those servers were deleted in
|
stdio MCP servers under mcp_servers/. Those servers were deleted in
|
||||||
@@ -670,7 +626,7 @@ async def _direct_fallback(
|
|||||||
stdout=asyncio.subprocess.PIPE,
|
stdout=asyncio.subprocess.PIPE,
|
||||||
stderr=asyncio.subprocess.PIPE,
|
stderr=asyncio.subprocess.PIPE,
|
||||||
env=_subproc_env,
|
env=_subproc_env,
|
||||||
cwd=workspace or _AGENT_WORKDIR,
|
cwd=_AGENT_WORKDIR,
|
||||||
)
|
)
|
||||||
stdout, stderr, rc, timed_out = await _run_subprocess_streaming(
|
stdout, stderr, rc, timed_out = await _run_subprocess_streaming(
|
||||||
proc,
|
proc,
|
||||||
@@ -697,7 +653,7 @@ async def _direct_fallback(
|
|||||||
stdout=asyncio.subprocess.PIPE,
|
stdout=asyncio.subprocess.PIPE,
|
||||||
stderr=asyncio.subprocess.PIPE,
|
stderr=asyncio.subprocess.PIPE,
|
||||||
env=_subproc_env,
|
env=_subproc_env,
|
||||||
cwd=workspace or _AGENT_WORKDIR,
|
cwd=_AGENT_WORKDIR,
|
||||||
)
|
)
|
||||||
stdout, stderr, rc, timed_out = await _run_subprocess_streaming(
|
stdout, stderr, rc, timed_out = await _run_subprocess_streaming(
|
||||||
proc,
|
proc,
|
||||||
@@ -727,8 +683,7 @@ async def _direct_fallback(
|
|||||||
except (json.JSONDecodeError, TypeError, ValueError):
|
except (json.JSONDecodeError, TypeError, ValueError):
|
||||||
pass
|
pass
|
||||||
try:
|
try:
|
||||||
path = (_resolve_tool_path_in_workspace(workspace, raw_path)
|
path = _resolve_tool_path(raw_path)
|
||||||
if workspace else _resolve_tool_path(raw_path))
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return {"error": f"read_file: {e}", "exit_code": 1}
|
return {"error": f"read_file: {e}", "exit_code": 1}
|
||||||
try:
|
try:
|
||||||
@@ -771,8 +726,7 @@ async def _direct_fallback(
|
|||||||
raw_path = lines[0].strip()
|
raw_path = lines[0].strip()
|
||||||
body = lines[1] if len(lines) > 1 else ""
|
body = lines[1] if len(lines) > 1 else ""
|
||||||
try:
|
try:
|
||||||
path = (_resolve_tool_path_in_workspace(workspace, raw_path)
|
path = _resolve_tool_path(raw_path)
|
||||||
if workspace else _resolve_tool_path(raw_path))
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return {"error": f"write_file: {e}", "exit_code": 1}
|
return {"error": f"write_file: {e}", "exit_code": 1}
|
||||||
try:
|
try:
|
||||||
@@ -825,7 +779,7 @@ async def _direct_fallback(
|
|||||||
max_hits = _CODENAV_MAX_HITS
|
max_hits = _CODENAV_MAX_HITS
|
||||||
max_hits = max(1, min(max_hits, _CODENAV_MAX_HITS))
|
max_hits = max(1, min(max_hits, _CODENAV_MAX_HITS))
|
||||||
try:
|
try:
|
||||||
root = _resolve_search_root(str(args.get("path", "")), workspace)
|
root = _resolve_search_root(str(args.get("path", "")))
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return {"error": f"grep: {e}", "exit_code": 1}
|
return {"error": f"grep: {e}", "exit_code": 1}
|
||||||
|
|
||||||
@@ -909,7 +863,7 @@ async def _direct_fallback(
|
|||||||
if not pattern:
|
if not pattern:
|
||||||
return {"error": "glob: pattern is required", "exit_code": 1}
|
return {"error": "glob: pattern is required", "exit_code": 1}
|
||||||
try:
|
try:
|
||||||
root = _resolve_search_root(str(args.get("path", "")), workspace)
|
root = _resolve_search_root(str(args.get("path", "")))
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return {"error": f"glob: {e}", "exit_code": 1}
|
return {"error": f"glob: {e}", "exit_code": 1}
|
||||||
|
|
||||||
@@ -956,7 +910,7 @@ async def _direct_fallback(
|
|||||||
else:
|
else:
|
||||||
raw_path = _s.split("\n", 1)[0].strip()
|
raw_path = _s.split("\n", 1)[0].strip()
|
||||||
try:
|
try:
|
||||||
root = _resolve_search_root(raw_path, workspace)
|
root = _resolve_search_root(raw_path)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return {"error": f"ls: {e}", "exit_code": 1}
|
return {"error": f"ls: {e}", "exit_code": 1}
|
||||||
|
|
||||||
@@ -1121,7 +1075,6 @@ async def execute_tool_block(
|
|||||||
tool_policy: Optional[ToolPolicy] = None,
|
tool_policy: Optional[ToolPolicy] = None,
|
||||||
owner: Optional[str] = None,
|
owner: Optional[str] = None,
|
||||||
progress_cb: Optional[Callable[[Dict], Awaitable[None]]] = None,
|
progress_cb: Optional[Callable[[Dict], Awaitable[None]]] = None,
|
||||||
workspace: Optional[str] = None,
|
|
||||||
) -> Tuple[str, Dict]:
|
) -> Tuple[str, Dict]:
|
||||||
"""Execute a single tool block. Returns (description, result_dict).
|
"""Execute a single tool block. Returns (description, result_dict).
|
||||||
|
|
||||||
@@ -1296,7 +1249,7 @@ async def execute_tool_block(
|
|||||||
_is_bg, _bg_cmd = _split_bg_marker(content)
|
_is_bg, _bg_cmd = _split_bg_marker(content)
|
||||||
if _is_bg and _bg_cmd:
|
if _is_bg and _bg_cmd:
|
||||||
from src import bg_jobs
|
from src import bg_jobs
|
||||||
rec = bg_jobs.launch(_bg_cmd, session_id=session_id, cwd=workspace or _AGENT_WORKDIR)
|
rec = bg_jobs.launch(_bg_cmd, session_id=session_id, cwd=_AGENT_WORKDIR)
|
||||||
short = _bg_cmd.strip().split(chr(10))[0][:80]
|
short = _bg_cmd.strip().split(chr(10))[0][:80]
|
||||||
desc = f"bash (background): {short}"
|
desc = f"bash (background): {short}"
|
||||||
result = {
|
result = {
|
||||||
@@ -1318,13 +1271,12 @@ async def execute_tool_block(
|
|||||||
if tool in _MCP_TOOL_MAP:
|
if tool in _MCP_TOOL_MAP:
|
||||||
first_line = content.split(chr(10))[0][:80]
|
first_line = content.split(chr(10))[0][:80]
|
||||||
desc = f"{tool}: {first_line}"
|
desc = f"{tool}: {first_line}"
|
||||||
result = await _call_mcp_tool(tool, content, progress_cb=progress_cb, workspace=workspace)
|
result = await _call_mcp_tool(tool, content, progress_cb=progress_cb)
|
||||||
elif tool in ("grep", "glob", "ls"):
|
elif tool in ("grep", "glob", "ls"):
|
||||||
# Code-navigation tools — no MCP server; run the direct implementation.
|
# Code-navigation tools — no MCP server; run the direct implementation.
|
||||||
# Confined to the workspace when one is set (same policy as read_file).
|
|
||||||
first_line = content.split(chr(10))[0][:80]
|
first_line = content.split(chr(10))[0][:80]
|
||||||
desc = f"{tool}: {first_line}"
|
desc = f"{tool}: {first_line}"
|
||||||
result = await _direct_fallback(tool, content, progress_cb=progress_cb, workspace=workspace) \
|
result = await _direct_fallback(tool, content, progress_cb=progress_cb) \
|
||||||
or {"error": f"{tool}: execution failed", "exit_code": 1}
|
or {"error": f"{tool}: execution failed", "exit_code": 1}
|
||||||
elif tool == "create_document":
|
elif tool == "create_document":
|
||||||
title = content.split("\n")[0].strip()[:60]
|
title = content.split("\n")[0].strip()[:60]
|
||||||
@@ -1429,7 +1381,7 @@ async def execute_tool_block(
|
|||||||
desc = "edit_image"
|
desc = "edit_image"
|
||||||
result = await do_edit_image(content, owner=owner)
|
result = await do_edit_image(content, owner=owner)
|
||||||
elif tool == "edit_file":
|
elif tool == "edit_file":
|
||||||
result = await _do_edit_file(content, workspace=workspace)
|
result = await _do_edit_file(content)
|
||||||
desc = result.get("output") or result.get("error") or "edit_file"
|
desc = result.get("output") or result.get("error") or "edit_file"
|
||||||
elif tool == "trigger_research":
|
elif tool == "trigger_research":
|
||||||
desc = "trigger_research"
|
desc = "trigger_research"
|
||||||
|
|||||||
+69
-45
@@ -1325,10 +1325,6 @@
|
|||||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><circle cx="6" cy="6" r="1"/><circle cx="6" cy="18" r="1"/></svg>
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><circle cx="6" cy="6" r="1"/><circle cx="6" cy="18" r="1"/></svg>
|
||||||
<span>Add Models</span>
|
<span>Add Models</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="settings-nav-item" data-settings-tab="added-models">
|
|
||||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
|
|
||||||
<span>Added Models</span>
|
|
||||||
</button>
|
|
||||||
<button class="settings-nav-item" data-settings-tab="ai">
|
<button class="settings-nav-item" data-settings-tab="ai">
|
||||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a4 4 0 0 0-4 4v2H6a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2h-2V6a4 4 0 0 0-4-4z"/></svg>
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a4 4 0 0 0-4 4v2H6a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2h-2V6a4 4 0 0 0-4-4z"/></svg>
|
||||||
<span>AI Defaults</span>
|
<span>AI Defaults</span>
|
||||||
@@ -1561,12 +1557,21 @@
|
|||||||
<div id="set-ttsSettingsMsg" style="font-size:11px;color:color-mix(in srgb, var(--fg) 45%, transparent);"></div>
|
<div id="set-ttsSettingsMsg" style="font-size:11px;color:color-mix(in srgb, var(--fg) 45%, transparent);"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- Teacher Model settings card hidden as part of the 2.0
|
<div class="admin-card">
|
||||||
"harden the core" pass. The escalation flow is dormant when
|
<h2 style="display:flex;align-items:center;gap:6px;"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;opacity:0.6"><path d="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c3 3 9 3 12 0v-5"/></svg>Teacher Model <span style="font-size:0.72em;opacity:0.55;font-weight:normal;">(Experimental)</span><span style="flex:1"></span><label class="admin-switch"><input type="checkbox" id="set-teacherEnabledToggle"><span class="admin-slider"></span></label></h2>
|
||||||
`teacher_model` is unset (its default), so the backend keeps
|
<div class="admin-toggle-sub" style="margin-bottom:8px">When a self-hosted student fails an agent-mode task, escalate to a SOTA teacher that writes a SKILL.md procedure so the student can do it next time. Off by default.</div>
|
||||||
working for anyone who wired it via `manage_settings` /
|
<div class="settings-col">
|
||||||
settings backup. Re-add this card to surface the toggle
|
<div class="settings-row">
|
||||||
again once the core experience is faster. -->
|
<label class="settings-label">Endpoint</label>
|
||||||
|
<select id="set-teacherEpSelect" class="settings-select"><option value="">—</option></select>
|
||||||
|
</div>
|
||||||
|
<div class="settings-row">
|
||||||
|
<label class="settings-label">Model</label>
|
||||||
|
<select id="set-teacherModelSelect" class="settings-select"><option value="">—</option></select>
|
||||||
|
</div>
|
||||||
|
<div id="set-teacherChatMsg" style="font-size:11px;color:color-mix(in srgb, var(--fg) 45%, transparent);"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ═══ SEARCH TAB ═══ -->
|
<!-- ═══ SEARCH TAB ═══ -->
|
||||||
@@ -2002,29 +2007,37 @@
|
|||||||
|
|
||||||
<!-- ═══ SERVICES TAB ═══ -->
|
<!-- ═══ SERVICES TAB ═══ -->
|
||||||
<div data-settings-panel="services">
|
<div data-settings-panel="services">
|
||||||
|
|
||||||
<!-- ── Local card ─────────────────────────────────────────── -->
|
|
||||||
<div class="admin-card">
|
<div class="admin-card">
|
||||||
<h2 style="display:flex;align-items:center;gap:8px;"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;opacity:0.6"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/></svg>Local Models</h2>
|
<h2><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;opacity:0.6"><rect x="2" y="2" width="20" height="8" rx="2"/><rect x="2" y="14" width="20" height="8" rx="2"/><circle cx="6" cy="6" r="1"/><circle cx="6" cy="18" r="1"/></svg>Add Models <span style="opacity:0.45;font-weight:normal;font-size:0.82em">(Endpoints)</span></h2>
|
||||||
<div class="admin-toggle-sub" style="margin:0 0 10px 2px;">Add a local model server (Ollama, llama.cpp, vLLM).</div>
|
<div class="admin-toggle-sub" style="margin-bottom:10px">Connect local models first, or add a cloud API.</div>
|
||||||
<div class="adm-add-section">
|
|
||||||
|
<!-- Local subsection -->
|
||||||
|
<div class="adm-add-section collapsible collapsed" id="adm-add-local">
|
||||||
|
<div class="adm-ep-section-head adm-section-toggle" role="button" tabindex="0" aria-expanded="false">
|
||||||
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:4px;"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/></svg>
|
||||||
|
<span>Local</span>
|
||||||
|
<svg class="adm-section-caret" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
|
||||||
|
</div>
|
||||||
<div class="admin-model-form">
|
<div class="admin-model-form">
|
||||||
<div class="admin-model-form-row">
|
<div class="admin-model-form-row">
|
||||||
<div class="adm-fused-group" style="display:flex;flex:1 1 180px;min-width:0;">
|
<input id="adm-epLocalUrl" type="text" placeholder="Paste endpoint URL, e.g. http://localhost:11434/v1" style="flex:1">
|
||||||
<select id="adm-epLocalType" style="padding:5px;width:62px;flex-shrink:0;border-top-right-radius:0;border-bottom-right-radius:0;border-right:0;">
|
|
||||||
<option value="llm" selected>LLM</option>
|
|
||||||
<option value="image">Image</option>
|
|
||||||
</select>
|
|
||||||
<input id="adm-epLocalUrl" type="text" placeholder="Paste endpoint URL, e.g. http://localhost:11434/v1" style="flex:1;min-width:0;border-top-left-radius:0;border-bottom-left-radius:0;">
|
|
||||||
</div>
|
|
||||||
<button class="admin-btn-add" id="adm-epLocalAddBtn" style="min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;flex-shrink:0;">
|
|
||||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>Add
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
<!-- API key row stays in the DOM but is collapsed until the
|
||||||
|
user clicks the Key button on the action row. Local
|
||||||
|
endpoints rarely need a key; hiding it by default keeps
|
||||||
|
the form a single visual line. -->
|
||||||
<div class="admin-model-form-row" id="adm-epLocalApiKey-row" style="display:none;">
|
<div class="admin-model-form-row" id="adm-epLocalApiKey-row" style="display:none;">
|
||||||
<input id="adm-epLocalApiKey" type="password" placeholder="API key (optional — for protected local endpoints)" autocomplete="off" style="flex:1">
|
<input id="adm-epLocalApiKey" type="password" placeholder="API key (optional — for protected local endpoints)" autocomplete="off" style="flex:1">
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Action row: LLM/Image type, Quickstart buttons (Scan,
|
||||||
|
Ollama), Key reveal toggle, Test, Add — all inline so
|
||||||
|
the Quickstart fold is gone and Type sits with the
|
||||||
|
primary actions. -->
|
||||||
<div class="admin-model-form-row">
|
<div class="admin-model-form-row">
|
||||||
|
<label style="display:inline-flex;align-items:center;gap:4px;font-size:11px;opacity:0.6;flex-shrink:0;">Type:<select id="adm-epLocalType" style="padding:5px;width:72px;flex-shrink:0;">
|
||||||
|
<option value="llm" selected>LLM</option>
|
||||||
|
<option value="image">Image</option>
|
||||||
|
</select></label>
|
||||||
<button class="admin-btn-sm" id="adm-epDiscoverBtn" title="Scan your network for running model servers" style="display:inline-flex;align-items:center;gap:4px;">
|
<button class="admin-btn-sm" id="adm-epDiscoverBtn" title="Scan your network for running model servers" style="display:inline-flex;align-items:center;gap:4px;">
|
||||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>Scan
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>Scan
|
||||||
</button>
|
</button>
|
||||||
@@ -2036,18 +2049,25 @@
|
|||||||
<button class="admin-btn-sm" id="adm-epLocalTestBtn" style="min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;">
|
<button class="admin-btn-sm" id="adm-epLocalTestBtn" style="min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;">
|
||||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>Test
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>Test
|
||||||
</button>
|
</button>
|
||||||
|
<button class="admin-btn-add" id="adm-epLocalAddBtn" style="min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;">
|
||||||
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>Add
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="adm-epLocalMsg" class="adm-ep-inline-msg"></div>
|
<div id="adm-epLocalMsg" class="adm-ep-inline-msg"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ── API card ───────────────────────────────────────────── -->
|
<!-- API subsection -->
|
||||||
<div class="admin-card">
|
<div class="adm-add-section collapsible collapsed" id="adm-add-api" style="margin-top:14px">
|
||||||
<h2 style="display:flex;align-items:center;gap:8px;"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;opacity:0.6"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>API Models</h2>
|
<div class="adm-ep-section-head adm-section-toggle" role="button" tabindex="0" aria-expanded="false">
|
||||||
<div class="admin-toggle-sub" style="margin:0 0 10px 2px;">Connect a cloud provider (OpenAI, Anthropic, DeepSeek, OpenRouter, etc.).</div>
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:4px;"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
|
||||||
<div class="adm-add-section">
|
<span>API</span>
|
||||||
|
<svg class="adm-section-caret" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
|
||||||
|
</div>
|
||||||
<div class="admin-model-form">
|
<div class="admin-model-form">
|
||||||
|
<!-- Custom picker (with logos). Hidden native <select> mirrors
|
||||||
|
its value so the existing JS that reads adm-epProvider
|
||||||
|
keeps working unchanged. -->
|
||||||
<div class="adm-provider-picker adm-provider-combo" id="adm-provider-picker">
|
<div class="adm-provider-picker adm-provider-combo" id="adm-provider-picker">
|
||||||
<input id="adm-epUrl" type="text" placeholder="Base URL or pick provider" autocomplete="off">
|
<input id="adm-epUrl" type="text" placeholder="Base URL or pick provider" autocomplete="off">
|
||||||
<button type="button" class="adm-provider-btn" id="adm-provider-btn" title="Pick provider">
|
<button type="button" class="adm-provider-btn" id="adm-provider-btn" title="Pick provider">
|
||||||
@@ -2076,7 +2096,11 @@
|
|||||||
<option value="https://opencode.ai/zen/go/v1" data-logo="opencode">OpenCode Go</option>
|
<option value="https://opencode.ai/zen/go/v1" data-logo="opencode">OpenCode Go</option>
|
||||||
<option value="https://api.z.ai/api/coding/paas/v4" data-logo="zhipu">Z.AI Coding Plan</option>
|
<option value="https://api.z.ai/api/coding/paas/v4" data-logo="zhipu">Z.AI Coding Plan</option>
|
||||||
</select>
|
</select>
|
||||||
<div class="admin-model-form-row" id="adm-epApiKey-row">
|
<!-- API key row stays in DOM, hidden until Key button is
|
||||||
|
clicked. Mirrors the Local section pattern: most users
|
||||||
|
paste a key via the provider preset flow rather than
|
||||||
|
typing it free-form, so the row only appears on demand. -->
|
||||||
|
<div class="admin-model-form-row" id="adm-epApiKey-row" style="display:none;">
|
||||||
<input id="adm-epApiKey" type="password" placeholder="API key" autocomplete="off" style="flex:1">
|
<input id="adm-epApiKey" type="password" placeholder="API key" autocomplete="off" style="flex:1">
|
||||||
</div>
|
</div>
|
||||||
<div class="admin-model-form-row" style="margin-top:-4px;">
|
<div class="admin-model-form-row" style="margin-top:-4px;">
|
||||||
@@ -2089,6 +2113,9 @@
|
|||||||
<option value="image">Image</option>
|
<option value="image">Image</option>
|
||||||
</select></label>
|
</select></label>
|
||||||
<span style="flex:1"></span>
|
<span style="flex:1"></span>
|
||||||
|
<button class="admin-btn-sm" id="adm-epApiKeyBtn" title="Show / hide the API key field" aria-expanded="false" aria-controls="adm-epApiKey-row" style="opacity:0.75;display:inline-flex;align-items:center;gap:4px;">
|
||||||
|
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2l-9.6 9.6"/><circle cx="7.5" cy="15.5" r="5.5"/><path d="M15.5 7.5l3 3"/></svg>API
|
||||||
|
</button>
|
||||||
<button class="admin-btn-sm" id="adm-epApiTestBtn" style="min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;">
|
<button class="admin-btn-sm" id="adm-epApiTestBtn" style="min-width:55px;text-align:center;display:inline-flex;align-items:center;justify-content:center;gap:4px;">
|
||||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>Test
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>Test
|
||||||
</button>
|
</button>
|
||||||
@@ -2102,13 +2129,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ═══ ADDED MODELS TAB ═══ -->
|
|
||||||
<div data-settings-panel="added-models" class="hidden">
|
|
||||||
<div class="admin-card">
|
<div class="admin-card">
|
||||||
<h2 style="display:flex;align-items:center;gap:8px;"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;opacity:0.6"><polyline points="20 6 9 17 4 12"/></svg>Added Models <span style="opacity:0.45;font-weight:normal;font-size:0.82em">(Endpoints)</span>
|
<h2 style="display:flex;align-items:center;gap:8px;"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:5px;opacity:0.6"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>Added Models <span style="opacity:0.45;font-weight:normal;font-size:0.82em">(Endpoints)</span>
|
||||||
<span style="flex:1"></span>
|
<span style="flex:1"></span>
|
||||||
<button class="admin-btn-sm" id="adm-epProbeAllBtn" title="Re-test every endpoint and refresh online status" style="font-size:11px;font-weight:normal;display:inline-flex;align-items:center;gap:4px;">
|
<button class="admin-btn-sm" id="adm-epProbeAllBtn" title="Re-test every endpoint and refresh online status" style="font-size:11px;font-weight:normal;display:inline-flex;align-items:center;gap:4px;">
|
||||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>Probe
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>Probe
|
||||||
@@ -2117,18 +2139,20 @@
|
|||||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>Clear offline <span id="adm-epOfflineCount" style="opacity:0.6;margin-left:2px;"></span>
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>Clear offline <span id="adm-epOfflineCount" style="opacity:0.6;margin-left:2px;"></span>
|
||||||
</button>
|
</button>
|
||||||
</h2>
|
</h2>
|
||||||
<div class="admin-toggle-sub" style="margin-bottom:12px">Endpoints you've connected. Probe re-tests them all; Clear offline removes the dead ones.</div>
|
<div class="admin-toggle-sub" style="margin-bottom:10px">Manage the endpoints you've added.</div>
|
||||||
<div class="adm-ep-section">
|
<div class="adm-ep-section">
|
||||||
<div class="adm-ep-section-head" style="font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;opacity:0.7;margin-bottom:6px;display:inline-flex;align-items:center;gap:5px;">
|
<div class="adm-ep-section-head">
|
||||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/></svg>Local
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:4px;"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/></svg>
|
||||||
|
<span>Local</span>
|
||||||
</div>
|
</div>
|
||||||
<div id="adm-epList-local"><div class="admin-empty">Loading...</div></div>
|
<div id="adm-epList-local"><div class="admin-empty">Loading...</div></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="adm-ep-section" style="margin-top:18px;">
|
<div class="adm-ep-section" style="margin-top:14px">
|
||||||
<div class="adm-ep-section-head" style="font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;opacity:0.7;margin-bottom:6px;display:inline-flex;align-items:center;gap:5px;">
|
<div class="adm-ep-section-head">
|
||||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>API
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:4px;"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
|
||||||
|
<span>API</span>
|
||||||
</div>
|
</div>
|
||||||
<div id="adm-epList-api"><div class="admin-empty">No API endpoints yet.</div></div>
|
<div id="adm-epList-api"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1168,6 +1168,7 @@ function initEndpointForm() {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
_wireKeyToggle('adm-epLocalKeyBtn', 'adm-epLocalApiKey-row');
|
_wireKeyToggle('adm-epLocalKeyBtn', 'adm-epLocalApiKey-row');
|
||||||
|
_wireKeyToggle('adm-epApiKeyBtn', 'adm-epApiKey-row');
|
||||||
|
|
||||||
// ── Added Models toolbar: Probe + Clear offline ────────────────────
|
// ── Added Models toolbar: Probe + Clear offline ────────────────────
|
||||||
// Both buttons act over the currently-rendered endpoint list. The
|
// Both buttons act over the currently-rendered endpoint list. The
|
||||||
@@ -1443,6 +1444,30 @@ function initEndpointForm() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Collapsible Add-Models subsections (API / Local). Both start collapsed
|
||||||
|
// so the card is compact; the last-used state is remembered per section
|
||||||
|
// in localStorage so a frequent API-adder doesn't re-expand every time.
|
||||||
|
document.querySelectorAll('#adm-add-api, #adm-add-local').forEach((sec) => {
|
||||||
|
const head = sec.querySelector('.adm-section-toggle');
|
||||||
|
if (!head) return;
|
||||||
|
const key = 'odysseus.addModels.' + sec.id + '.open';
|
||||||
|
let open = false;
|
||||||
|
try { open = localStorage.getItem(key) === '1'; } catch {}
|
||||||
|
const apply = () => {
|
||||||
|
sec.classList.toggle('collapsed', !open);
|
||||||
|
head.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||||||
|
};
|
||||||
|
apply();
|
||||||
|
const toggle = () => {
|
||||||
|
open = !open;
|
||||||
|
try { localStorage.setItem(key, open ? '1' : '0'); } catch {}
|
||||||
|
apply();
|
||||||
|
};
|
||||||
|
head.addEventListener('click', toggle);
|
||||||
|
head.addEventListener('keydown', (e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); }
|
||||||
|
});
|
||||||
|
});
|
||||||
document.querySelectorAll('.adm-quickstart-section').forEach((sec) => {
|
document.querySelectorAll('.adm-quickstart-section').forEach((sec) => {
|
||||||
const head = sec.querySelector('.adm-quickstart-toggle');
|
const head = sec.querySelector('.adm-quickstart-toggle');
|
||||||
if (!head) return;
|
if (!head) return;
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ let _envState;
|
|||||||
let _sshCmd;
|
let _sshCmd;
|
||||||
let _getPort;
|
let _getPort;
|
||||||
let _sshPrefix;
|
let _sshPrefix;
|
||||||
let _serverByVal;
|
|
||||||
let _getPlatform;
|
let _getPlatform;
|
||||||
let _isWindows;
|
let _isWindows;
|
||||||
let _isMetal;
|
let _isMetal;
|
||||||
@@ -117,7 +116,6 @@ function _selectedServeTarget(panel) {
|
|||||||
host,
|
host,
|
||||||
port: host ? (_getPort(host) || server?.port || '') : '',
|
port: host ? (_getPort(host) || server?.port || '') : '',
|
||||||
venv,
|
venv,
|
||||||
platform: server?.platform || _envState.platform || '',
|
|
||||||
label,
|
label,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -2042,12 +2040,8 @@ async function _deleteCachedModel(repo, itemEl, skipConfirm = false, model = nul
|
|||||||
function _retryCachedModel(repo, m) {
|
function _retryCachedModel(repo, m) {
|
||||||
const payload = { repo_id: repo };
|
const payload = { repo_id: repo };
|
||||||
if (_envState.hfToken) payload.hf_token = _envState.hfToken;
|
if (_envState.hfToken) payload.hf_token = _envState.hfToken;
|
||||||
const _target = _selectedServeTarget(document.getElementById('cookbook-modal') || document);
|
if (_envState.remoteHost) { payload.remote_host = _envState.remoteHost; const _sp2 = _getPort(_envState.remoteHost); if (_sp2) payload.ssh_port = _sp2; }
|
||||||
if (_target.host) {
|
if (_envState.platform) payload.platform = _envState.platform;
|
||||||
payload.remote_host = _target.host;
|
|
||||||
if (_target.port) payload.ssh_port = _target.port;
|
|
||||||
}
|
|
||||||
if (_target.platform) payload.platform = _target.platform;
|
|
||||||
if (_isWindows()) {
|
if (_isWindows()) {
|
||||||
if (_envState.env === 'venv' && _envState.envPath) {
|
if (_envState.env === 'venv' && _envState.envPath) {
|
||||||
payload.env_prefix = '& ' + _psQuote(_envState.envPath.endsWith('\\Scripts\\Activate.ps1') ? _envState.envPath : _envState.envPath + '\\Scripts\\Activate.ps1');
|
payload.env_prefix = '& ' + _psQuote(_envState.envPath.endsWith('\\Scripts\\Activate.ps1') ? _envState.envPath : _envState.envPath + '\\Scripts\\Activate.ps1');
|
||||||
@@ -2312,7 +2306,6 @@ export function initServe(shared) {
|
|||||||
_sshCmd = shared._sshCmd;
|
_sshCmd = shared._sshCmd;
|
||||||
_getPort = shared._getPort;
|
_getPort = shared._getPort;
|
||||||
_sshPrefix = shared._sshPrefix;
|
_sshPrefix = shared._sshPrefix;
|
||||||
_serverByVal = shared._serverByVal;
|
|
||||||
_getPlatform = shared._getPlatform;
|
_getPlatform = shared._getPlatform;
|
||||||
_isWindows = shared._isWindows;
|
_isWindows = shared._isWindows;
|
||||||
_isMetal = shared._isMetal;
|
_isMetal = shared._isMetal;
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Regression test for routes/backup_routes.py import_data skills dedup.
|
||||||
|
|
||||||
|
BUG: the skills import block deduplicates against EVERY tenant's skills
|
||||||
|
(skills_manager.load_all()) instead of the importing user's own skills.
|
||||||
|
So importing your own backup silently drops any skill whose title (or id)
|
||||||
|
collides with ANOTHER user's skill — the same cross-tenant data-loss bug
|
||||||
|
that was already fixed for memories in the block just above.
|
||||||
|
"""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
import routes.backup_routes as backup_routes
|
||||||
|
from routes.backup_routes import setup_backup_routes
|
||||||
|
|
||||||
|
# require_admin / get_current_user are bound into routes.backup_routes at import
|
||||||
|
# time (`from x import name`). We patch them on that module directly per-test
|
||||||
|
# via monkeypatch — robust to import order and reverted at teardown. (Stubbing
|
||||||
|
# them through sys.modules only works if backup_routes has not been imported
|
||||||
|
# yet, which is not guaranteed in a full-suite run.)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeMemoryManager:
|
||||||
|
def __init__(self):
|
||||||
|
self.rows = []
|
||||||
|
|
||||||
|
def load(self, owner=None):
|
||||||
|
return [r for r in self.rows if r.get("owner") == owner]
|
||||||
|
|
||||||
|
def load_all(self):
|
||||||
|
return list(self.rows)
|
||||||
|
|
||||||
|
def save(self, rows):
|
||||||
|
self.rows = list(rows)
|
||||||
|
|
||||||
|
|
||||||
|
class FakePresetManager:
|
||||||
|
def get_all(self):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def save(self, d):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class FakeSkillsManager:
|
||||||
|
"""Mimics services.memory.skills: load_all() = all owners,
|
||||||
|
load(owner) = that owner's skills only."""
|
||||||
|
|
||||||
|
def __init__(self, rows):
|
||||||
|
self.rows = list(rows)
|
||||||
|
|
||||||
|
def load(self, owner=None):
|
||||||
|
return [s for s in self.rows if s.get("owner") == owner]
|
||||||
|
|
||||||
|
def load_all(self):
|
||||||
|
return list(self.rows)
|
||||||
|
|
||||||
|
def save(self, rows):
|
||||||
|
self.rows = list(rows)
|
||||||
|
|
||||||
|
def add_skill(self, title=None, name=None, owner=None, **kwargs):
|
||||||
|
# Mirrors services.memory.skills.add_skill: persists a SKILL.md row and
|
||||||
|
# returns its identity. source="user" skips auto-dedup, so no _deduped.
|
||||||
|
entry = {"id": f"new-{len(self.rows)}", "title": title, "name": name, "owner": owner}
|
||||||
|
self.rows.append(entry)
|
||||||
|
return {"name": name, "id": entry["id"]}
|
||||||
|
|
||||||
|
|
||||||
|
def _make_client(skills_mgr, monkeypatch):
|
||||||
|
# Bypass the admin gate and read the importer straight off request.state.
|
||||||
|
monkeypatch.setattr(backup_routes, "require_admin", lambda *a, **k: None)
|
||||||
|
monkeypatch.setattr(backup_routes, "get_current_user",
|
||||||
|
lambda req: getattr(req.state, "user", None))
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def _set_user(request: Request, call_next):
|
||||||
|
request.state.user = "alice"
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
|
router = setup_backup_routes(FakeMemoryManager(), FakePresetManager(), skills_mgr)
|
||||||
|
app.include_router(router)
|
||||||
|
return TestClient(app)
|
||||||
|
|
||||||
|
|
||||||
|
def test_import_skill_not_dropped_by_other_users_title_collision(monkeypatch):
|
||||||
|
# Bob already owns a skill titled "Deploy". Alice (the importer) has none.
|
||||||
|
skills_mgr = FakeSkillsManager([
|
||||||
|
{"id": "bob-1", "title": "Deploy", "name": "Deploy", "owner": "bob"},
|
||||||
|
])
|
||||||
|
client = _make_client(skills_mgr, monkeypatch)
|
||||||
|
|
||||||
|
# Alice imports HER OWN backup containing a skill also titled "Deploy".
|
||||||
|
payload = {
|
||||||
|
"skills": [
|
||||||
|
{"id": "alice-1", "title": "Deploy", "name": "Deploy"},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
resp = client.post("/api/import", json=payload)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
|
||||||
|
# Alice's skill must have been imported and assigned to her.
|
||||||
|
alice_skills = skills_mgr.load(owner="alice")
|
||||||
|
titles = {s["title"] for s in alice_skills}
|
||||||
|
assert "Deploy" in titles, (
|
||||||
|
"Alice's own 'Deploy' skill was silently dropped because Bob owns a "
|
||||||
|
"skill with the same title (cross-tenant dedup bug)."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(pytest.main([__file__, "-v"]))
|
||||||
@@ -22,10 +22,12 @@ from routes.cookbook_helpers import (
|
|||||||
_user_shell_path_bootstrap,
|
_user_shell_path_bootstrap,
|
||||||
_venv_safe_local_pip_install_cmd,
|
_venv_safe_local_pip_install_cmd,
|
||||||
_validate_gpus,
|
_validate_gpus,
|
||||||
|
_validate_local_dir,
|
||||||
_validate_repo_id,
|
_validate_repo_id,
|
||||||
_validate_serve_cmd,
|
_validate_serve_cmd,
|
||||||
_validate_serve_model_id,
|
_validate_serve_model_id,
|
||||||
_validate_ssh_port,
|
_validate_ssh_port,
|
||||||
|
_shell_path,
|
||||||
run_ssh_command_async,
|
run_ssh_command_async,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -110,6 +112,89 @@ def test_validate_ssh_port_rejects_shell_payload():
|
|||||||
assert _validate_ssh_port("2222") == "2222"
|
assert _validate_ssh_port("2222") == "2222"
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_local_dir_accepts_external_drive_paths_with_spaces():
|
||||||
|
path = "/Volumes/T7 2TB/AI Models/llamacpp"
|
||||||
|
|
||||||
|
assert _validate_local_dir(path) == path
|
||||||
|
assert _validate_local_dir(f'"{path}"') == path
|
||||||
|
assert _shell_path(f"{path}/Qwen3-8B") == '"/Volumes/T7 2TB/AI Models/llamacpp/Qwen3-8B"'
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_local_dir_accepts_windows_drive_paths_with_spaces():
|
||||||
|
backslash_path = r"D:\AI Models\llamacpp"
|
||||||
|
slash_path = "D:/AI Models/llamacpp"
|
||||||
|
|
||||||
|
assert _validate_local_dir(backslash_path) == backslash_path
|
||||||
|
assert _validate_local_dir(f"'{backslash_path}'") == backslash_path
|
||||||
|
assert _validate_local_dir(slash_path) == slash_path
|
||||||
|
assert _shell_path(backslash_path + r"\Qwen3-8B") == '"D:\\AI Models\\llamacpp\\Qwen3-8B"'
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_local_dir_still_rejects_shell_metacharacters():
|
||||||
|
for path in [
|
||||||
|
"/Volumes/T7 2TB/AI Models; touch /tmp/pwned",
|
||||||
|
"/Volumes/T7 2TB/AI Models/$(touch pwned)",
|
||||||
|
"/Volumes/T7 2TB/AI Models/`touch pwned`",
|
||||||
|
"/Volumes/T7 2TB/AI Models/model\nnext",
|
||||||
|
]:
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
_validate_local_dir(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_local_dir_rejects_windows_shell_metacharacters():
|
||||||
|
for path in [
|
||||||
|
r"D:\AI Models\llamacpp; touch C:\pwned",
|
||||||
|
r"D:\AI Models\llamacpp\$(touch pwned)",
|
||||||
|
r"D:\AI Models\llamacpp\`touch pwned`",
|
||||||
|
"D:\\AI Models\\llamacpp\nnext",
|
||||||
|
]:
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
_validate_local_dir(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_local_dir_accepts_non_ascii_unicode_paths():
|
||||||
|
# Folder names are routinely non-ASCII on localized systems; the validator
|
||||||
|
# must accept them the same way it accepts spaces (see issue: spaces AND
|
||||||
|
# non-ASCII chars were both rejected by the old ASCII-only allowlist).
|
||||||
|
for path in [
|
||||||
|
"/Volumes/Модели/llamacpp", # Cyrillic (POSIX / external drive)
|
||||||
|
"/home/josé/models", # accented Latin
|
||||||
|
"/Volumes/モデル/llm", # CJK
|
||||||
|
r"D:\AI Models\Модели", # Cyrillic (Windows drive path)
|
||||||
|
]:
|
||||||
|
assert _validate_local_dir(path) == path
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_local_dir_rejects_metacharacters_in_unicode_paths():
|
||||||
|
# Widening the allowlist to Unicode must not reopen the injection surface:
|
||||||
|
# shell metacharacters stay rejected even alongside non-ASCII segments.
|
||||||
|
for path in [
|
||||||
|
"/Volumes/Модели; touch /tmp/pwned",
|
||||||
|
"/Volumes/Модели/$(touch pwned)",
|
||||||
|
"/Volumes/Модели/`touch pwned`",
|
||||||
|
"/Volumes/Модели/a|b",
|
||||||
|
"/Volumes/Модели\nnext",
|
||||||
|
r"D:\Модели\llamacpp & calc.exe",
|
||||||
|
]:
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
_validate_local_dir(path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_local_dir_rejects_leading_dash_segments():
|
||||||
|
# A path segment starting with '-' could be parsed as a CLI option by hf/etc.
|
||||||
|
# (option injection) even when quoted, since quoting doesn't stop a value from
|
||||||
|
# being read as a flag. The validator must reject it on every platform.
|
||||||
|
for path in [
|
||||||
|
"/models/-rf",
|
||||||
|
"/models/-rf/llamacpp",
|
||||||
|
"/-oStrictHostKeyChecking=no",
|
||||||
|
r"D:\models\-rf",
|
||||||
|
"D:/models/-rf",
|
||||||
|
]:
|
||||||
|
with pytest.raises(HTTPException):
|
||||||
|
_validate_local_dir(path)
|
||||||
|
|
||||||
|
|
||||||
def test_validate_gpus_accepts_indexes_only():
|
def test_validate_gpus_accepts_indexes_only():
|
||||||
assert _validate_gpus("0,1,2") == "0,1,2"
|
assert _validate_gpus("0,1,2") == "0,1,2"
|
||||||
with pytest.raises(HTTPException):
|
with pytest.raises(HTTPException):
|
||||||
|
|||||||
@@ -0,0 +1,165 @@
|
|||||||
|
"""Tests for Ollama /v1 thinking-suppression helpers.
|
||||||
|
|
||||||
|
Covers:
|
||||||
|
- _is_ollama_openai_compat_url: URL classification (local host + /v1 path)
|
||||||
|
- think: false is injected into the payload for Ollama /v1 thinking models
|
||||||
|
- think: false is NOT injected for non-thinking models or non-Ollama /v1 endpoints
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
|
||||||
|
from src import llm_core
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Fake HTTP client — captures the outgoing payload without network I/O
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class _FakeResp:
|
||||||
|
status_code = 200
|
||||||
|
|
||||||
|
async def aiter_lines(self):
|
||||||
|
# Yield a minimal done event so stream_llm exits cleanly
|
||||||
|
yield json.dumps({"choices": [{"delta": {"content": "ok"}, "finish_reason": "stop"}]})
|
||||||
|
yield "data: [DONE]"
|
||||||
|
|
||||||
|
async def aread(self):
|
||||||
|
return b""
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeStreamCtx:
|
||||||
|
def __init__(self, captured):
|
||||||
|
self._captured = captured
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return _FakeResp()
|
||||||
|
|
||||||
|
async def __aexit__(self, *a):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
"""Minimal stand-in for httpx.AsyncClient that captures request payload."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.captured_payload = {}
|
||||||
|
|
||||||
|
def stream(self, method, url, **kw):
|
||||||
|
self.captured_payload = kw.get("json") or {}
|
||||||
|
return _FakeStreamCtx(self.captured_payload)
|
||||||
|
|
||||||
|
|
||||||
|
def _capture_payload(monkeypatch, url, model):
|
||||||
|
"""Run stream_llm, intercept the HTTP payload, and return it."""
|
||||||
|
client = _FakeClient()
|
||||||
|
monkeypatch.setattr(llm_core, "_get_http_client", lambda: client)
|
||||||
|
monkeypatch.setattr(llm_core, "_is_host_dead", lambda u: False)
|
||||||
|
monkeypatch.setattr(llm_core, "note_model_activity", lambda *a, **k: None)
|
||||||
|
monkeypatch.setattr(llm_core, "_clear_host_dead", lambda *a, **k: None)
|
||||||
|
monkeypatch.setattr(llm_core, "get_context_length", lambda u, m: 32768)
|
||||||
|
|
||||||
|
async def run():
|
||||||
|
return [c async for c in llm_core.stream_llm(
|
||||||
|
url, model, [{"role": "user", "content": "hi"}],
|
||||||
|
)]
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
return client.captured_payload
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# _is_ollama_openai_compat_url — pure function, no I/O
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class TestIsOllamaOpenAICompatUrl:
|
||||||
|
"""Unit tests for the URL classifier that gates think-suppression."""
|
||||||
|
|
||||||
|
# Positive cases — should be True
|
||||||
|
def test_default_port_v1_root(self):
|
||||||
|
assert llm_core._is_ollama_openai_compat_url("http://127.0.0.1:11434/v1")
|
||||||
|
|
||||||
|
def test_default_port_chat_completions(self):
|
||||||
|
assert llm_core._is_ollama_openai_compat_url("http://127.0.0.1:11434/v1/chat/completions")
|
||||||
|
|
||||||
|
def test_localhost_default_port(self):
|
||||||
|
assert llm_core._is_ollama_openai_compat_url("http://localhost:11434/v1")
|
||||||
|
|
||||||
|
def test_localhost_default_port_with_path(self):
|
||||||
|
assert llm_core._is_ollama_openai_compat_url("http://localhost:11434/v1/chat/completions")
|
||||||
|
|
||||||
|
def test_loopback_ipv6(self):
|
||||||
|
# IPv6 addresses in URLs require square brackets per RFC 3986
|
||||||
|
assert llm_core._is_ollama_openai_compat_url("http://[::1]:11434/v1")
|
||||||
|
|
||||||
|
def test_any_local_non_default_port(self):
|
||||||
|
"""Localhost on a non-default port (custom OLLAMA_HOST) must also match."""
|
||||||
|
assert llm_core._is_ollama_openai_compat_url("http://127.0.0.1:11435/v1")
|
||||||
|
|
||||||
|
def test_localhost_non_default_port(self):
|
||||||
|
assert llm_core._is_ollama_openai_compat_url("http://localhost:8080/v1/chat/completions")
|
||||||
|
|
||||||
|
def test_zero_dot_zero_host(self):
|
||||||
|
assert llm_core._is_ollama_openai_compat_url("http://0.0.0.0:11434/v1")
|
||||||
|
|
||||||
|
# Negative cases — should be False
|
||||||
|
def test_openai_api_v1(self):
|
||||||
|
"""Real OpenAI endpoint must never match, even though path is /v1."""
|
||||||
|
assert not llm_core._is_ollama_openai_compat_url("https://api.openai.com/v1")
|
||||||
|
|
||||||
|
def test_openai_chat_completions(self):
|
||||||
|
assert not llm_core._is_ollama_openai_compat_url("https://api.openai.com/v1/chat/completions")
|
||||||
|
|
||||||
|
def test_ollama_native_api_path(self):
|
||||||
|
"""The native /api path is a different surface and must not match /v1."""
|
||||||
|
assert not llm_core._is_ollama_openai_compat_url("http://localhost:11434/api")
|
||||||
|
|
||||||
|
def test_ollama_native_api_chat(self):
|
||||||
|
assert not llm_core._is_ollama_openai_compat_url("http://localhost:11434/api/chat")
|
||||||
|
|
||||||
|
def test_remote_openrouter(self):
|
||||||
|
assert not llm_core._is_ollama_openai_compat_url("https://openrouter.ai/api/v1")
|
||||||
|
|
||||||
|
def test_empty_string(self):
|
||||||
|
assert not llm_core._is_ollama_openai_compat_url("")
|
||||||
|
|
||||||
|
def test_none_like_empty(self):
|
||||||
|
assert not llm_core._is_ollama_openai_compat_url(None) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Payload injection — think: false only when both conditions hold
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class TestThinkSuppression:
|
||||||
|
"""Assert think:false is present/absent in the outgoing HTTP payload."""
|
||||||
|
|
||||||
|
def test_think_false_for_ollama_v1_thinking_model(self, monkeypatch):
|
||||||
|
"""think:false must be set for qwen3 on Ollama /v1."""
|
||||||
|
payload = _capture_payload(
|
||||||
|
monkeypatch, "http://127.0.0.1:11434/v1/chat/completions", "qwen3:14b"
|
||||||
|
)
|
||||||
|
assert payload.get("think") is False
|
||||||
|
|
||||||
|
def test_no_think_for_ollama_v1_non_thinking_model(self, monkeypatch):
|
||||||
|
"""think must NOT be set for a plain (non-thinking) model on Ollama /v1."""
|
||||||
|
payload = _capture_payload(
|
||||||
|
monkeypatch, "http://127.0.0.1:11434/v1/chat/completions", "llama3.2:3b"
|
||||||
|
)
|
||||||
|
assert "think" not in payload
|
||||||
|
|
||||||
|
def test_no_think_for_openai_endpoint_with_thinking_model_name(self, monkeypatch):
|
||||||
|
"""think must NOT leak to a real OpenAI endpoint even if the model name
|
||||||
|
matches a thinking pattern — the URL guard is what matters."""
|
||||||
|
payload = _capture_payload(
|
||||||
|
monkeypatch, "https://api.openai.com/v1/chat/completions", "qwen3:14b"
|
||||||
|
)
|
||||||
|
assert "think" not in payload
|
||||||
|
|
||||||
|
def test_think_false_for_non_default_port_thinking_model(self, monkeypatch):
|
||||||
|
"""Custom-port localhost Ollama (e.g. OLLAMA_HOST=0.0.0.0:11435) must
|
||||||
|
also receive think:false — this is the regression guarded by the
|
||||||
|
host-set check added in this fix."""
|
||||||
|
payload = _capture_payload(
|
||||||
|
monkeypatch, "http://127.0.0.1:11435/v1/chat/completions", "qwen3:14b"
|
||||||
|
)
|
||||||
|
assert payload.get("think") is False
|
||||||
@@ -238,36 +238,6 @@ def test_guide_only_blocks_later_round_document_streaming(monkeypatch):
|
|||||||
assert not any(event.get("type") == "doc_stream_delta" for event in events)
|
assert not any(event.get("type") == "doc_stream_delta" for event in events)
|
||||||
|
|
||||||
|
|
||||||
def test_guide_only_directive_dominates_workspace_prompt(monkeypatch):
|
|
||||||
_patch_loop_basics(monkeypatch)
|
|
||||||
system_prompts = []
|
|
||||||
|
|
||||||
async def _fake_stream(_candidates, messages, **kwargs):
|
|
||||||
system_prompts.append(messages[0]["content"])
|
|
||||||
yield _delta_chunk("ok")
|
|
||||||
yield "data: [DONE]\n\n"
|
|
||||||
|
|
||||||
monkeypatch.setattr(al, "stream_llm_with_fallback", _fake_stream, raising=False)
|
|
||||||
policy = build_effective_tool_policy(last_user_message="Do not use tools.")
|
|
||||||
|
|
||||||
_collect(
|
|
||||||
al.stream_agent_loop(
|
|
||||||
"http://local.test/v1",
|
|
||||||
"local-model",
|
|
||||||
[{"role": "user", "content": "Do not use tools."}],
|
|
||||||
max_rounds=1,
|
|
||||||
relevant_tools={"bash"},
|
|
||||||
tool_policy=policy,
|
|
||||||
workspace="/tmp/project",
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
assert system_prompts
|
|
||||||
assert system_prompts[0].startswith("## GUIDE-ONLY MODE")
|
|
||||||
assert "ACTIVE WORKSPACE" not in system_prompts[0]
|
|
||||||
assert "ALWAYS start by exploring" not in system_prompts[0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_guide_only_skips_intent_without_action_nudge(monkeypatch):
|
def test_guide_only_skips_intent_without_action_nudge(monkeypatch):
|
||||||
_patch_loop_basics(monkeypatch)
|
_patch_loop_basics(monkeypatch)
|
||||||
|
|
||||||
|
|||||||
@@ -1,107 +0,0 @@
|
|||||||
"""Workspace confinement: file tools are hard-bounded to the workspace folder
|
|
||||||
(layered on upstream's sensitive-path policy); bash runs with cwd there."""
|
|
||||||
import os
|
|
||||||
import tempfile
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from src.tool_execution import _resolve_tool_path_in_workspace, _direct_fallback
|
|
||||||
|
|
||||||
|
|
||||||
def test_workspace_resolver_confines():
|
|
||||||
ws = tempfile.mkdtemp()
|
|
||||||
open(os.path.join(ws, "a.txt"), "w").write("x")
|
|
||||||
real = os.path.realpath(os.path.join(ws, "a.txt"))
|
|
||||||
# relative path resolves under the workspace
|
|
||||||
assert _resolve_tool_path_in_workspace(ws, "a.txt") == real
|
|
||||||
# absolute path inside the workspace is allowed
|
|
||||||
assert _resolve_tool_path_in_workspace(ws, os.path.join(ws, "a.txt")) == real
|
|
||||||
# absolute path outside is rejected (sibling temp dir, portable across OSes)
|
|
||||||
outside = tempfile.mkdtemp()
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
_resolve_tool_path_in_workspace(ws, os.path.join(outside, "x.txt"))
|
|
||||||
# parent-escape is rejected
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
_resolve_tool_path_in_workspace(ws, os.path.join("..", "..", "escape.txt"))
|
|
||||||
|
|
||||||
|
|
||||||
def test_workspace_resolver_blocks_sensitive():
|
|
||||||
"""Upstream's sensitive-file deny list still applies inside the workspace."""
|
|
||||||
ws = tempfile.mkdtemp()
|
|
||||||
os.makedirs(os.path.join(ws, ".ssh"), exist_ok=True)
|
|
||||||
with pytest.raises(ValueError):
|
|
||||||
_resolve_tool_path_in_workspace(ws, ".ssh/authorized_keys")
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_read_write_confined_in_workspace():
|
|
||||||
ws = tempfile.mkdtemp()
|
|
||||||
# Write inside the workspace (relative path) succeeds.
|
|
||||||
res = await _direct_fallback("write_file", "note.txt\nhello", workspace=ws)
|
|
||||||
assert res["exit_code"] == 0
|
|
||||||
assert os.path.isfile(os.path.join(ws, "note.txt"))
|
|
||||||
# Read it back.
|
|
||||||
res = await _direct_fallback("read_file", "note.txt", workspace=ws)
|
|
||||||
assert res["exit_code"] == 0 and res["output"] == "hello"
|
|
||||||
# Reading outside the workspace is rejected (sibling temp dir, portable).
|
|
||||||
outside = tempfile.mkdtemp()
|
|
||||||
outside_file = os.path.join(outside, "secret.txt")
|
|
||||||
open(outside_file, "w").write("nope")
|
|
||||||
res = await _direct_fallback("read_file", outside_file, workspace=ws)
|
|
||||||
assert res["exit_code"] == 1 and "outside the workspace" in res["error"]
|
|
||||||
# Writing outside is rejected (file must not be created).
|
|
||||||
escape = os.path.join(outside, "_ws_escape.txt")
|
|
||||||
res = await _direct_fallback("write_file", f"{escape}\nx", workspace=ws)
|
|
||||||
assert res["exit_code"] == 1 and "outside the workspace" in res["error"]
|
|
||||||
assert not os.path.exists(escape)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_subprocess_runs_with_workspace_cwd():
|
|
||||||
"""bash/python subprocesses run with cwd set to the workspace. Use the
|
|
||||||
python tool for an OS-agnostic cwd probe (Windows cmd has no `pwd`)."""
|
|
||||||
ws = tempfile.mkdtemp()
|
|
||||||
res = await _direct_fallback("python", "import os; print(os.getcwd())", workspace=ws)
|
|
||||||
assert res["exit_code"] == 0
|
|
||||||
assert os.path.realpath(res["output"].strip()) == os.path.realpath(ws)
|
|
||||||
|
|
||||||
|
|
||||||
# --- Tools that landed after this PR, now wired into the workspace -----------
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_edit_file_confined_in_workspace():
|
|
||||||
import json
|
|
||||||
from src.tool_execution import _do_edit_file
|
|
||||||
ws = tempfile.mkdtemp()
|
|
||||||
open(os.path.join(ws, "f.txt"), "w").write("foo bar")
|
|
||||||
# Edit inside the workspace succeeds.
|
|
||||||
res = await _do_edit_file(json.dumps(
|
|
||||||
{"path": "f.txt", "old_string": "foo", "new_string": "baz"}), workspace=ws)
|
|
||||||
assert res["exit_code"] == 0
|
|
||||||
assert open(os.path.join(ws, "f.txt")).read() == "baz bar"
|
|
||||||
# Editing outside the workspace is rejected (sibling temp dir, portable).
|
|
||||||
outside = tempfile.mkdtemp()
|
|
||||||
outside_file = os.path.join(outside, "f.txt")
|
|
||||||
open(outside_file, "w").write("a")
|
|
||||||
res = await _do_edit_file(json.dumps(
|
|
||||||
{"path": outside_file, "old_string": "a", "new_string": "b"}), workspace=ws)
|
|
||||||
assert res["exit_code"] == 1 and "outside the workspace" in res["error"]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_grep_and_ls_confined_in_workspace():
|
|
||||||
import json
|
|
||||||
ws = tempfile.mkdtemp()
|
|
||||||
open(os.path.join(ws, "doc.txt"), "w").write("hello workspace\n")
|
|
||||||
# grep with no path searches the workspace root and finds the match.
|
|
||||||
res = await _direct_fallback("grep", json.dumps({"pattern": "hello"}), workspace=ws)
|
|
||||||
assert res["exit_code"] == 0 and "doc.txt" in res["output"]
|
|
||||||
# grep pointed outside the workspace is rejected (sibling temp dir, portable).
|
|
||||||
outside = tempfile.mkdtemp()
|
|
||||||
res = await _direct_fallback("grep", json.dumps({"pattern": "x", "path": outside}), workspace=ws)
|
|
||||||
assert res["exit_code"] == 1 and "outside the workspace" in res["error"]
|
|
||||||
# ls of the workspace lists its files; ls outside is rejected.
|
|
||||||
res = await _direct_fallback("ls", "", workspace=ws)
|
|
||||||
assert res["exit_code"] == 0 and "doc.txt" in res["output"]
|
|
||||||
res = await _direct_fallback("ls", outside, workspace=ws)
|
|
||||||
assert res["exit_code"] == 1 and "outside the workspace" in res["error"]
|
|
||||||
Reference in New Issue
Block a user