diff --git a/bun.lock b/bun.lock index 7aee71829a..a16edafe29 100644 --- a/bun.lock +++ b/bun.lock @@ -12,7 +12,7 @@ "@corbits/codex-provider": "github:corbitsdev/corbits-codex-provider#a1f475f341261c05fa8dade0c82f1246c175b5b3", "@corbits/connections": "workspace:*", "@corbits/mailbox": "github:corbitsdev/corbits-mailbox#e85b81e4a2e0cc318dd33a4f0f92337b6fac7f38", - "@corbits/ollama-adapter": "workspace:*", + "@corbits/ollama-adapter": "github:corbitsdev/corbits-ollama-adapter#0387eb17bee5ac87530e9c48bb3bffd9a6998ded", "@corbits/webhook-triggers": "workspace:*", "@corbits/xai-provider": "github:corbitsdev/corbits-xai-provider#9f2d4bac40ea075df092fef807404a13c638cf14", "@intx/crypto": "workspace:*", @@ -352,7 +352,7 @@ "name": "@corbits/inference-catalog", "version": "0.1.0", "dependencies": { - "@corbits/ollama-adapter": "0.0.2", + "@corbits/ollama-adapter": "github:corbitsdev/corbits-ollama-adapter#0387eb17bee5ac87530e9c48bb3bffd9a6998ded", "@intx/inference-catalog": "0.3.0", "arktype": "catalog:", }, @@ -376,21 +376,6 @@ "typescript": "catalog:", }, }, - "packages/ollama-adapter": { - "name": "@corbits/ollama-adapter", - "version": "0.0.2", - "dependencies": { - "arktype": "catalog:", - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:", - }, - "peerDependencies": { - "@intx/inference": "0.3.0", - "@intx/types": "0.3.0", - }, - }, "packages/tool-registry-publish": { "name": "@corbits/tool-registry-publish", "version": "0.0.1", @@ -1180,7 +1165,7 @@ "@corbits/oauth-core": ["@corbits/oauth-core@github:corbitsdev/corbits-oauth-core#e1e69e6", { "dependencies": { "arktype": "2.2.3" } }, "corbitsdev-corbits-oauth-core-e1e69e6", "sha512-wUrD73iVyk/Dtb4yRn3hCh6N8syfsEvAkRz4XYqT0FIB3sYDSMYEWHcDMJx9nq64my/HBOeN1J6PHIOtpjhtPg=="], - "@corbits/ollama-adapter": ["@corbits/ollama-adapter@workspace:packages/ollama-adapter"], + "@corbits/ollama-adapter": ["@corbits/ollama-adapter@github:corbitsdev/corbits-ollama-adapter#0387eb1", { "dependencies": { "arktype": "2.2.3" }, "peerDependencies": { "@intx/inference": ">=0.3.0", "@intx/types": ">=0.3.0" } }, "corbitsdev-corbits-ollama-adapter-0387eb1", "sha512-O1dl5lSwWzNGJibQLlpYDFKJZWpstgHX519bl8oe1ALL/KHszT/tBDlpsD9jN3hmQD3jV2L1jNwvOwLOBLtpyw=="], "@corbits/openai-responses": ["@corbits/openai-responses@github:corbitsdev/corbits-openai-responses#7efe000", { "dependencies": { "arktype": "2.2.3" }, "peerDependencies": { "@intx/inference": ">=0.3.0", "@intx/types": ">=0.3.0" } }, "corbitsdev-corbits-openai-responses-7efe000", "sha512-pH6C8T1WDJjqM+YbnQpofd7HgP5krEj48JCCQK16KI98a6kaz+gffpgdOdQpU3aNVZnFlyADXod1Z4tqUG/3ww=="], diff --git a/package.json b/package.json index 863accf74b..f3ede8687b 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "devDependencies": { "@corbits/artifacts": "github:corbitsdev/corbits-artifacts#5309a15d4aa504f132c54b4da08bb672b4903873", "@corbits/codex-provider": "github:corbitsdev/corbits-codex-provider#a1f475f341261c05fa8dade0c82f1246c175b5b3", - "@corbits/ollama-adapter": "workspace:*", + "@corbits/ollama-adapter": "github:corbitsdev/corbits-ollama-adapter#0387eb17bee5ac87530e9c48bb3bffd9a6998ded", "@corbits/xai-provider": "github:corbitsdev/corbits-xai-provider#9f2d4bac40ea075df092fef807404a13c638cf14", "@intx/db": "workspace:*", "@intx/crypto": "workspace:*", diff --git a/packages/inference-catalog/package.json b/packages/inference-catalog/package.json index 64ab148911..1281fe920d 100644 --- a/packages/inference-catalog/package.json +++ b/packages/inference-catalog/package.json @@ -32,7 +32,7 @@ "test": "bun test" }, "dependencies": { - "@corbits/ollama-adapter": "0.0.2", + "@corbits/ollama-adapter": "github:corbitsdev/corbits-ollama-adapter#0387eb17bee5ac87530e9c48bb3bffd9a6998ded", "@intx/inference-catalog": "0.3.0", "arktype": "catalog:" }, diff --git a/packages/ollama-adapter/LICENSE b/packages/ollama-adapter/LICENSE deleted file mode 100644 index 173c3a21d0..0000000000 --- a/packages/ollama-adapter/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - -Version 2.1, February 1999 - -Copyright (C) 1991, 1999 Free Software Foundation, Inc. -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] - -Preamble - -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. - -This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. - -To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - -Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. - -When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. - -We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. - -For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. - -Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - -GNU LESSER GENERAL PUBLIC LICENSE -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". - -A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. - -The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) - -"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - -1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. - -(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - -Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of the Library into a program that is not a library. - -4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. - -5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. - -However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. - -When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - -6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - - a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. - - e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. - -For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. - -It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - -7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. - - b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. - -8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. - -10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - -11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - -14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -NO WARRANTY - -15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -END OF TERMS AND CONDITIONS - -How to Apply These Terms to Your New Libraries - -If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). - -To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library's name and an idea of what it does. - Copyright (C) year name of author - - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; version 2.1 of the License. - - This library 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 Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: - -Yoyodyne, Inc., hereby disclaims all copyright interest in -the library `Frob' (a library for tweaking knobs) written -by James Random Hacker. - -signature of Ty Coon, 1 April 1990 -Ty Coon, President of Vice -That's all there is to it! diff --git a/packages/ollama-adapter/README.md b/packages/ollama-adapter/README.md deleted file mode 100644 index aeab759ad1..0000000000 --- a/packages/ollama-adapter/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# @corbits/ollama-adapter - -A custom Interchange inference adapter for the `ollama` provider key -(Ollama's `openai-compatible` endpoint, `/v1`). It wraps the built-in -OpenAI Chat Completions adapter — reusing its message marshaling, SSE -parsing, and retry/pacing header extraction unchanged — and adds one -thing: operator-configured overrides for context window, max output -tokens, and reasoning effort, applied to every built request body. - -## Why - -Ollama's `/v1/chat/completions` endpoint has no OpenAI-shaped field for -context window (`num_ctx`); it only takes it through the endpoint's -`options` passthrough object, exactly like the native `/api/chat` -surface. Without a custom adapter, `num_ctx` has nowhere to go and is -silently ignored. `max_tokens` (mapped internally to Ollama's -`num_predict`) and `reasoning_effort` (recognized for `gpt-oss` models) -both ride through fields the built-in adapter already sets, so this -adapter just lets an operator override them. - -## Activating it - -Set the sidecar's `SIDECAR_ADAPTER_MANIFEST` env var to a JSON array -naming this package for the `ollama` provider key: - -``` -SIDECAR_ADAPTER_MANIFEST=[{"provider":"ollama","specifier":"@corbits/ollama-adapter","export":"createOllamaAdapter"}] -``` - -`@corbits/ollama-adapter` must be installed in the sidecar's workspace — -the manifest names an already-installed module, it never carries code of -its own. See the root `.env.example` for the full `SIDECAR_ADAPTER_MANIFEST` -contract. - -## Configuring overrides - -Overrides ride in as the adapter's `quirks` argument, which -`loadAdapterRegistry` resolves from the matching `InferenceSource.quirks` -bag (the per-catalog-entry config an operator sets on a connected -provider's model). The shape: - -```jsonc -{ - // Applies to every model resolved through this source unless a - // perModel entry below overrides a field. - "default": { - "numCtx": 8192, - "maxOutputTokens": 4096, - "reasoningEffort": "medium", - }, - "perModel": { - "gpt-oss:20b": { "numCtx": 32768, "reasoningEffort": "high" }, - }, -} -``` - -- `numCtx` — positive integer, sets `options.num_ctx` on the request body. -- `maxOutputTokens` — positive integer, overrides whichever max-tokens - field the built-in adapter set (`max_tokens` or `max_completion_tokens`). -- `reasoningEffort` — `"low" | "medium" | "high"`, sets `reasoning_effort`. - -A per-model entry wins field-by-field over `default`; an unconfigured -field falls through to the built-in adapter's own behavior (no override). -With no `quirks` at all, the built request body is byte-for-byte -equivalent to the built-in OpenAI adapter's. diff --git a/packages/ollama-adapter/package.json b/packages/ollama-adapter/package.json deleted file mode 100644 index 7312552d2e..0000000000 --- a/packages/ollama-adapter/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "@corbits/ollama-adapter", - "version": "0.0.2", - "description": "Custom Interchange inference adapter for the Ollama openai-compatible provider: operator-configured context-window (num_ctx), max-output-token, and reasoning-effort overrides, general or per model, wrapping the built-in OpenAI adapter's request/response handling rather than reimplementing it.", - "license": "LGPL-2.1-only", - "repository": { - "type": "git", - "url": "https://github.com/corbitsdev/workbench.git", - "directory": "packages/ollama-adapter" - }, - "files": [ - "src", - "LICENSE", - "README.md" - ], - "type": "module", - "exports": { - ".": "./src/index.ts", - "./overrides": "./src/overrides.ts" - }, - "publishConfig": { - "access": "public" - }, - "scripts": { - "typecheck": "tsc --noEmit", - "test": "bun test" - }, - "dependencies": { - "arktype": "catalog:" - }, - "devDependencies": { - "@types/bun": "catalog:", - "typescript": "catalog:" - }, - "peerDependencies": { - "@intx/inference": "0.3.0", - "@intx/types": "0.3.0" - } -} diff --git a/packages/ollama-adapter/src/adapter.test.ts b/packages/ollama-adapter/src/adapter.test.ts deleted file mode 100644 index 6c3cee8371..0000000000 --- a/packages/ollama-adapter/src/adapter.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { createOpenAIAdapter } from "@intx/inference/providers"; -import type { LastCycleSource } from "@intx/types/runtime"; -import type { - ConversationTurn, - InferenceEvent, - InferenceOptions, - ToolDefinition, -} from "@intx/types/runtime"; - -import { createOllamaAdapter } from "./adapter"; - -const source: LastCycleSource = { - sourceId: "ollama-test", - provider: "ollama", - model: "gpt-oss:20b", -}; - -const messages: ConversationTurn[] = [ - { - role: "user", - content: [{ type: "text", text: "hello" }], - timestamp: 0, - }, -]; - -const options: InferenceOptions = {}; - -const memorySearchTool: ToolDefinition = { - name: "memory_search", - description: "Search firm memory", - inputSchema: { type: "object" }, -}; - -const CL_7186_PAYLOAD = '{"name":"memory_search","parameters":{"query":"this person"}}'; - -function bodyOf(built: { body: string }): Record { - return JSON.parse(built.body) as Record; -} - -function toolStarts(events: readonly InferenceEvent[]): InferenceEvent[] { - return events.filter((event) => event.type === "inference.tool_call.start"); -} - -function textDeltas(events: readonly InferenceEvent[]): InferenceEvent[] { - return events.filter((event) => event.type === "inference.text.delta"); -} - -function argumentFragments(events: readonly InferenceEvent[]): string { - return events - .filter((event) => event.type === "inference.tool_call.delta") - .map((event) => (event.data as { argumentFragment: string }).argumentFragment) - .join(""); -} - -function expectSharedToolCallId(events: readonly InferenceEvent[]): void { - const ids = events - .filter( - (event) => - event.type === "inference.tool_call.start" || event.type === "inference.tool_call.delta", - ) - .map((event) => (event.data as { callId: string }).callId); - expect(ids.length).toBeGreaterThan(0); - expect(new Set(ids)).toEqual(new Set(["ollama-inline-0"])); -} - -describe("createOllamaAdapter", () => { - test("no override configured leaves the body equivalent to the built-in adapter's", () => { - const wrapped = createOllamaAdapter(source, undefined); - const inner = createOpenAIAdapter(source); - const wrappedBuilt = wrapped.buildRequest(messages, "gpt-oss:20b", options); - const innerBuilt = inner.buildRequest(messages, "gpt-oss:20b", options); - const wrappedBody = bodyOf(wrappedBuilt); - const { stream_options: _streamOptions, ...rest } = wrappedBody; - expect(rest).toEqual(bodyOf(innerBuilt)); - expect(wrappedBuilt.url).toBe(innerBuilt.url); - expect(wrappedBuilt.headers).toEqual(innerBuilt.headers); - }); - - test("a configured num_ctx and max output tokens appear in the built request body", () => { - const wrapped = createOllamaAdapter(source, { - default: { numCtx: 32768, maxOutputTokens: 2048 }, - }); - const built = wrapped.buildRequest(messages, "gpt-oss:20b", options); - const body = bodyOf(built); - expect(body["options"]).toEqual({ num_ctx: 32768 }); - expect(body["max_tokens"]).toBe(2048); - }); - - test("a configured reasoning effort appears in the built request body", () => { - const wrapped = createOllamaAdapter(source, { - default: { reasoningEffort: "high" }, - }); - const built = wrapped.buildRequest(messages, "gpt-oss:20b", options); - expect(bodyOf(built)["reasoning_effort"]).toBe("high"); - }); - - test("a per-model override beats the general default", () => { - const wrapped = createOllamaAdapter(source, { - default: { numCtx: 8192 }, - perModel: { "gpt-oss:20b": { numCtx: 65536 } }, - }); - const forOverriddenModel = bodyOf(wrapped.buildRequest(messages, "gpt-oss:20b", options)); - const forOtherModel = bodyOf(wrapped.buildRequest(messages, "qwen3.8:27b", options)); - expect(forOverriddenModel["options"]).toEqual({ num_ctx: 65536 }); - expect(forOtherModel["options"]).toEqual({ num_ctx: 8192 }); - }); - - test("preserves the built-in adapter's response parsing and header extractors", () => { - const wrapped = createOllamaAdapter(source, undefined); - const chunk = JSON.stringify({ - choices: [{ delta: { content: "hi" } }], - }); - expect(wrapped.parseResponse(chunk)).toEqual([ - { - type: "inference.text.delta", - seq: 0, - data: { token: "hi", partial: { text: "" }, index: 0 }, - }, - ]); - expect(typeof wrapped.extractRetryAfterMs).toBe("function"); - expect(typeof wrapped.extractPacingDelayMs).toBe("function"); - }); - - test("parseResponse salvages declared inline memory_search JSON into a tool call", () => { - const wrapped = createOllamaAdapter(source, undefined); - wrapped.buildRequest(messages, "gpt-oss:20b", { - tools: [memorySearchTool], - }); - const events = [ - ...wrapped.parseResponse( - JSON.stringify({ - choices: [{ delta: { content: CL_7186_PAYLOAD } }], - }), - ), - ...wrapped.parseResponse( - JSON.stringify({ - choices: [{ delta: {}, finish_reason: "stop" }], - }), - ), - ]; - expect(textDeltas(events)).toEqual([]); - expect((toolStarts(events)[0]?.data as { name: string }).name).toBe("memory_search"); - expectSharedToolCallId(events); - expect(JSON.parse(argumentFragments(events))).toEqual({ - query: "this person", - }); - }); - - test("parseJSONResponse salvages declared inline memory_search JSON into a tool call", () => { - const wrapped = createOllamaAdapter(source, undefined); - wrapped.buildRequest(messages, "gpt-oss:20b", { - tools: [memorySearchTool], - }); - const events = wrapped.parseJSONResponse( - JSON.stringify({ - object: "chat.completion", - choices: [ - { - message: { role: "assistant", content: CL_7186_PAYLOAD }, - }, - ], - usage: { prompt_tokens: 1, completion_tokens: 1 }, - }), - ); - expect(textDeltas(events)).toEqual([]); - expect((toolStarts(events)[0]?.data as { name: string }).name).toBe("memory_search"); - expectSharedToolCallId(events); - expect(JSON.parse(argumentFragments(events))).toEqual({ - query: "this person", - }); - }); - - test("every request asks the OpenAI-compat endpoint for a terminal usage chunk", () => { - const wrapped = createOllamaAdapter(source, undefined); - const body = bodyOf(wrapped.buildRequest(messages, "gpt-oss:20b", options)); - expect(body["stream_options"]).toEqual({ include_usage: true }); - }); - - test("parseResponse maps native prompt_eval_count/eval_count onto inference.usage", () => { - const wrapped = createOllamaAdapter(source, undefined); - const events = wrapped.parseResponse( - JSON.stringify({ - choices: [{ delta: {}, finish_reason: "stop" }], - prompt_eval_count: 42, - eval_count: 17, - }), - ); - const usage = events.filter((event) => event.type === "inference.usage"); - expect(usage).toHaveLength(1); - expect(usage[0]?.data).toEqual({ - usage: { - input: 42, - output: 17, - cacheRead: 0, - cacheWrite: 0, - thinking: 0, - }, - source, - }); - }); - - test("parseResponse does not double-emit usage when the OpenAI-shaped object is already present", () => { - const wrapped = createOllamaAdapter(source, undefined); - const events = wrapped.parseResponse( - JSON.stringify({ - choices: [{ delta: {}, finish_reason: "stop" }], - usage: { prompt_tokens: 10, completion_tokens: 4 }, - prompt_eval_count: 99, - eval_count: 99, - }), - ); - const usage = events.filter((event) => event.type === "inference.usage"); - expect(usage).toHaveLength(1); - expect(usage[0]?.data).toEqual({ - usage: { - input: 10, - output: 4, - cacheRead: 0, - cacheWrite: 0, - thinking: 0, - }, - source, - }); - }); -}); diff --git a/packages/ollama-adapter/src/adapter.ts b/packages/ollama-adapter/src/adapter.ts deleted file mode 100644 index fdf045d66e..0000000000 --- a/packages/ollama-adapter/src/adapter.ts +++ /dev/null @@ -1,185 +0,0 @@ -// The `ollama` provider adapter: the built-in OpenAI Chat Completions -// adapter (SSE parsing, retry/pacing header extraction, message -// marshaling — all unmodified), wrapped so `buildRequest` applies -// operator-configured overrides onto the request body before it ships. -// -// Ollama's openai-compatible `/v1/chat/completions` endpoint takes -// `max_tokens` (mapped internally to Ollama's native `num_predict`) but has -// no OpenAI-shaped field for context window — that rides through the -// endpoint's `options` passthrough object as `options.num_ctx`, exactly -// like a native `/api/chat` call. A silently-dropped `num_ctx` (set on the -// wrong field, or as a top-level key the endpoint ignores) is the failure -// mode this adapter exists to rule out. Reasoning effort rides through the -// same `reasoning_effort` field Ollama already recognizes for gpt-oss -// models on this endpoint. -import { createOpenAIAdapter } from "@intx/inference/providers"; -import type { AdapterFactory, BuiltRequest, ProviderAdapter } from "@intx/inference"; -import type { InferenceEvent, LastCycleSource, TokenUsage } from "@intx/types/runtime"; - -import { parseOllamaAdapterConfig, resolveOverride, type OllamaAdapterOverride } from "./overrides"; -import { createThinkSplitState, reclassifyThinkingEvents } from "./think-tags"; -import { - createInlineToolJsonState, - reclassifyInlineToolJsonEvents, - responseChunkIsTerminal, - setDeclaredToolNames, -} from "./inline-tool-json"; - -type OllamaChatBody = { - options?: Record; - max_tokens?: number; - max_completion_tokens?: number; - reasoning_effort?: string; - stream_options?: { include_usage: boolean }; -}; - -function applyOverride(built: BuiltRequest, override: OllamaAdapterOverride): BuiltRequest { - const body = JSON.parse(built.body) as OllamaChatBody; - // Without include_usage, Ollama's OpenAI-compat stream often ends with no - // usage object; the harness then synthesizes zero token counts that Insights - // used to display as Cost $0.00 / 0/0. - body.stream_options = { include_usage: true }; - if (override.numCtx !== undefined) { - body.options = { ...body.options, num_ctx: override.numCtx }; - } - if (override.maxOutputTokens !== undefined) { - // The built-in adapter already set whichever of these two fields its - // quirks resolved to; overwrite that same field rather than assuming - // one, so the override wins regardless of which one is in play. - if (body.max_completion_tokens !== undefined) { - body.max_completion_tokens = override.maxOutputTokens; - } else { - body.max_tokens = override.maxOutputTokens; - } - } - if (override.reasoningEffort !== undefined) { - body.reasoning_effort = override.reasoningEffort; - } - return { ...built, body: JSON.stringify(body) }; -} - -function isPlainObject(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -function asNonNegativeInt(value: unknown): number | null { - return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null; -} - -function openaiShapedUsage(value: unknown): TokenUsage | null { - if (!isPlainObject(value)) return null; - const input = asNonNegativeInt(value["prompt_tokens"]); - const output = asNonNegativeInt(value["completion_tokens"]); - if (input === null && output === null) return null; - const details = value["prompt_tokens_details"]; - const completionDetails = value["completion_tokens_details"]; - const cacheRead = isPlainObject(details) ? asNonNegativeInt(details["cached_tokens"]) : null; - const thinking = isPlainObject(completionDetails) - ? asNonNegativeInt(completionDetails["reasoning_tokens"]) - : null; - return { - input: input ?? 0, - output: output ?? 0, - cacheRead: cacheRead ?? 0, - cacheWrite: 0, - thinking: thinking ?? 0, - }; -} - -function ollamaTokenUsageFromChunk(raw: string): TokenUsage | null { - try { - const parsed: unknown = JSON.parse(raw); - if (!isPlainObject(parsed)) return null; - const fromUsage = openaiShapedUsage(parsed["usage"]); - if (fromUsage !== null) return fromUsage; - const input = asNonNegativeInt(parsed["prompt_eval_count"]); - const output = asNonNegativeInt(parsed["eval_count"]); - if (input === null && output === null) return null; - return { - input: input ?? 0, - output: output ?? 0, - cacheRead: 0, - cacheWrite: 0, - thinking: 0, - }; - } catch { - // report-error-ignore: a non-JSON SSE chunk is the common case, not a - // failure — this function is "usage if present", never an error path. - return null; - } -} - -function withOllamaUsage( - events: readonly InferenceEvent[], - raw: string, - source: LastCycleSource, -): InferenceEvent[] { - if (events.some((event) => event.type === "inference.usage")) { - return [...events]; - } - const usage = ollamaTokenUsageFromChunk(raw); - if (usage === null) return [...events]; - return [ - ...events, - { - type: "inference.usage", - seq: 0, - data: { usage, source }, - }, - ]; -} - -/** - * `AdapterFactory` for the `ollama` provider key, the named export a - * `SIDECAR_ADAPTER_MANIFEST` entry points at. `quirks` is this package's - * own {@link OllamaAdapterConfig} (an `InferenceSource.quirks` bag), not - * the built-in adapter's `OpenAIQuirks` — the wrapped adapter is - * constructed with no quirks of its own, so its request/response handling - * is exactly the shipped default except for this override pass. - */ -export const createOllamaAdapter: AdapterFactory = ( - source: LastCycleSource, - quirks?: unknown, -): ProviderAdapter => { - const config = parseOllamaAdapterConfig(quirks); - const inner = createOpenAIAdapter(source); - // One split state per adapter instance: the registry resolves a fresh - // adapter per request (see `createAdapterRegistry`'s own doc comment), - // so this safely tracks "are we inside a `` span" across every - // chunk of one response without leaking state between requests. - const streamThinkState = createThinkSplitState(); - const jsonThinkState = createThinkSplitState(); - const streamInlineState = createInlineToolJsonState(); - const jsonInlineState = createInlineToolJsonState(); - return { - ...inner, - buildRequest: (messages, model, options) => { - setDeclaredToolNames(streamInlineState, options.tools); - setDeclaredToolNames(jsonInlineState, options.tools); - return applyOverride( - inner.buildRequest(messages, model, options), - resolveOverride(config, model), - ); - }, - parseResponse: (sseData) => - withOllamaUsage( - reclassifyInlineToolJsonEvents( - reclassifyThinkingEvents(inner.parseResponse(sseData), streamThinkState), - streamInlineState, - { flush: responseChunkIsTerminal(sseData) }, - ), - sseData, - source, - ), - parseJSONResponse: (body) => - withOllamaUsage( - reclassifyInlineToolJsonEvents( - reclassifyThinkingEvents(inner.parseJSONResponse(body), jsonThinkState), - jsonInlineState, - { flush: true }, - ), - body, - source, - ), - }; -}; diff --git a/packages/ollama-adapter/src/index.ts b/packages/ollama-adapter/src/index.ts deleted file mode 100644 index 4b1393f8d3..0000000000 --- a/packages/ollama-adapter/src/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -export { createOllamaAdapter } from "./adapter"; -export { - OllamaAdapterConfig, - OllamaAdapterOverride, - ReasoningEffort, - parseOllamaAdapterConfig, - resolveOverride, -} from "./overrides"; -export { - createThinkSplitState, - reclassifyThinkingEvents, - type ThinkSplitState, -} from "./think-tags"; -export { - createInlineToolJsonState, - reclassifyInlineToolJsonEvents, - responseChunkIsTerminal, - setDeclaredToolNames, - type InlineToolJsonState, -} from "./inline-tool-json"; diff --git a/packages/ollama-adapter/src/inline-tool-json.test.ts b/packages/ollama-adapter/src/inline-tool-json.test.ts deleted file mode 100644 index 48cb5042ae..0000000000 --- a/packages/ollama-adapter/src/inline-tool-json.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import type { InferenceEvent } from "@intx/types/runtime"; - -import { createInlineToolJsonState, reclassifyInlineToolJsonEvents } from "./inline-tool-json"; - -const CL_7186_PAYLOAD = '{"name":"memory_search","parameters":{"query":"this person"}}'; - -function textDelta(token: string, seq = 1): InferenceEvent { - return { - type: "inference.text.delta", - seq, - data: { token, partial: { text: token }, index: 0 }, - }; -} - -function usageEvent(seq = 2): InferenceEvent { - return { - type: "inference.usage", - seq, - data: { - usage: { - input: 1, - output: 1, - cacheRead: 0, - cacheWrite: 0, - thinking: 0, - }, - source: { sourceId: "ollama-test", provider: "ollama", model: "qwen" }, - }, - }; -} - -function reclassify( - events: readonly InferenceEvent[], - declaredNames: Iterable, - opts?: { flush?: boolean }, -): InferenceEvent[] { - return reclassifyInlineToolJsonEvents(events, createInlineToolJsonState(declaredNames), opts); -} - -function toolStarts(events: readonly InferenceEvent[]): InferenceEvent[] { - return events.filter((event) => event.type === "inference.tool_call.start"); -} - -function textDeltas(events: readonly InferenceEvent[]): InferenceEvent[] { - return events.filter((event) => event.type === "inference.text.delta"); -} - -function toolCallIds(events: readonly InferenceEvent[]): string[] { - return events - .filter( - (event) => - event.type === "inference.tool_call.start" || event.type === "inference.tool_call.delta", - ) - .map((event) => (event.data as { callId: string }).callId); -} - -function expectSharedToolCallId(events: readonly InferenceEvent[]): void { - const ids = toolCallIds(events); - expect(ids.length).toBeGreaterThan(0); - expect(new Set(ids)).toEqual(new Set(["ollama-inline-0"])); -} - -function argumentFragments(events: readonly InferenceEvent[]): string { - return events - .filter((event) => event.type === "inference.tool_call.delta") - .map((event) => (event.data as { argumentFragment: string }).argumentFragment) - .join(""); -} - -describe("reclassifyInlineToolJsonEvents", () => { - test("a memory_search JSON payload becomes a tool_call.start with no text", () => { - const out = reclassify([textDelta(CL_7186_PAYLOAD), usageEvent()], ["memory_search"]); - expect(textDeltas(out)).toEqual([]); - const starts = toolStarts(out); - expect(starts).toHaveLength(1); - expect((starts[0]?.data as { name: string }).name).toBe("memory_search"); - expectSharedToolCallId(out); - expect(JSON.parse(argumentFragments(out))).toEqual({ - query: "this person", - }); - }); - - test("chunks split across a JSON boundary still salvage once the object completes", () => { - const state = createInlineToolJsonState(["memory_search"]); - const splitAt = CL_7186_PAYLOAD.indexOf("memory_search") + 6; - const first = reclassifyInlineToolJsonEvents( - [textDelta(CL_7186_PAYLOAD.slice(0, splitAt))], - state, - ); - expect(textDeltas(first)).toEqual([]); - expect(toolStarts(first)).toEqual([]); - - const second = reclassifyInlineToolJsonEvents( - [textDelta(CL_7186_PAYLOAD.slice(splitAt))], - state, - ); - expect(textDeltas(second)).toEqual([]); - expect(toolStarts(second)).toEqual([]); - - const flushed = reclassifyInlineToolJsonEvents([], state, { flush: true }); - expect(textDeltas(flushed)).toEqual([]); - expect((toolStarts(flushed)[0]?.data as { name: string }).name).toBe("memory_search"); - expectSharedToolCallId(flushed); - expect(JSON.parse(argumentFragments(flushed))).toEqual({ - query: "this person", - }); - }); - - test("arguments is accepted as the args object, same as parameters", () => { - const payload = '{"name":"memory_search","arguments":{"query":"this person"}}'; - const out = reclassify([textDelta(payload)], ["memory_search"], { - flush: true, - }); - expect(textDeltas(out)).toEqual([]); - expectSharedToolCallId(out); - expect(JSON.parse(argumentFragments(out))).toEqual({ - query: "this person", - }); - }); - - test("an unknown name stays text even when the JSON shape matches", () => { - const payload = '{"name":"not_a_tool","parameters":{"query":"this person"}}'; - const original = [textDelta(payload)]; - const out = reclassify(original, ["memory_search"], { flush: true }); - expect(out).toEqual(original); - expect(toolStarts(out)).toEqual([]); - }); - - test("declared-name gate: no tools on the request leaves the JSON as text", () => { - const original = [textDelta(CL_7186_PAYLOAD)]; - const out = reclassify(original, [], { flush: true }); - expect(out).toEqual(original); - expect(toolStarts(out)).toEqual([]); - }); - - test("legitimate JSON answers stay text: extra keys, arrays, mixed prose, tutorials", () => { - const samples = [ - '{"name":"memory_search","parameters":{"query":"this person"},"title":"example"}', - '[{"name":"memory_search","parameters":{"query":"this person"}}]', - 'Call it like this:\n{"name":"memory_search","parameters":{"query":"this person"}}', - '{"ok":true,"count":3}', - '{"name":"memory_search"}', - "```json\n" + CL_7186_PAYLOAD + "\n```", - ]; - for (const sample of samples) { - const original = [textDelta(sample)]; - const out = reclassify(original, ["memory_search"], { flush: true }); - expect(out).toEqual(original); - expect(toolStarts(out)).toEqual([]); - } - }); - - test("incomplete JSON at flush stays the original text", () => { - const original = [textDelta('{"name":"memory_search"')]; - const out = reclassify(original, ["memory_search"], { flush: true }); - expect(out).toEqual(original); - }); - - test("ordinary prose with tools declared passes through unchanged", () => { - const original = [textDelta("hello, how can I help?")]; - const out = reclassify(original, ["memory_search"]); - expect(out).toEqual(original); - }); - - test("salvaged tool_call events reuse the text block index so they cannot collide with leftover content", () => { - const out = reclassify([textDelta(CL_7186_PAYLOAD)], ["memory_search"], { - flush: true, - }); - const start = toolStarts(out)[0]; - expect((start?.data as { index?: number }).index).toBe(0); - expectSharedToolCallId(out); - expect(textDeltas(out)).toEqual([]); - }); -}); diff --git a/packages/ollama-adapter/src/inline-tool-json.ts b/packages/ollama-adapter/src/inline-tool-json.ts deleted file mode 100644 index 82932a291e..0000000000 --- a/packages/ollama-adapter/src/inline-tool-json.ts +++ /dev/null @@ -1,272 +0,0 @@ -// Ollama's OpenAI-compatible endpoint sometimes emits a declared tool call -// as a JSON object in `content` instead of native `tool_calls`. -// `@intx/inference`'s OpenAI parser only reads `delta.tool_calls`, so that -// JSON rides downstream as assistant text and the tool never runs. This -// module reclassifies a content stream that is exactly that object into -// `inference.tool_call.*` events, gated on the tools declared for the -// request so unknown names and ordinary JSON answers stay text. -import type { InferenceEvent } from "@intx/types/runtime"; - -export type InlineToolJsonState = { - declaredNames: Set; - held: InferenceEvent[]; - acc: string; - verdict: "pending" | "text" | "tool"; -}; - -export function createInlineToolJsonState( - declaredNames: Iterable = [], -): InlineToolJsonState { - return { - declaredNames: new Set(declaredNames), - held: [], - acc: "", - verdict: "pending", - }; -} - -export function setDeclaredToolNames( - state: InlineToolJsonState, - tools: readonly { name: string }[] | undefined, -): void { - state.declaredNames = new Set((tools ?? []).map((tool) => tool.name)); -} - -const INLINE_TOOL_CALL_ID = "ollama-inline-0"; -const EMPTY_PARTIAL = { text: "" }; - -function isPlainObject(value: unknown): value is Record { - return typeof value === "object" && value !== null && Array.isArray(value) === false; -} - -type ParseResult = - | { kind: "incomplete" } - | { kind: "reject" } - | { kind: "object"; value: Record }; - -function parseExactObject(text: string): ParseResult { - const trimmed = text.trim(); - if (trimmed.length === 0) { - return { kind: "incomplete" }; - } - if (trimmed.startsWith("{") === false) { - return { kind: "reject" }; - } - try { - const parsed: unknown = JSON.parse(trimmed); - if (!isPlainObject(parsed)) { - return { kind: "reject" }; - } - return { kind: "object", value: parsed }; - } catch { - return { kind: "incomplete" }; - } -} - -function salvageToolCall( - value: Record, - declaredNames: ReadonlySet, -): { name: string; args: Record } | null { - for (const key of Object.keys(value)) { - if (key !== "name" && key !== "parameters" && key !== "arguments" && key !== "id") { - return null; - } - } - const name = value["name"]; - if (typeof name !== "string" || declaredNames.has(name) === false) { - return null; - } - const hasParameters = Object.hasOwn(value, "parameters"); - const hasArguments = Object.hasOwn(value, "arguments"); - if (hasParameters === hasArguments) { - return null; - } - const raw = hasParameters ? value["parameters"] : value["arguments"]; - if (!isPlainObject(raw)) { - return null; - } - const id = value["id"]; - if (id !== undefined && typeof id !== "string") { - return null; - } - return { name, args: raw }; -} - -function lastHeldText(held: readonly InferenceEvent[]): InferenceEvent | undefined { - for (let i = held.length - 1; i >= 0; i--) { - const event = held[i]; - if (event?.type === "inference.text.delta") { - return event; - } - } - return undefined; -} - -function emitToolCallEvents( - salvaged: { name: string; args: Record }, - template: InferenceEvent | undefined, -): InferenceEvent[] { - const seq = template?.seq ?? 0; - const index = - template?.type === "inference.text.delta" && template.data.index !== undefined - ? template.data.index - : 0; - return [ - { - type: "inference.tool_call.start", - seq, - data: { - callId: INLINE_TOOL_CALL_ID, - name: salvaged.name, - partial: EMPTY_PARTIAL, - index, - }, - }, - { - type: "inference.tool_call.delta", - seq, - data: { - // Same id as start. The harness keys open tool calls by start's - // callId and resolves a delta as `indexToCallId.get(callId) ?? - // callId`; a matching id attaches arguments. OpenAI's - // `String(index)` placeholder is only for native continuation - // deltas that omit the real id — this salvage mints both events. - callId: INLINE_TOOL_CALL_ID, - argumentFragment: JSON.stringify(salvaged.args), - partial: EMPTY_PARTIAL, - index, - }, - }, - ]; -} - -function matchingSalvage( - state: InlineToolJsonState, -): { name: string; args: Record } | null { - const parsed = parseExactObject(state.acc); - if (parsed.kind !== "object") { - return null; - } - return salvageToolCall(parsed.value, state.declaredNames); -} - -function releaseHeldAsText(output: InferenceEvent[], state: InlineToolJsonState): void { - output.push(...state.held); - state.held = []; - state.verdict = "text"; -} - -function flushPending(output: InferenceEvent[], state: InlineToolJsonState): void { - if (state.verdict !== "pending") { - return; - } - if (state.held.length === 0 && state.acc === "") { - return; - } - const salvaged = matchingSalvage(state); - if (salvaged !== null) { - output.push(...emitToolCallEvents(salvaged, lastHeldText(state.held))); - state.held = []; - state.verdict = "tool"; - return; - } - releaseHeldAsText(output, state); -} - -function inspectHeldText(output: InferenceEvent[], state: InlineToolJsonState): void { - const parsed = parseExactObject(state.acc); - if (parsed.kind === "incomplete") { - return; - } - if (parsed.kind === "reject") { - releaseHeldAsText(output, state); - return; - } - if (salvageToolCall(parsed.value, state.declaredNames) === null) { - releaseHeldAsText(output, state); - } -} - -export function responseChunkIsTerminal(sseData: string): boolean { - try { - const parsed: unknown = JSON.parse(sseData); - if (!isPlainObject(parsed)) { - return false; - } - if (parsed["usage"] != null) { - return true; - } - const choices = parsed["choices"]; - if (!Array.isArray(choices) || choices.length === 0) { - return false; - } - const first: unknown = choices[0]; - if (!isPlainObject(first)) { - return false; - } - const reason = first["finish_reason"]; - return typeof reason === "string" && reason.length > 0; - } catch { - return false; - } -} - -/** - * Rewrites one `parseResponse`/`parseJSONResponse` result so a content - * stream that is exactly a declared-tool JSON object becomes tool-call - * events instead of text. `state` is mutated in place so a caller threads - * the same instance across every chunk of one response. Pass `flush` on - * the terminal chunk (finish_reason / complete JSON body) so a matching - * object is committed only once the stream cannot grow trailing prose. - */ -export function reclassifyInlineToolJsonEvents( - events: readonly InferenceEvent[], - state: InlineToolJsonState, - opts?: { flush?: boolean }, -): InferenceEvent[] { - if (state.declaredNames.size === 0) { - return [...events]; - } - - const output: InferenceEvent[] = []; - - for (const event of events) { - if (state.verdict === "text") { - output.push(event); - continue; - } - if (state.verdict === "tool") { - if (event.type !== "inference.text.delta") { - output.push(event); - } - continue; - } - if (event.type === "inference.text.delta") { - state.acc += event.data.token; - state.held.push(event); - inspectHeldText(output, state); - continue; - } - if (event.type === "inference.usage") { - flushPending(output, state); - output.push(event); - continue; - } - if ( - event.type === "inference.tool_call.start" || - event.type === "inference.tool_call.delta" || - event.type === "inference.tool_call.end" - ) { - releaseHeldAsText(output, state); - output.push(event); - continue; - } - output.push(event); - } - - if (opts?.flush === true) { - flushPending(output, state); - } - - return output; -} diff --git a/packages/ollama-adapter/src/overrides.test.ts b/packages/ollama-adapter/src/overrides.test.ts deleted file mode 100644 index be8afb97d7..0000000000 --- a/packages/ollama-adapter/src/overrides.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { OllamaAdapterConfig, parseOllamaAdapterConfig, resolveOverride } from "./overrides"; - -describe("parseOllamaAdapterConfig", () => { - test("undefined quirks resolve to an empty config", () => { - expect(parseOllamaAdapterConfig(undefined)).toEqual({}); - }); - - test("rejects an unknown top-level key", () => { - expect(() => parseOllamaAdapterConfig({ bogus: true })).toThrow(); - }); - - test("rejects a non-positive numCtx", () => { - expect(() => parseOllamaAdapterConfig({ default: { numCtx: 0 } })).toThrow(); - }); - - test("rejects a reasoningEffort outside the closed set", () => { - expect(() => parseOllamaAdapterConfig({ default: { reasoningEffort: "extreme" } })).toThrow(); - }); - - test("accepts a well-formed default and perModel config", () => { - const parsed = OllamaAdapterConfig({ - default: { numCtx: 8192 }, - perModel: { "gpt-oss:20b": { maxOutputTokens: 2048 } }, - }); - expect(parsed instanceof Error).toBe(false); - }); -}); - -describe("resolveOverride", () => { - test("no override configured resolves to an empty override", () => { - expect(resolveOverride({}, "gpt-oss:20b")).toEqual({}); - }); - - test("the general default applies when no per-model entry matches", () => { - const config = parseOllamaAdapterConfig({ default: { numCtx: 8192 } }); - expect(resolveOverride(config, "qwen3.8:27b")).toEqual({ numCtx: 8192 }); - }); - - test("a per-model override beats the general default field-by-field", () => { - const config = parseOllamaAdapterConfig({ - default: { numCtx: 8192, maxOutputTokens: 1024 }, - perModel: { "gpt-oss:20b": { numCtx: 32768 } }, - }); - expect(resolveOverride(config, "gpt-oss:20b")).toEqual({ - numCtx: 32768, - maxOutputTokens: 1024, - }); - expect(resolveOverride(config, "qwen3.8:27b")).toEqual({ - numCtx: 8192, - maxOutputTokens: 1024, - }); - }); - - test("reasoningEffort resolves the same way", () => { - const config = parseOllamaAdapterConfig({ - default: { reasoningEffort: "low" }, - perModel: { "gpt-oss:20b": { reasoningEffort: "high" } }, - }); - expect(resolveOverride(config, "gpt-oss:20b").reasoningEffort).toBe("high"); - expect(resolveOverride(config, "qwen3.8:27b").reasoningEffort).toBe("low"); - }); -}); diff --git a/packages/ollama-adapter/src/overrides.ts b/packages/ollama-adapter/src/overrides.ts deleted file mode 100644 index 306052b19f..0000000000 --- a/packages/ollama-adapter/src/overrides.ts +++ /dev/null @@ -1,58 +0,0 @@ -// Typed operator overrides for the Ollama adapter's built request body: -// context window, max output tokens, and reasoning effort. Threaded in as -// the `quirks` argument `loadAdapterRegistry`'s resolved factory receives -// (an `InferenceSource.quirks` bag), never a loose passthrough object. - -import { type } from "arktype"; - -export const ReasoningEffort = type("'low' | 'medium' | 'high'"); -export type ReasoningEffort = typeof ReasoningEffort.infer; - -export const OllamaAdapterOverride = type({ - "numCtx?": "number.integer > 0", - "maxOutputTokens?": "number.integer > 0", - "reasoningEffort?": ReasoningEffort, - "+": "reject", -}); -export type OllamaAdapterOverride = typeof OllamaAdapterOverride.infer; - -export const OllamaAdapterConfig = type({ - "default?": OllamaAdapterOverride, - "perModel?": { - "[string]": OllamaAdapterOverride, - }, - "+": "reject", -}); -export type OllamaAdapterConfig = typeof OllamaAdapterConfig.infer; - -/** - * Parse the adapter's `quirks` argument into a validated - * {@link OllamaAdapterConfig}. `undefined`/`null` (no quirks configured for - * this source) resolves to an empty config, matching every other override - * class's "unset means unset" convention. - */ -export function parseOllamaAdapterConfig(raw: unknown): OllamaAdapterConfig { - const validated = OllamaAdapterConfig(raw ?? {}); - if (validated instanceof type.errors) { - throw new Error(`@corbits/ollama-adapter: invalid adapter config: ${validated.summary}`); - } - return validated; -} - -/** - * Resolve the effective override for one model: a per-model entry wins - * field-by-field over the general `default`, and an unconfigured field - * resolves to `undefined` (no override, built-in adapter behavior). - */ -export function resolveOverride(config: OllamaAdapterConfig, model: string): OllamaAdapterOverride { - const base = config.default ?? {}; - const perModel = config.perModel?.[model] ?? {}; - const resolved: OllamaAdapterOverride = {}; - const numCtx = perModel.numCtx ?? base.numCtx; - if (numCtx !== undefined) resolved.numCtx = numCtx; - const maxOutputTokens = perModel.maxOutputTokens ?? base.maxOutputTokens; - if (maxOutputTokens !== undefined) resolved.maxOutputTokens = maxOutputTokens; - const reasoningEffort = perModel.reasoningEffort ?? base.reasoningEffort; - if (reasoningEffort !== undefined) resolved.reasoningEffort = reasoningEffort; - return resolved; -} diff --git a/packages/ollama-adapter/src/think-tags.test.ts b/packages/ollama-adapter/src/think-tags.test.ts deleted file mode 100644 index 4ba0d84f93..0000000000 --- a/packages/ollama-adapter/src/think-tags.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import type { InferenceEvent } from "@intx/types/runtime"; - -import { createThinkSplitState, reclassifyThinkingEvents } from "./think-tags"; - -function textDelta(token: string, seq = 1): InferenceEvent { - return { - type: "inference.text.delta", - seq, - data: { token, partial: { text: token }, index: 0 }, - }; -} - -describe("reclassifyThinkingEvents", () => { - test("a whole ... span in one token becomes thinking-delta, not text-delta", () => { - const state = createThinkSplitState(); - const out = reclassifyThinkingEvents( - [textDelta("plan the approachHere is the answer.")], - state, - ); - expect(out).toHaveLength(2); - expect(out[0]?.type).toBe("inference.thinking.delta"); - expect((out[0]?.data as { token: string }).token).toBe("plan the approach"); - expect(out[1]?.type).toBe("inference.text.delta"); - expect((out[1]?.data as { token: string }).token).toBe("Here is the answer."); - }); - - test("a span split across multiple chunks stays classified as thinking across the boundary", () => { - const state = createThinkSplitState(); - const first = reclassifyThinkingEvents([textDelta("step one, ")], state); - const second = reclassifyThinkingEvents([textDelta("step twofinal reply")], state); - - expect(first).toHaveLength(1); - expect(first[0]?.type).toBe("inference.thinking.delta"); - expect(second).toHaveLength(2); - expect(second[0]?.type).toBe("inference.thinking.delta"); - expect((second[0]?.data as { token: string }).token).toBe("step two"); - expect(second[1]?.type).toBe("inference.text.delta"); - expect((second[1]?.data as { token: string }).token).toBe("final reply"); - }); - - test("ordinary text with no tag passes through as text-delta unchanged", () => { - const state = createThinkSplitState(); - const out = reclassifyThinkingEvents([textDelta("just a normal reply")], state); - expect(out).toEqual([textDelta("just a normal reply")]); - }); - - test("non-text events (tool calls, done) pass through untouched", () => { - const state = createThinkSplitState(); - const toolCallStart: InferenceEvent = { - type: "inference.tool_call.start", - seq: 1, - data: { - callId: "call-1", - name: "slack__post_message", - partial: { text: "" }, - }, - }; - const out = reclassifyThinkingEvents([toolCallStart], state); - expect(out).toEqual([toolCallStart]); - }); - - test("thinking events never share an index with the text stream, so the harness's per-index blockMap can't collide them", () => { - const state = createThinkSplitState(); - const out = reclassifyThinkingEvents( - [textDelta("internal notesvisible reply", 3)], - state, - ); - const thinkingEvent = out.find((event) => event.type === "inference.thinking.delta"); - const textEvent = out.find((event) => event.type === "inference.text.delta"); - expect((thinkingEvent?.data as { index?: number }).index).not.toBe( - (textEvent?.data as { index?: number }).index, - ); - expect((textEvent?.data as { index?: number }).index).toBe(0); - }); - - test("cumulative partial.text/partial.thinking reflect only their own kind, never the raw tags", () => { - const state = createThinkSplitState(); - const out = reclassifyThinkingEvents( - [textDelta("internal notesvisible reply")], - state, - ); - const thinkingEvent = out.find((event) => event.type === "inference.thinking.delta"); - const textEvent = out.find((event) => event.type === "inference.text.delta"); - expect((thinkingEvent?.data as { partial: { thinking?: string } }).partial.thinking).toBe( - "internal notes", - ); - expect((textEvent?.data as { partial: { text: string } }).partial.text).toBe("visible reply"); - expect((textEvent?.data as { partial: { text: string } }).partial.text).not.toContain( - "", - ); - }); -}); diff --git a/packages/ollama-adapter/src/think-tags.ts b/packages/ollama-adapter/src/think-tags.ts deleted file mode 100644 index 3820a83b94..0000000000 --- a/packages/ollama-adapter/src/think-tags.ts +++ /dev/null @@ -1,145 +0,0 @@ -// Ollama's OpenAI-compatible endpoint never populates the `reasoning`/ -// `reasoning_content` delta fields `@intx/inference`'s OpenAI provider -// looks for (see `providers/openai.js`'s `reasoningFieldNames` handling). -// gpt-oss and qwen instead emit their chain-of-thought inline inside the -// ordinary `content` field, wrapped in `…`. Left alone, that -// text is indistinguishable from the reply and rides every hop downstream -// as a genuine `inference.text.delta` leak. This -// module reclassifies it into `inference.thinking.delta` before anything -// else ever sees it, at the one place that already knows these tokens came -// from Ollama. -import type { InferenceEvent } from "@intx/types/runtime"; - -/** Carries the split state across every chunk of one streamed response — - * a `` tag can land at a chunk boundary, so "are we inside a - * thinking span" has to survive from one `parseResponse` call to the next. */ -export type ThinkSplitState = { - inThink: boolean; - /** Once a `` tag has appeared at all, every later text-delta gets - * its `partial` recomputed from this module's own tally rather than the - * built-in adapter's — otherwise a token after the closing tag would - * still carry the raw-tagged cumulative text the built-in parser tracked - * on its own. Before the first tag, events pass through byte-identical. */ - everInThink: boolean; - textAcc: string; - thinkingAcc: string; -}; - -export function createThinkSplitState(): ThinkSplitState { - return { inThink: false, everInThink: false, textAcc: "", thinkingAcc: "" }; -} - -const THINK_OPEN = ""; -const THINK_CLOSE = ""; - -/** The harness (`@intx/inference`'s `dist/harness.js`) keys its per-index - * `blockMap` by `event.data.index` and throws a `ProtocolMismatchError` the - * moment two different block kinds land at the same index — so the - * thinking half of a split can never reuse the text index the built-in - * OpenAI adapter already assigned to Ollama's one undifferentiated content - * stream. Ollama's own indexer starts at 0 and only counts up (one index - * per real block: text, then any tool calls), so a fixed negative - * sentinel is guaranteed to never collide with one it hands out. */ -const THINKING_BLOCK_INDEX = -1; - -type TokenSplit = { - readonly textToken: string; - readonly thinkingToken: string; -}; - -/** Peels ``/`` spans out of one token, folding the result - * into the running cumulative text/thinking strings. A tag never splits - * across two tokens in practice, but a token straddling the tag boundary - * (open and content in the same token, or close and content) is still - * handled correctly by looping until the whole token is consumed. */ -function splitToken(state: ThinkSplitState, token: string): TokenSplit { - let remaining = token; - let textToken = ""; - let thinkingToken = ""; - - while (remaining.length > 0) { - if (!state.inThink) { - const openIndex = remaining.indexOf(THINK_OPEN); - if (openIndex === -1) { - textToken += remaining; - break; - } - textToken += remaining.slice(0, openIndex); - remaining = remaining.slice(openIndex + THINK_OPEN.length); - state.inThink = true; - } else { - const closeIndex = remaining.indexOf(THINK_CLOSE); - if (closeIndex === -1) { - thinkingToken += remaining; - break; - } - thinkingToken += remaining.slice(0, closeIndex); - remaining = remaining.slice(closeIndex + THINK_CLOSE.length); - state.inThink = false; - } - } - - state.textAcc += textToken; - state.thinkingAcc += thinkingToken; - return { textToken, thinkingToken }; -} - -/** - * Rewrites one `parseResponse`/`parseJSONResponse` result so a - * `…` span in an `inference.text.delta`'s token becomes an - * `inference.thinking.delta` instead — every other event (tool calls, - * usage, `inference.done`, ...) passes through untouched. `state` is - * mutated in place so a caller threads the same instance across every - * chunk of one response. - */ -export function reclassifyThinkingEvents( - events: readonly InferenceEvent[], - state: ThinkSplitState, -): InferenceEvent[] { - const output: InferenceEvent[] = []; - - for (const event of events) { - if (event.type !== "inference.text.delta") { - output.push(event); - continue; - } - - const token = event.data.token; - if (!state.inThink && !state.everInThink && !token.includes(THINK_OPEN)) { - output.push(event); - continue; - } - state.everInThink = true; - - const { textToken, thinkingToken } = splitToken(state, token); - const partial = { - text: state.textAcc, - ...(state.thinkingAcc !== "" ? { thinking: state.thinkingAcc } : {}), - }; - - if (thinkingToken !== "") { - output.push({ - type: "inference.thinking.delta", - seq: event.seq, - data: { - token: thinkingToken, - partial, - index: THINKING_BLOCK_INDEX, - }, - }); - } - if (textToken !== "") { - output.push({ - type: "inference.text.delta", - seq: event.seq, - data: { - token: textToken, - partial, - ...(event.data.index !== undefined ? { index: event.data.index } : {}), - }, - }); - } - } - - return output; -} diff --git a/packages/ollama-adapter/tsconfig.json b/packages/ollama-adapter/tsconfig.json deleted file mode 100644 index e125e90614..0000000000 --- a/packages/ollama-adapter/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "./tsconfig.src.json", - "compilerOptions": { - "composite": false, - "noEmit": true, - "disableSourceOfProjectReferenceRedirect": true, - "declaration": false, - "declarationMap": false, - "emitDeclarationOnly": false, - "tsBuildInfoFile": "tsconfig.tsbuildinfo", - "rootDir": "../.." - }, - "include": ["src"], - "exclude": [] -} diff --git a/packages/ollama-adapter/tsconfig.src.json b/packages/ollama-adapter/tsconfig.src.json deleted file mode 100644 index fc8724305f..0000000000 --- a/packages/ollama-adapter/tsconfig.src.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["src", "package.json", "src/**/*.json"], - "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"], - "compilerOptions": { - "types": ["bun"], - "composite": true, - "emitDeclarationOnly": true, - "outDir": "dist", - "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" - } -} diff --git a/tsconfig.build.json b/tsconfig.build.json index 15cebe2e41..587ee17827 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -40,9 +40,6 @@ { "path": "./packages/migration-runner/tsconfig.src.json" }, - { - "path": "./packages/ollama-adapter/tsconfig.src.json" - }, { "path": "./packages/tool-registry-publish/tsconfig.src.json" },