diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml
index 18713ef..dcac458 100644
--- a/.github/workflows/checks.yml
+++ b/.github/workflows/checks.yml
@@ -30,11 +30,6 @@ jobs:
cache: true
- name: Vet
run: go vet ./...
- - name: Test
- run: go test ./...
- - name: Race test
- if: matrix.os == 'ubuntu-latest'
- run: go test -race ./...
- name: Build
run: go build -trimpath ./cmd/opencode2api
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c0db894..c0cb193 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -128,7 +128,8 @@ jobs:
run: |
mkdir -p "dist/$PACKAGE_NAME"
go build -trimpath -ldflags="-s -w -X main.version=$RELEASE_TAG" -o "dist/$PACKAGE_NAME/opencode2api$EXTENSION" ./cmd/opencode2api
- cp README.md README.zh-CN.md config.example.json "dist/$PACKAGE_NAME/"
+ cp README.md README.zh-CN.md LICENSE config.example.json "dist/$PACKAGE_NAME/"
+ cp -r docs "dist/$PACKAGE_NAME/"
if [[ "$ARCHIVE_FORMAT" == "zip" ]]; then
(cd dist && zip -q -r "$PACKAGE_NAME.zip" "$PACKAGE_NAME")
archive="$PACKAGE_NAME.zip"
@@ -184,6 +185,7 @@ jobs:
labels: |
org.opencontainers.image.title=opencode2api
org.opencontainers.image.description=OpenAI-compatible API gateway for OpenCode Zen and Go
+ org.opencontainers.image.licenses=GPL-3.0-or-later
- name: Build and push image
uses: docker/build-push-action@v6
diff --git a/.gitignore b/.gitignore
index e0f69c8..6c84134 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,3 +20,4 @@ coverage.out
# Local credentials, deployment backups, and verification artifacts
.local/
+*.availability.json
diff --git a/.prettierignore b/.prettierignore
index b4d91f5..0a2013a 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -12,3 +12,4 @@ package-lock.json
.local/
*.rotation.json
+*.availability.json
diff --git a/Dockerfile b/Dockerfile
index ef89733..25cac6d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -30,6 +30,8 @@ RUN apk add --no-cache ca-certificates su-exec tzdata \
COPY --from=builder /out/opencode2api /usr/local/bin/opencode2api
COPY --chmod=0755 docker-entrypoint.sh /usr/local/bin/docker-entrypoint
COPY --chown=opencode2api:opencode2api config.example.json /app/config.example.json
+COPY LICENSE /usr/share/licenses/opencode2api/LICENSE
+LABEL org.opencontainers.image.licenses="GPL-3.0-or-later"
# LISTEN_ADDRESS / WEBUI_LISTEN_ADDRESS are intentionally unset: config.json is
# authoritative. Export them to override the configured listen addresses.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ 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.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ 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 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. Use with the GNU Affero General Public License.
+
+ 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 Affero 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 special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ 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 GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
index 0bc7a46..2564355 100644
--- a/README.md
+++ b/README.md
@@ -196,14 +196,14 @@ The gateway refreshes Zen/Go `/v1/models` and OpenCode's [capability catalog](ht
Allowed protocol values are `chat`, `responses`, and `anthropic`. Models using unsupported native protocols are filtered from discovery unless overridden.
-Cost, deprecation, and model limits come from [models.dev](https://models.dev/api.json), refreshed every 24 hours. OpenCode's capability catalog remains authoritative for context and token limits; models.dev `limit.context`, `limit.input`, and `limit.output` fill fields missing from that catalog. These limits are exposed by `/v1/models` as `context_window`/`context_length`, `max_input`, and `max_output` for discovery clients such as CLIProxyAPI and Pi. Metadata requests use a 30-second timeout per HTTP client. Refresh failures retain existing data.
+Cost, deprecation, and model limits come from the official [OpenCode metadata endpoint](https://models.opencode.ai/api.json), refreshed every 24 hours. OpenCode's capability catalog remains authoritative for context and token limits; metadata `limit.context`, `limit.input`, and `limit.output` fill fields missing from that catalog. These limits are exposed by `/v1/models` as `context_window`/`context_length`, `max_input`, and `max_output` for discovery clients such as CLIProxyAPI and Pi. Metadata requests use a 30-second timeout per HTTP client. Refresh failures retain existing data.
### Anonymous access and fallback
With `anonymous: true`, either condition makes a model eligible for the anonymous Zen lane:
- Its ID contains `free`, case-insensitively.
-- models.dev reports zero input and output cost and the model is not deprecated.
+- OpenCode metadata reports zero input and output cost and the model is not deprecated.
Eligibility is a routing decision; the upstream can still reject or rate-limit the request. Anonymous requests use `public` in the upstream authentication header.
@@ -215,10 +215,20 @@ The routing sequence is:
Anonymous attempts are not cut short by `retry.max_attempts`, but all attempts share the request timeout. Network errors, authentication failures, rate limits, and server errors can rotate keys. Other 4xx responses end the current tier; another available tier may still be tried.
-Requests are encoded for each tier's own protocol. Once a stream has started, the gateway does not retry generation on another node, except when the upstream resets before anything reached downstream (the turn is replayed once inside the same connection). A recognized stale Responses reasoning reference can trigger one repair pass; selected-key diagnostics never use that replay.
+Requests are encoded for each tier's own protocol. With `performance.first_event_timeout_seconds` enabled, a successful SSE response is held until the first complete data event. A timeout or disconnect before that event uses the existing key/proxy retry budget; comments do not satisfy the timeout. Once released downstream, the stream is never replayed. The default is `0` (disabled); try `15` seconds for upstreams that accept requests but send no events. This bounds the first event, not the first text token, and does not apply to System One. Rotation aliases use their separate `rotation.first_output_seconds` timeout. A recognized stale Responses reasoning reference can trigger one repair pass; selected-key diagnostics never use that replay.
When only anonymous access is configured, `/v1/models` exposes only models eligible for that lane.
+### Free model availability
+
+The gateway probes models whose IDs contain `free` (case-insensitive), or whose metadata reports zero input/output cost without deprecation, with a short streaming inference request. It tries the enabled anonymous lane first and then one configured Zen Key. A valid completed response on either lane keeps the model enabled; if every attempted lane fails, the model is disabled in discovery and routing. Probe traffic does not alter production key/proxy cooldowns or request statistics. It still reaches the upstream and may consume its free allowance.
+
+The intervals are fixed: enabled models are checked every **1 hour**, failed models every **24 hours**. A successful recheck restores the model automatically. The WebUI **Free model availability** page can restore it immediately, with its next check one hour later. An in-flight probe cannot undo a manual restore. Models without a usable Zen/anonymous lane, or without a supported inference protocol, are skipped.
+
+State survives restarts in `config.json..availability.json`, separated by the Zen upstream URL. The background scheduler checks for due models once per minute and probes sequentially, with a 60-second timeout per lane. No channels available means no automatic disable.
+
+Administration endpoints (login required; restore also requires CSRF): `GET /api/models/availability` and `POST /api/models/restore` with `{"model":"MODEL_ID"}`.
+
### Sessions and proxies
Keys are initially spread across proxies. Real traffic can trigger proxy checks, key rebinding, and cooldowns. Unhealthy proxies are rechecked every 15 minutes against Cloudflare trace.
@@ -471,3 +481,9 @@ npm run check:web
## Acknowledgements
Thanks to the [LINUX DO](https://linux.do) community for its support.
+
+## License
+
+SPDX-License-Identifier: GPL-3.0-or-later
+
+This project is free software: you may redistribute and modify it under the GNU General Public License as published by the Free Software Foundation, either version 3 or (at your option) any later version. It is distributed without any warranty. See [LICENSE](LICENSE) for the full terms.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 85a7177..796160f 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -196,14 +196,14 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
协议值仅允许 `chat`、`responses`、`anthropic`。使用不支持的原生协议的模型会从模型列表中隐藏,除非配置了覆盖值。
-成本和弃用信息来自 [models.dev](https://models.dev/api.json),每 24 小时刷新一次;每个 HTTP 客户端的拉取超时为 30 秒。刷新失败时保留已有数据。
+成本、弃用信息及模型限制来自官方 [OpenCode 元数据地址](https://models.opencode.ai/api.json),每 24 小时刷新一次。能力目录中的限制优先;元数据中的 `limit.context`、`limit.input` 和 `limit.output` 仅补充缺失字段,通过 `/v1/models` 的 `context_window` / `context_length`、`max_input`、`max_output` 暴露。每个 HTTP 客户端的拉取超时为 30 秒,刷新失败时保留已有数据。升级后继续兼容原有 `.models.dev.json` 缓存文件名,无需删除缓存。
### 匿名通道与回退
启用 `anonymous: true` 后,满足以下任一条件的模型可以进入 Zen 匿名通道:
- 模型 ID 包含 `free`,不区分大小写。
-- models.dev 中的输入、输出成本均为零,且模型未弃用。
+- OpenCode 元数据中的输入、输出成本均为零,且模型未弃用。
这只是网关的路由判断,上游仍可能拒绝或限制请求。匿名请求在上游认证头中使用 `public` 凭证。
@@ -215,10 +215,20 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
匿名阶段不受 `retry.max_attempts` 截断,但所有阶段共享请求总超时。网络错误、认证失败、限流和服务端错误可以触发 Key 轮换;其他 4xx 会结束当前 Tier,仍可继续尝试另一个可用 Tier。
-每个 Tier 使用自己的原生协议编码请求。流开始后不再切换节点重新生成,除非上游在下游收到任何内容之前中断(该轮在本连接内重放一次)。识别到过期的 Responses reasoning 引用时,可执行一次修复重试;指定 Key 的诊断不会执行该重试。
+每个 Tier 使用自己的原生协议编码请求。启用 `performance.first_event_timeout_seconds` 后,会先等待完整的 SSE data 事件再向客户端交付响应;注释心跳不算首事件。首事件前超时或断开会沿用现有 Key / 代理重试预算,交付后不再重放。默认 `0` 关闭,可对接受请求后无事件的上游尝试设置为 `15` 秒。它限制首事件而非首个文本 token,不适用于 System One;轮转别名使用独立的 `rotation.first_output_seconds`。识别到过期的 Responses reasoning 引用时,可执行一次修复重试;指定 Key 的诊断不会执行该重试。
只有匿名通道可用时,`/v1/models` 仅展示符合匿名条件的模型。
+### 免费模型可用性
+
+只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,发送简短的流式推理请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;任一通道返回完整有效响应即视为可用,所有实际尝试的通道均失败后自动禁用,从模型列表与路由中移除。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。
+
+周期硬编码:正常模型每 **1 小时**探测,失败模型每 **24 小时**复测。复测成功自动恢复;也可在 WebUI「免费模型可用性」页立即恢复启用,下一次探测在 1 小时后。手动恢复不会被已经在途的旧探测结果覆盖。没有可用 Zen / 匿名通道,或推理协议不支持探测时跳过,不自动禁用。
+
+状态保存在 `config.json.<上游地址指纹>.availability.json`,重启后保留,按 Zen 上游 URL 隔离。后台每分钟检查到期项,串行探测,每条通道最多等待 60 秒。
+
+管理接口:`GET /api/models/availability` 查看状态;`POST /api/models/restore` 携带 `{"model":"MODEL_ID"}` 恢复。两者均需管理登录,恢复接口还需 CSRF 校验。
+
### 会话与代理
Key 初始化时均衡分配到代理。真实流量可以触发代理检查、Key 重新绑定和失败冷却。已经标记异常的代理,每 15 分钟通过 Cloudflare trace 复查一次。
@@ -466,3 +476,9 @@ npm run check:web
## 致谢
感谢 [LINUX DO](https://linux.do) 社区的支持。
+
+## 许可证
+
+SPDX-License-Identifier: GPL-3.0-or-later
+
+本项目是自由软件,采用自由软件基金会发布的 GNU 通用公共许可证第 3 版或(由你选择的)任何后续版本。你可以按该许可证重新分发和修改本项目;本项目不提供任何担保。完整条款见 [LICENSE](LICENSE)。
diff --git a/config.example.json b/config.example.json
index b17f423..a76d2a6 100644
--- a/config.example.json
+++ b/config.example.json
@@ -25,7 +25,8 @@
"idle_conn_timeout_seconds": 120,
"connect_timeout_seconds": 5,
"failure_cooldown_seconds": 15,
- "attempt_timeout_seconds": 0
+ "attempt_timeout_seconds": 0,
+ "first_event_timeout_seconds": 0
},
"logging": {
"level": "info",
diff --git a/internal/admin/api_keys_test.go b/internal/admin/api_keys_test.go
deleted file mode 100644
index 0a9bbee..0000000
--- a/internal/admin/api_keys_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package admin
-
-import (
- "encoding/json"
- "strings"
- "testing"
-
- "opencode2api/internal/config"
-)
-
-func TestManagedKeyLifecycle(t *testing.T) {
- base := "sk-existing-1234567890"
- cfg := config.Config{ServerKeys: []string{base}}
- key := "sk-client-12345678901234"
- if err := addAPIKey(&cfg, "笔记助手", key); err != nil {
- t.Fatal(err)
- }
- if err := addAPIKey(&cfg, "重复", key); err == nil {
- t.Fatal("duplicate accepted")
- }
- views, _ := json.Marshal(apiKeyViews(cfg))
- if strings.Contains(string(views), key) || strings.Contains(string(views), base) {
- t.Fatal("list leaked secret")
- }
- id := config.Fingerprint(key)
- enabled := false
- candidate := config.Clone(cfg)
- if err := changeAPIKey(&candidate, id, nil, &enabled, false); err != nil {
- t.Fatal(err)
- }
- if candidate.ServerKeyEnabled(key) || !cfg.ServerKeyEnabled(key) {
- t.Fatal("clone metadata aliases source")
- }
- cfg = candidate
- name := "新的名称"
- if err := changeAPIKey(&cfg, id, &name, nil, false); err != nil {
- t.Fatal(err)
- }
- if cfg.ServerKeyMetadata[id].Name != name {
- t.Fatal("rename not applied")
- }
- if err := changeAPIKey(&cfg, config.Fingerprint(base), nil, &enabled, false); err == nil {
- t.Fatal("last active key disabled")
- }
- // Failed mutations are applied only to a clone by RuntimeManager.Update.
- cfg = config.Config{ServerKeys: []string{base, key}}
- if err := changeAPIKey(&cfg, id, nil, nil, true); err != nil {
- t.Fatal(err)
- }
- if len(cfg.ServerKeys) != 1 || cfg.ServerKeys[0] != base {
- t.Fatal("wrong key deleted")
- }
- if err := changeAPIKey(&cfg, config.Fingerprint(base), nil, nil, true); err == nil {
- t.Fatal("last key deleted")
- }
-}
-
-func TestCustomKeyValidation(t *testing.T) {
- for _, key := range []string{"short", "long-key with-space-123", "含中文的密钥12345678901234567890", "secret\n12345678901234567890"} {
- cfg := config.Config{}
- if addAPIKey(&cfg, "test", key) == nil {
- t.Errorf("invalid key accepted")
- }
- }
-}
diff --git a/internal/admin/availability.go b/internal/admin/availability.go
new file mode 100644
index 0000000..7e0c619
--- /dev/null
+++ b/internal/admin/availability.go
@@ -0,0 +1,26 @@
+package admin
+
+import (
+ "net/http"
+ "opencode2api/internal/httpx"
+)
+
+func (a *Server) handleAvailability(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": a.manager.AvailabilitySnapshot()})
+}
+
+func (a *Server) handleRestoreModel(w http.ResponseWriter, r *http.Request) {
+ var input struct {
+ Model string `json:"model"`
+ }
+ if err := decodeAdminJSON(w, r, &input); err != nil {
+ writeAdminError(w, 400, "invalid_request", err.Error())
+ return
+ }
+ if err := a.manager.RestoreModel(input.Model); err != nil {
+ writeAdminError(w, 400, "restore_failed", a.manager.Redact(err.Error()))
+ return
+ }
+ a.handleAvailability(w, r)
+}
diff --git a/internal/admin/model_quotas_test.go b/internal/admin/model_quotas_test.go
deleted file mode 100644
index fd38825..0000000
--- a/internal/admin/model_quotas_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package admin
-
-import (
- "context"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "strings"
- "testing"
-)
-
-const validQuota = `{"usage":{"rolling":{"status":"ok","percent":19,"resetsAt":"2026-09-20T12:00:00Z"},"weekly":{"status":"rate-limited","percent":100,"resetsAt":"2026-09-21T00:00:00Z"},"monthly":{"status":"ok","percent":0,"resetsAt":"2026-10-20T00:00:00Z"}}}`
-
-func TestQuotaDecode(t *testing.T) {
- windows, err := decodeQuota(strings.NewReader(validQuota))
- if err != nil {
- t.Fatal(err)
- }
- if windows["rolling"].RemainingPercent != 81 || windows["weekly"].RemainingPercent != 0 || windows["monthly"].RemainingPercent != 100 {
- t.Fatal("incorrect percentage semantics")
- }
- for _, raw := range []string{`{}`, strings.Replace(validQuota, `"percent":19`, `"percent":null`, 1), strings.Replace(validQuota, `"percent":19`, `"percent":101`, 1), strings.Replace(validQuota, "2026-09-20T12:00:00Z", "invalid", 1), strings.Replace(validQuota, `"status":"ok"`, `"status":"unknown"`, 1)} {
- if _, err := decodeQuota(strings.NewReader(raw)); err == nil {
- t.Fatal("malformed quota accepted")
- }
- }
-}
-
-func TestQuotaFailureRetainsLastGoodAndRedacts(t *testing.T) {
- failing := false
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Header.Get("Authorization") != "Bearer test-upstream-secret" {
- t.Error("missing authorization")
- }
- if r.Header.Get("User-Agent") != "opencode2api-admin/1.0" {
- t.Error("incorrect identity")
- }
- if failing {
- w.WriteHeader(401)
- w.Write([]byte(`{"error":"test-upstream-secret"}`))
- return
- }
- w.Write([]byte(validQuota))
- }))
- defer srv.Close()
- first := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", quotaCacheEntry{})
- if first.Account.Status != "ok" {
- t.Fatal(first.Account.Error)
- }
- failing = true
- stale := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", first)
- if stale.Account.Status != "stale" || stale.Account.Windows["rolling"].RemainingPercent != 81 || !stale.Account.FetchedAt.Equal(*first.Account.FetchedAt) {
- t.Fatal("last known quota lost")
- }
- encoded, _ := json.Marshal(stale.Account)
- if strings.Contains(string(encoded), "test-upstream-secret") {
- t.Fatal("secret leaked")
- }
- missing := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", quotaCacheEntry{})
- if missing.Account.Status != "unavailable" || missing.Account.Windows != nil {
- t.Fatal("invented unavailable balance")
- }
-}
-
-func TestQuotaDoesNotFollowRedirect(t *testing.T) {
- reached := false
- target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached = true }))
- defer target.Close()
- source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, target.URL, 302) }))
- defer source.Close()
- if _, err := fetchQuota(context.Background(), source.URL, "secret"); err == nil || reached {
- t.Fatal("redirect leaked credentials")
- }
-}
diff --git a/internal/admin/server.go b/internal/admin/server.go
index de59e3d..3e6453a 100644
--- a/internal/admin/server.go
+++ b/internal/admin/server.go
@@ -55,6 +55,8 @@ func (a *Server) Handler() http.Handler {
mux.Handle("PUT /api/account", a.authenticate(a.csrf(http.HandlerFunc(a.handleAccount))))
mux.Handle("GET /api/monitor", a.authenticate(http.HandlerFunc(a.handleMonitor)))
mux.Handle("GET /api/debug/models", a.authenticate(http.HandlerFunc(a.handleDebugModels)))
+ mux.Handle("GET /api/models/availability", a.authenticate(http.HandlerFunc(a.handleAvailability)))
+ mux.Handle("POST /api/models/restore", a.authenticate(a.csrf(http.HandlerFunc(a.handleRestoreModel))))
mux.Handle("GET /api/rotation", a.authenticate(http.HandlerFunc(a.handleRotation)))
mux.Handle("PUT /api/rotation", a.authenticate(a.csrf(http.HandlerFunc(a.handleSaveRotation))))
mux.Handle("POST /api/rotation/current", a.authenticate(a.csrf(http.HandlerFunc(a.handleSelectRotation))))
diff --git a/internal/config/config.go b/internal/config/config.go
index d1d8446..5155f94 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -85,13 +85,14 @@ type WebUIConfig struct {
}
type PerformanceConfig struct {
- MaxIdleConns int `json:"max_idle_conns"`
- MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"`
- MaxConnsPerHost int `json:"max_conns_per_host"`
- IdleConnTimeoutSeconds int `json:"idle_conn_timeout_seconds"`
- ConnectTimeoutSeconds int `json:"connect_timeout_seconds"`
- FailureCooldownSeconds int `json:"failure_cooldown_seconds"`
- AttemptTimeoutSeconds int `json:"attempt_timeout_seconds"`
+ MaxIdleConns int `json:"max_idle_conns"`
+ MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"`
+ MaxConnsPerHost int `json:"max_conns_per_host"`
+ IdleConnTimeoutSeconds int `json:"idle_conn_timeout_seconds"`
+ ConnectTimeoutSeconds int `json:"connect_timeout_seconds"`
+ FailureCooldownSeconds int `json:"failure_cooldown_seconds"`
+ AttemptTimeoutSeconds int `json:"attempt_timeout_seconds"`
+ FirstEventTimeoutSeconds int `json:"first_event_timeout_seconds"`
}
// AttemptTimeout bounds how long a single upstream attempt may wait for
@@ -198,6 +199,9 @@ func Normalize(path string, cfg Config) (Config, error) {
if cfg.Performance.AttemptTimeoutSeconds < 0 {
return Config{}, errors.New("performance.attempt_timeout_seconds must not be negative (0 keeps the retry timeout)")
}
+ if cfg.Performance.FirstEventTimeoutSeconds < 0 || cfg.Performance.FirstEventTimeoutSeconds > 86400 {
+ return Config{}, errors.New("performance.first_event_timeout_seconds must be between 0 and 86400 (0 disables the first-event timeout)")
+ }
if cfg.Logging.Level != "debug" && cfg.Logging.Level != "info" && cfg.Logging.Level != "warn" && cfg.Logging.Level != "error" {
return Config{}, errors.New("logging.level must be debug, info, warn, or error")
}
diff --git a/internal/config/rotation_test.go b/internal/config/rotation_test.go
deleted file mode 100644
index b0d754f..0000000
--- a/internal/config/rotation_test.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package config
-
-import "testing"
-
-func TestRotationConfigValidationAndClone(t *testing.T) {
- c := RotationConfig{}
- c.Defaults()
- if err := c.Validate(nil); err != nil {
- t.Fatal(err)
- }
- for _, change := range []func(*RotationConfig){
- func(c *RotationConfig) { c.SOTA.Alias = c.Sweet.Alias },
- func(c *RotationConfig) { c.SOTA.Alias = "glm-5.3" },
- func(c *RotationConfig) { c.SOTA.Alias = "real-model" },
- func(c *RotationConfig) { c.Sweet.Alias = "bad alias" },
- func(c *RotationConfig) { c.SOTA.Order = []string{"other-model"} },
- func(c *RotationConfig) { c.Sweet.Order = []string{"glm-5.3"} },
- func(c *RotationConfig) { c.Sweet.Order = []string{"x", "x"} },
- func(c *RotationConfig) { c.FirstOutputSeconds = -1 },
- } {
- candidate := Clone(Config{Rotation: c}).Rotation
- change(&candidate)
- if candidate.Validate([]string{"real-model"}) == nil {
- t.Fatal("accepted invalid config", candidate)
- }
- }
- clone := Clone(Config{Rotation: c})
- clone.Rotation.SOTA.Order[0] = "changed"
- if c.SOTA.Order[0] != "deepseek-v4.1-flash" {
- t.Fatal("cloning aliased config")
- }
-}
diff --git a/internal/gateway/availability.go b/internal/gateway/availability.go
new file mode 100644
index 0000000..5ffb644
--- /dev/null
+++ b/internal/gateway/availability.go
@@ -0,0 +1,180 @@
+package gateway
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "opencode2api/internal/config"
+ "opencode2api/internal/identity"
+ "opencode2api/internal/models"
+ wire "opencode2api/internal/protocol"
+)
+
+func (m *RuntimeManager) AvailabilitySnapshot() []models.Availability {
+ items := []models.Availability{}
+ r := m.current.Load()
+ if r == nil {
+ return items
+ }
+ for _, model := range r.gateway.catalog.List() {
+ if r.gateway.catalog.IsFreeModel(model) {
+ items = append(items, r.availability.Get(model))
+ }
+ }
+ return items
+}
+
+func (m *RuntimeManager) RestoreModel(model string) error {
+ m.updateMu.Lock()
+ defer m.updateMu.Unlock()
+ for _, item := range m.AvailabilitySnapshot() {
+ if item.Model == model {
+ return m.current.Load().availability.Restore(model, time.Now().UTC())
+ }
+ }
+ return errors.New("unknown free model")
+}
+
+func (m *RuntimeManager) startAvailabilityChecks() {
+ ctx, cancel := context.WithCancel(m.root)
+ m.availabilityCancel = cancel
+ go func() {
+ ticker := time.NewTicker(time.Minute)
+ defer ticker.Stop()
+ for {
+ m.checkFreeModels(ctx)
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ }
+ }
+ }()
+}
+
+func (m *RuntimeManager) checkFreeModels(ctx context.Context) {
+ for _, item := range m.AvailabilitySnapshot() {
+ if ctx.Err() != nil {
+ return
+ }
+ r := m.current.Load()
+ if r == nil {
+ return
+ }
+ item = r.availability.Get(item.Model)
+ if time.Now().Before(item.NextCheck) {
+ continue
+ }
+ ok, reason, channel, attempted := r.gateway.probeFreeModel(ctx, item.Model)
+ if !attempted || ctx.Err() != nil {
+ continue
+ }
+ // Config changes may replace credentials or endpoints during a probe.
+ m.updateMu.Lock()
+ if m.current.Load() == r {
+ if err := r.availability.Record(item.Model, item.Generation, ok, reason, channel, time.Now().UTC()); err != nil {
+ m.logger.Warn("model availability state save failed", "error", err)
+ }
+ m.logger.Info("free model availability checked", "component", "models", "event", "availability_checked", "model", item.Model, "available", ok, "reason", reason, "channel", channel)
+ }
+ m.updateMu.Unlock()
+ }
+}
+
+func (g *Gateway) probeFreeModel(ctx context.Context, model string) (success bool, reason, channel string, attempted bool) {
+ if !g.catalog.IsFreeModel(model) {
+ return false, "not_free", "", false
+ }
+ d := g.catalog.Diagnostic(model, wire.Chat, g.zenNodes.Len() > 0, false, g.cfg.Anonymous)
+ protocol := d.NativeProtocols[config.TierZen]
+ if !d.AvailableZen || !g.catalog.Supported(model) || protocol == wire.SystemOne {
+ return false, "unsupported_probe", "", false
+ }
+ payload := map[string]any{"model": model, "stream": true, "max_tokens": 64, "messages": []any{map[string]any{"role": "user", "content": "Reply with OK."}}}
+ converted, err := wire.ConvertRequest(wire.Chat, protocol, payload)
+ if err != nil {
+ return false, "request_conversion_error", "", false
+ }
+ b, err := json.Marshal(converted)
+ if err != nil {
+ return false, "request_conversion_error", "", false
+ }
+ b = prepareAnonymousBody(b, protocol)
+ type lane struct {
+ key, name string
+ client *http.Client
+ }
+ var lanes []lane
+ if g.cfg.Anonymous {
+ cursor := g.anonymous.CursorFor("availability:" + model)
+ if node := cursor.Next(); node != nil {
+ lanes = append(lanes, lane{anonymousZenKey, "anonymous", node.proxy.client})
+ }
+ }
+ cursor := g.zenNodes.CursorFor("availability:" + model)
+ if node := cursor.Next(); node != nil {
+ if proxy := g.zenNodes.Proxy(node); proxy != nil {
+ lanes = append(lanes, lane{node.key, "zen", proxy.client})
+ }
+ }
+ for _, lane := range lanes {
+ if ctx.Err() != nil {
+ return false, "canceled", "", false
+ }
+ attempted, channel = true, lane.name
+ probeCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
+ req, err := newUpstreamRequest(probeCtx, g.cfg.Upstream.Zen, protocol, b, identity.RequestIDs{Session: "availability:" + model}, lane.key)
+ if err == nil {
+ // Probe traffic never updates production key/proxy cooldowns or usage.
+ var resp *http.Response
+ resp, err = lane.client.Do(req)
+ if err == nil {
+ reason = fmt.Sprintf("http_%d", resp.StatusCode)
+ if resp.StatusCode/100 == 2 {
+ if strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {
+ _, err = wire.CollapseStream(io.LimitReader(resp.Body, 1<<20), protocol, model)
+ } else {
+ var document map[string]any
+ err = json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&document)
+ if err == nil && (document == nil || document["error"] != nil) {
+ err = errors.New("invalid response")
+ }
+ if err == nil {
+ field := "choices"
+ if protocol == wire.Anthropic {
+ field = "content"
+ } else if protocol == wire.Responses {
+ field = "output"
+ }
+ if _, ok := document[field].([]any); !ok {
+ err = errors.New("invalid response schema")
+ }
+ }
+ }
+ success = err == nil
+ if !success {
+ reason = "invalid_or_incomplete_response"
+ }
+ }
+ resp.Body.Close()
+ } else {
+ reason = "transport_error"
+ }
+ }
+ if probeCtx.Err() != nil {
+ success = false
+ reason = "probe_timeout"
+ }
+ cancel()
+ if success {
+ return true, "probe_succeeded", channel, true
+ }
+ }
+ return success, reason, channel, attempted
+}
diff --git a/internal/gateway/first_event.go b/internal/gateway/first_event.go
new file mode 100644
index 0000000..e7e80c2
--- /dev/null
+++ b/internal/gateway/first_event.go
@@ -0,0 +1,94 @@
+package gateway
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+)
+
+var errFirstEventTimeout = fmt.Errorf("upstream first SSE event timed out: %w", context.DeadlineExceeded)
+
+type attemptBody struct {
+ io.Reader
+ body io.ReadCloser
+ cancel context.CancelCauseFunc
+}
+
+func (b *attemptBody) Close() error {
+ b.cancel(nil)
+ return b.body.Close()
+}
+
+// Wait before returning a successful SSE response to the retry loop, while
+// nothing has been committed downstream. Keep every byte for native forwarding.
+// Comments and incomplete frames do not count as the first event.
+func doInferenceAttempt(client *http.Client, req *http.Request, timeout time.Duration) (*http.Response, error) {
+ if timeout <= 0 || strings.HasSuffix(req.URL.Path, "/systemone") {
+ return client.Do(req)
+ }
+ ctx, cancel := context.WithCancelCause(req.Context())
+ resp, err := client.Do(req.Clone(ctx))
+ if err != nil {
+ cancel(nil)
+ return resp, err
+ }
+ if resp.StatusCode/100 != 2 || !strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") {
+ resp.Body = &attemptBody{Reader: resp.Body, body: resp.Body, cancel: cancel}
+ return resp, nil
+ }
+ timer := time.AfterFunc(timeout, func() { cancel(errFirstEventTimeout) })
+ reader := bufio.NewReader(resp.Body)
+ prefix, err := readFirstEvent(reader)
+ stopped := timer.Stop()
+ if !stopped && ctx.Err() == nil {
+ // Stop(false) means the callback may still be about to run.
+ cancel(errFirstEventTimeout)
+ }
+ if cause := context.Cause(ctx); cause != nil {
+ err = cause
+ }
+ if err != nil {
+ cancel(nil)
+ resp.Body.Close()
+ return nil, err
+ }
+ resp.Body = &attemptBody{Reader: io.MultiReader(bytes.NewReader(prefix), reader), body: resp.Body, cancel: cancel}
+ return resp, nil
+}
+
+func readFirstEvent(reader *bufio.Reader) ([]byte, error) {
+ const maxPrelude = 1 << 20
+ var prefix, line []byte
+ hasData := false
+ for {
+ part, err := reader.ReadSlice('\n')
+ if len(prefix)+len(part) > maxPrelude {
+ return nil, errors.New("upstream SSE prelude exceeds 1 MiB")
+ }
+ prefix = append(prefix, part...)
+ line = append(line, part...)
+ if errors.Is(err, bufio.ErrBufferFull) {
+ continue
+ }
+ if err != nil {
+ if errors.Is(err, io.EOF) {
+ err = io.ErrUnexpectedEOF
+ }
+ return nil, err
+ }
+ text := strings.TrimSuffix(strings.TrimSuffix(string(line), "\n"), "\r")
+ line = line[:0]
+ if text == "" && hasData {
+ return prefix, nil
+ }
+ if strings.HasPrefix(text, "data:") || text == "data" {
+ hasData = true
+ }
+ }
+}
diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go
index 8605310..93d074c 100644
--- a/internal/gateway/pool.go
+++ b/internal/gateway/pool.go
@@ -245,6 +245,9 @@ func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTrans
// route is unavailable. HTTP responses and unrelated transport/protocol errors
// must not evict a proxy.
func isProxyFailure(err error) bool {
+ if errors.Is(err, errFirstEventTimeout) {
+ return false // The upstream accepted HTTP; slow generation is not a broken proxy.
+ }
if err == nil {
return false
}
diff --git a/internal/gateway/rotation_test.go b/internal/gateway/rotation_test.go
deleted file mode 100644
index a318abe..0000000
--- a/internal/gateway/rotation_test.go
+++ /dev/null
@@ -1,373 +0,0 @@
-package gateway
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "io"
- "log/slog"
- "net/http"
- "net/http/httptest"
- "slices"
- "strings"
- "sync"
- "testing"
- "time"
-
- "opencode2api/internal/config"
- wire "opencode2api/internal/protocol"
- "opencode2api/internal/telemetry"
-)
-
-func rotationGateway(t *testing.T, models []string, fn http.HandlerFunc) *Gateway {
- t.Helper()
- up := httptest.NewServer(fn)
- t.Cleanup(up.Close)
- cfg := config.Config{ServerKeys: []string{"local"}, GoKeys: []string{"go-key-one", "go-key-two"}, Prefer: config.TierGo, Upstream: config.UpstreamConfig{Go: up.URL}, Retry: config.RetryConfig{MaxAttempts: 99, TimeoutSeconds: 15}, Models: config.ModelsConfig{RefreshSeconds: 300}, Performance: config.PerformanceConfig{ConnectTimeoutSeconds: 1}}
- g, err := New(cfg, slog.New(slog.NewTextHandler(io.Discard, nil)), nil)
- if err != nil {
- t.Fatal(err)
- }
- native := map[string]wire.Protocol{}
- for _, model := range models {
- native[model] = wire.Chat
- }
- g.catalog.ReplaceWithCapabilities(nil, models, map[config.Tier]map[string]wire.Protocol{config.TierGo: native}, nil, nil)
- t.Cleanup(func() {
- for _, p := range g.transports.items {
- p.client.CloseIdleConnections()
- }
- })
- return g
-}
-func modelBody(r *http.Request) map[string]any {
- var p map[string]any
- _ = json.NewDecoder(r.Body).Decode(&p)
- return p
-}
-func replyChat(w http.ResponseWriter, model string, stream bool) {
- if stream {
- w.Header().Set("Content-Type", "text/event-stream")
- fmt.Fprintf(w, "data: {\"id\":\"answer\",\"model\":%q,\"choices\":[{\"delta\":{\"content\":\"complete answer\"}}]}\n\ndata: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":2,\"completion_tokens\":3}}\n\ndata: [DONE]\n\n", model)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- fmt.Fprintf(w, `{"id":"answer","object":"chat.completion","model":%q,"choices":[{"index":0,"message":{"role":"assistant","content":"complete answer"},"finish_reason":"stop"}],"usage":{"prompt_tokens":2,"completion_tokens":3}}`, model)
-}
-func callRotation(g *Gateway, model string, stream bool) (*httptest.ResponseRecorder, *telemetry.RequestMeta) {
- r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(fmt.Sprintf(`{"model":%q,"stream":%t,"messages":[{"role":"user","content":"hi"}]}`, model, stream)))
- r.Header.Set("Authorization", "Bearer local")
- meta := &telemetry.RequestMeta{}
- r = r.WithContext(telemetry.WithRequestMeta(r.Context(), meta))
- w := httptest.NewRecorder()
- g.Handler().ServeHTTP(w, r)
- return w, meta
-}
-func TestRotationBudgets(t *testing.T) {
- for _, tc := range []struct {
- name string
- status func(string, int) int
- want int
- code int
- }{
- {"ordinary three models times three", func(string, int) int { return 500 }, 9, 503},
- {"quota skips more than three", func(m string, _ int) int {
- if m == "f" {
- return 200
- }
- return 429
- }, 6, 200},
- {"whole group quota", func(string, int) int { return 429 }, 6, 503},
- {"mixed quota keeps ordinary budget", func(_ string, n int) int {
- if n == 2 {
- return 429
- }
- return 500
- }, 8, 503},
- } {
- t.Run(tc.name, func(t *testing.T) {
- calls := []string{}
- per := map[string]int{}
- g := rotationGateway(t, []string{"a", "b", "c", "d", "e", "f"}, func(w http.ResponseWriter, r *http.Request) {
- p := modelBody(r)
- m := p["model"].(string)
- calls = append(calls, m)
- per[m]++
- status := tc.status(m, len(calls))
- if status == 200 {
- replyChat(w, m, false)
- return
- }
- w.Header().Set("Retry-After", "120")
- w.WriteHeader(status)
- fmt.Fprint(w, `{"error":{"message":"failed"}}`)
- })
- w, _ := callRotation(g, "sweet", false)
- if len(calls) != tc.want || w.Code != tc.code {
- t.Fatalf("calls=%v status=%d body=%s", calls, w.Code, w.Body)
- }
- for _, node := range g.goNodes.nodes {
- if node.cooldownUntil.Load() != 0 {
- t.Fatal("model failure cooled entire key")
- }
- }
- if tc.name == "whole group quota" {
- for _, until := range g.rotation.Snapshot().Groups[1].Paused {
- if time.Until(until) < 119*time.Second {
- t.Fatal("Retry-After ignored")
- }
- }
- }
- })
- }
-}
-func TestRotationSuccessAliasesAndDirectModels(t *testing.T) {
- calls := []string{}
- g := rotationGateway(t, []string{"glm-5.3-flash", "deepseek-v4.1-flash", "glm-5.3"}, func(w http.ResponseWriter, r *http.Request) {
- p := modelBody(r)
- m := p["model"].(string)
- calls = append(calls, m)
- replyChat(w, m, p["stream"] == true)
- })
- for _, alias := range []string{"sota", "sweet"} {
- for _, stream := range []bool{false, true, false} {
- w, meta := callRotation(g, alias, stream)
- if w.Code != 200 || !strings.Contains(w.Body.String(), `"model":"`+alias+`"`) || w.Header().Get("X-Resolved-Model") == "" {
- t.Fatalf("%s: %s", alias, w.Body)
- }
- if meta.Model == alias || meta.ModelAlias != alias || !meta.UsageReported || meta.Usage.Output != 3 {
- t.Fatalf("incorrect real-model usage: %+v", meta)
- }
- }
- }
- if !slices.Equal(calls, []string{"deepseek-v4.1-flash", "deepseek-v4.1-flash", "deepseek-v4.1-flash", "glm-5.3-flash", "glm-5.3-flash", "glm-5.3-flash"}) {
- t.Fatal(calls)
- }
- w, _ := callRotation(g, "glm-5.3", false)
- if !strings.Contains(w.Body.String(), `"model":"glm-5.3"`) || w.Header().Get("X-Resolved-Model") != "" {
- t.Fatal("direct route changed")
- }
- r := httptest.NewRequest("GET", "/v1/models", nil)
- r.Header.Set("Authorization", "Bearer local")
- w = httptest.NewRecorder()
- g.Handler().ServeHTTP(w, r)
- for _, alias := range []string{"sota", "sweet"} {
- if !strings.Contains(w.Body.String(), `"id":"`+alias+`"`) {
- t.Fatal("alias missing")
- }
- }
-}
-func TestRotationStreamingBoundaries(t *testing.T) {
- for _, tc := range []struct {
- name, first string
- wantFirst int
- partial bool
- }{
- {"error before content", "data: {\"error\":{\"type\":\"rate_limit_error\",\"message\":\"rate limit\"}}\n\n", 2, false},
- {"invalid prelude", "data: invalid\n\n", 4, false},
- {"partial then error", "data: {\"id\":\"x\",\"model\":\"a\",\"choices\":[{\"delta\":{\"content\":\"partial original\"}}]}\n\ndata: {\"error\":{\"message\":\"provider failed\"}}\n\n", 1, true},
- {"partial then eof", "data: {\"id\":\"x\",\"model\":\"a\",\"choices\":[{\"delta\":{\"content\":\"partial original\"}}]}\n\n", 1, true},
- } {
- t.Run(tc.name, func(t *testing.T) {
- calls := []string{}
- g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) {
- p := modelBody(r)
- m := p["model"].(string)
- calls = append(calls, m)
- w.Header().Set("Content-Type", "text/event-stream")
- if m == "a" {
- fmt.Fprint(w, tc.first)
- return
- }
- replyChat(w, m, true)
- })
- w, _ := callRotation(g, "sweet", true)
- if len(calls) != tc.wantFirst {
- t.Fatal(calls)
- }
- if tc.partial {
- if strings.Contains(w.Body.String(), "complete answer") || !strings.Contains(w.Body.String(), "partial original") || !strings.Contains(w.Body.String(), "upstream_error") {
- t.Fatal(w.Body)
- }
- if g.rotation.Snapshot().Groups[1].Current != "b" {
- t.Fatal("next request was not advanced")
- }
- w, _ = callRotation(g, "sweet", true)
- if calls[len(calls)-1] != "b" || !strings.Contains(w.Body.String(), "complete answer") {
- t.Fatal(calls, w.Body)
- }
- } else if !strings.Contains(w.Body.String(), "complete answer") || strings.Contains(w.Body.String(), "upstream_error") {
- t.Fatal(w.Body)
- }
- })
- }
-}
-func TestRotationMalformedResponseAndCrossProtocol(t *testing.T) {
- for _, endpoint := range []string{"/v1/chat/completions", "/v1/responses", "/v1/messages"} {
- t.Run(endpoint, func(t *testing.T) {
- calls := 0
- g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) {
- p := modelBody(r)
- calls++
- if p["model"] == "a" {
- fmt.Fprint(w, `{"unexpected":"schema"}`)
- return
- }
- if r.URL.Path != "/v1/messages" {
- t.Errorf("protocol not reconverted: %s", r.URL.Path)
- }
- fmt.Fprint(w, `{"id":"x","type":"message","role":"assistant","model":"b","content":[{"type":"text","text":"anthropic answer"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"output_tokens":3}}`)
- })
- g.catalog.ReplaceWithCapabilities(nil, []string{"a", "b"}, map[config.Tier]map[string]wire.Protocol{config.TierGo: {"a": wire.Chat, "b": wire.Anthropic}}, nil, nil)
- input := `{"model":"sweet","messages":[{"role":"user","content":"hello"}],"max_tokens":50}`
- if endpoint == "/v1/responses" {
- input = `{"model":"sweet","input":"hello"}`
- }
- r := httptest.NewRequest("POST", endpoint, strings.NewReader(input))
- r.Header.Set("Authorization", "Bearer local")
- w := httptest.NewRecorder()
- g.Handler().ServeHTTP(w, r)
- if calls != 4 || w.Code != 200 || !strings.Contains(w.Body.String(), "anthropic answer") || !strings.Contains(w.Body.String(), `"model":"sweet"`) {
- t.Fatal(calls, w.Code, w.Body)
- }
- })
- }
-}
-func TestRotationFirstOutputTimeoutAndCancellation(t *testing.T) {
- t.Run("timeout before content", func(t *testing.T) {
- var mu sync.Mutex
- calls := []string{}
- g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) {
- m := modelBody(r)["model"].(string)
- mu.Lock()
- calls = append(calls, m)
- mu.Unlock()
- if m == "a" {
- w.Header().Set("Content-Type", "text/event-stream")
- fmt.Fprint(w, "data: {\"id\":\"x\",\"choices\":[{\"delta\":{\"role\":\"assistant\"}}]}\n\n")
- w.(http.Flusher).Flush()
- <-r.Context().Done()
- return
- }
- replyChat(w, m, true)
- })
- cfg := g.cfg.Rotation
- cfg.FirstOutputSeconds = 1
- g.rotation.Configure(cfg)
- w, _ := callRotation(g, "sweet", true)
- if w.Code != 200 || w.Header().Get("X-Resolved-Model") != "b" {
- t.Fatal(w.Code, w.Body)
- }
- mu.Lock()
- defer mu.Unlock()
- if !slices.Equal(calls, []string{"a", "a", "a", "b"}) {
- t.Fatal(calls)
- }
- })
- t.Run("caller cancellation", func(t *testing.T) {
- entered := make(chan struct{})
- g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) {
- _, _ = io.Copy(io.Discard, r.Body)
- close(entered)
- <-r.Context().Done()
- })
- ctx, cancel := context.WithCancel(context.Background())
- r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"sweet","messages":[],"stream":true}`)).WithContext(ctx)
- r.Header.Set("Authorization", "Bearer local")
- done := make(chan struct{})
- go func() { g.Handler().ServeHTTP(httptest.NewRecorder(), r); close(done) }()
- <-entered
- cancel()
- <-done
- state := g.rotation.Snapshot().Groups[1]
- if state.Current != "a" || len(state.Paused) != 0 {
- t.Fatal("cancel rotated", state)
- }
- })
-}
-
-func TestRotationStreamingCrossProtocol(t *testing.T) {
- for _, endpoint := range []string{"/v1/chat/completions", "/v1/responses", "/v1/messages"} {
- t.Run(endpoint, func(t *testing.T) {
- calls := 0
- g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) {
- p := modelBody(r)
- calls++
- if p["model"] == "a" {
- w.WriteHeader(429)
- return
- }
- if r.URL.Path != "/v1/messages" {
- t.Errorf("wrong protocol %s", r.URL.Path)
- }
- fmt.Fprint(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"x\",\"model\":\"b\",\"usage\":{\"input_tokens\":2}}}\n\nevent: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\nevent: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"full answer\"}}\n\nevent: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":3}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")
- })
- g.catalog.ReplaceWithCapabilities(nil, []string{"a", "b"}, map[config.Tier]map[string]wire.Protocol{config.TierGo: {"a": wire.Chat, "b": wire.Anthropic}}, nil, nil)
- input := `{"model":"sweet","stream":true,"messages":[{"role":"user","content":"hello"}],"max_tokens":50}`
- if endpoint == "/v1/responses" {
- input = `{"model":"sweet","stream":true,"input":"hello"}`
- }
- r := httptest.NewRequest("POST", endpoint, strings.NewReader(input))
- r.Header.Set("Authorization", "Bearer local")
- w := httptest.NewRecorder()
- g.Handler().ServeHTTP(w, r)
- if calls != 2 || w.Code != 200 || !strings.Contains(w.Body.String(), "full answer") || !strings.Contains(w.Body.String(), `"model":"sweet"`) || strings.Contains(w.Body.String(), "upstream_error") {
- t.Fatal(calls, w.Code, w.Body)
- }
- })
- }
-}
-
-type signalWriter struct {
- *httptest.ResponseRecorder
- once sync.Once
- first chan struct{}
-}
-
-func (w *signalWriter) Write(b []byte) (int, error) {
- n, e := w.ResponseRecorder.Write(b)
- w.once.Do(func() { close(w.first) })
- return n, e
-}
-func TestRotationInflightPinnedAndCancelAfterOutput(t *testing.T) {
- for _, cancelClient := range []bool{false, true} {
- t.Run(fmt.Sprint(cancelClient), func(t *testing.T) {
- resume := make(chan struct{})
- g := rotationGateway(t, []string{"a", "b"}, func(w http.ResponseWriter, r *http.Request) {
- modelBody(r)
- fmt.Fprint(w, "data: {\"id\":\"x\",\"model\":\"a\",\"choices\":[{\"delta\":{\"content\":\"first\"}}]}\n\n")
- w.(http.Flusher).Flush()
- select {
- case <-resume:
- fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\" last\"}}]}\n\ndata: [DONE]\n\n")
- case <-r.Context().Done():
- }
- })
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"sweet","stream":true,"messages":[]}`)).WithContext(ctx)
- r.Header.Set("Authorization", "Bearer local")
- w := &signalWriter{ResponseRecorder: httptest.NewRecorder(), first: make(chan struct{})}
- done := make(chan struct{})
- go func() { g.Handler().ServeHTTP(w, r); close(done) }()
- <-w.first
- if cancelClient {
- cancel()
- } else {
- if e := g.rotation.Manual("sweet", "b"); e != nil {
- t.Fatal(e)
- }
- close(resume)
- }
- <-done
- s := g.rotation.Snapshot().Groups[1]
- if cancelClient {
- if s.Current != "a" || len(s.Paused) > 0 {
- t.Fatal("cancel after output rotated")
- }
- } else if s.Current != "b" || !strings.Contains(w.Body.String(), " last") || w.Header().Get("X-Resolved-Model") != "a" {
- t.Fatal("inflight stream interrupted or cursor reverted", s, w.Body)
- }
- })
- }
-}
diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go
index 3a976f7..8a21e9a 100644
--- a/internal/gateway/runtime.go
+++ b/internal/gateway/runtime.go
@@ -18,10 +18,11 @@ import (
)
type gatewayRuntime struct {
- config config.Config
- gateway *Gateway
- handler http.Handler
- cancel context.CancelFunc
+ availability *modelcatalog.AvailabilityStore
+ config config.Config
+ gateway *Gateway
+ handler http.Handler
+ cancel context.CancelFunc
}
type ApplyResult struct {
@@ -31,18 +32,19 @@ type ApplyResult struct {
}
type RuntimeManager struct {
- rotation *rotation.Manager
- configPath string
- root context.Context
- logger *slog.Logger
- monitor *telemetry.Monitor
- hub *telemetry.LogHub
- redactor *config.SecretRedactor
- level *slog.LevelVar
- current atomic.Pointer[gatewayRuntime]
- updateMu sync.Mutex
- effective effectiveListeners
- metadata *modelcatalog.PricingStore
+ rotation *rotation.Manager
+ configPath string
+ root context.Context
+ logger *slog.Logger
+ monitor *telemetry.Monitor
+ hub *telemetry.LogHub
+ redactor *config.SecretRedactor
+ level *slog.LevelVar
+ current atomic.Pointer[gatewayRuntime]
+ updateMu sync.Mutex
+ effective effectiveListeners
+ metadata *modelcatalog.PricingStore
+ availabilityCancel context.CancelFunc
}
type effectiveListeners struct {
@@ -110,6 +112,7 @@ func NewRuntimeManager(root context.Context, configPath string, cfg config.Confi
telemetry.SetLogLevel(manager.level, cfg.Logging.Level)
manager.start(runtime)
manager.metadata.Start(root)
+ manager.startAvailabilityChecks()
return manager, nil
}
@@ -119,9 +122,21 @@ func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) {
return nil, err
}
gateway.rotation = m.rotation
+ availabilityPath := ""
+ if m.configPath != "" {
+ availabilityPath = m.configPath + "." + config.Fingerprint(cfg.Upstream.Zen) + ".availability.json"
+ }
+ availability, err := modelcatalog.NewAvailabilityStore(availabilityPath)
+ if err != nil {
+ return nil, fmt.Errorf("load model availability: %w", err)
+ }
+ if current := m.current.Load(); current != nil && current.config.Upstream.Zen == cfg.Upstream.Zen {
+ availability = current.availability
+ }
gateway.catalog.SetPricingStore(m.metadata)
+ gateway.catalog.SetAvailabilityStore(availability)
gateway.catalog.SetCachePath(modelcatalog.CatalogCachePath(m.configPath))
- return &gatewayRuntime{config: cfg, gateway: gateway, handler: gateway.Handler(), cancel: func() {}}, nil
+ return &gatewayRuntime{config: cfg, gateway: gateway, availability: availability, handler: gateway.Handler(), cancel: func() {}}, nil
}
func (m *RuntimeManager) start(runtime *gatewayRuntime) {
@@ -264,6 +279,9 @@ func (m *RuntimeManager) Reload() (ApplyResult, error) {
}
func (m *RuntimeManager) Shutdown() {
+ if m.availabilityCancel != nil {
+ m.availabilityCancel()
+ }
if current := m.current.Load(); current != nil {
current.cancel()
}
diff --git a/internal/gateway/server_keys_test.go b/internal/gateway/server_keys_test.go
deleted file mode 100644
index a44a6ff..0000000
--- a/internal/gateway/server_keys_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package gateway
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-
- "opencode2api/internal/config"
-)
-
-func TestDisabledServerKeysRejected(t *testing.T) {
- g := &Gateway{cfg: config.Config{ServerKeys: []string{"active-secret", "disabled-secret"}, ServerKeyMetadata: map[string]config.ServerKeyMetadata{config.Fingerprint("disabled-secret"): {Disabled: true}}}}
- h := g.authenticate(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })
- for _, header := range []string{"Authorization", "x-api-key"} {
- for _, key := range []string{"active-secret", "disabled-secret", "unknown"} {
- r := httptest.NewRequest("GET", "/v1/models", nil)
- value := key
- if header == "Authorization" {
- value = "Bearer " + key
- }
- r.Header.Set(header, value)
- w := httptest.NewRecorder()
- h(w, r)
- want := 401
- if key == "active-secret" {
- want = 204
- }
- if w.Code != want {
- t.Errorf("%s status %d want %d", header, w.Code, want)
- }
- }
- }
-}
diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go
index b9d272f..2e15124 100644
--- a/internal/gateway/upstream.go
+++ b/internal/gateway/upstream.go
@@ -78,7 +78,9 @@ func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map
// visible without dumping full payloads. Bodies stay out of attempt
// records; the hub redactor scrubs configured secrets from log output.
if len(errBody) > 0 {
- snippet := string(errBody)
+ redactor := config.NewSecretRedactor()
+ redactor.Replace(g.cfg)
+ snippet := redactor.String(string(errBody))
if len(snippet) > 240 {
snippet = snippet[:240]
}
@@ -300,7 +302,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
}
setRequestCredential(ctx, config.TierZen, "anonymous", "anonymous", true, node.proxy)
started := time.Now()
- resp, err := node.proxy.client.Do(req)
+ resp, err := doInferenceAttempt(node.proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
duration := time.Since(started)
if ctx.Err() != nil {
// The parent budget expired while this attempt was in flight. Its
@@ -576,7 +578,7 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
return nil, err, 0
}
started := time.Now()
- resp, err := proxy.client.Do(req)
+ resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
duration := time.Since(started)
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, proxy, resp, err, duration)
if err != nil {
@@ -645,7 +647,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
keyID := config.KeyDisplayID(node.key)
setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy)
attemptStarted := time.Now()
- resp, err := proxy.client.Do(req)
+ resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second)
attemptDuration := time.Since(attemptStarted)
if ctx.Err() != nil {
// The request budget expired while this attempt was in flight. A
diff --git a/internal/models/availability.go b/internal/models/availability.go
new file mode 100644
index 0000000..7cda86f
--- /dev/null
+++ b/internal/models/availability.go
@@ -0,0 +1,120 @@
+package models
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+const FreeModelCheckInterval = time.Hour
+const FailedModelCheckInterval = 24 * time.Hour
+
+type Availability struct {
+ Model string `json:"model"`
+ Disabled bool `json:"disabled"`
+ CheckedAt time.Time `json:"checked_at,omitempty"`
+ NextCheck time.Time `json:"next_check"`
+ Reason string `json:"reason,omitempty"`
+ Channel string `json:"channel,omitempty"`
+ Generation uint64 `json:"-"`
+}
+
+type AvailabilityStore struct {
+ mu sync.RWMutex
+ path string
+ items map[string]Availability
+}
+
+func NewAvailabilityStore(path string) (*AvailabilityStore, error) {
+ s := &AvailabilityStore{path: path, items: map[string]Availability{}}
+ if path != "" {
+ b, err := os.ReadFile(path)
+ if err == nil {
+ if err = json.Unmarshal(b, &s.items); err != nil {
+ return nil, err
+ }
+ } else if !os.IsNotExist(err) {
+ return nil, err
+ }
+ }
+ if s.items == nil {
+ s.items = map[string]Availability{}
+ }
+ return s, nil
+}
+
+func (s *AvailabilityStore) Get(model string) Availability {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ item := s.items[model]
+ item.Model = model
+ return item
+}
+
+func (s *AvailabilityStore) Disabled(model string) bool { return s.Get(model).Disabled }
+
+// A manual restore invalidates results from probes that were already running.
+func (s *AvailabilityStore) Restore(model string, now time.Time) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ item := s.items[model]
+ previous, existed := s.items[model]
+ item.Model, item.Disabled, item.Reason = model, false, "manually_enabled"
+ item.NextCheck = now.Add(FreeModelCheckInterval)
+ item.Generation++
+ s.items[model] = item
+ if err := s.saveLocked(); err != nil {
+ if existed {
+ s.items[model] = previous
+ } else {
+ delete(s.items, model)
+ }
+ return err
+ }
+ return nil
+}
+
+func (s *AvailabilityStore) Record(model string, generation uint64, success bool, reason, channel string, now time.Time) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ item := s.items[model]
+ if item.Generation != generation {
+ return nil
+ }
+ item.Model, item.Disabled = model, !success
+ item.CheckedAt, item.Reason, item.Channel = now, reason, channel
+ interval := FreeModelCheckInterval
+ if !success {
+ interval = FailedModelCheckInterval
+ }
+ item.NextCheck = now.Add(interval)
+ s.items[model] = item
+ return s.saveLocked()
+}
+
+func (s *AvailabilityStore) saveLocked() error {
+ if s.path == "" {
+ return nil
+ }
+ b, err := json.MarshalIndent(s.items, "", " ")
+ if err != nil {
+ return err
+ }
+ f, err := os.CreateTemp(filepath.Dir(s.path), ".availability-*.tmp")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(f.Name())
+ if _, err = f.Write(b); err == nil {
+ err = f.Sync()
+ }
+ if closeErr := f.Close(); err == nil {
+ err = closeErr
+ }
+ if err != nil {
+ return err
+ }
+ return os.Rename(f.Name(), s.path)
+}
diff --git a/internal/models/catalog.go b/internal/models/catalog.go
index 8f07e79..fd7d3cb 100644
--- a/internal/models/catalog.go
+++ b/internal/models/catalog.go
@@ -61,6 +61,7 @@ type Catalog struct {
updatedAt time.Time
prefer config.Tier
pricing *PricingStore
+ availability *AvailabilityStore
cachePath string
cacheSource string
stale bool
@@ -97,6 +98,12 @@ func (c *Catalog) SetPricingStore(store *PricingStore) {
c.mu.Unlock()
}
+func (c *Catalog) SetAvailabilityStore(store *AvailabilityStore) {
+ c.mu.Lock()
+ c.availability = store
+ c.mu.Unlock()
+}
+
// MetadataSnapshot reports pricing freshness without exposing the store.
func (c *Catalog) MetadataSnapshot() MetadataSnapshot {
c.mu.RLock()
@@ -197,6 +204,9 @@ func (c *Catalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool)
}
func (c *Catalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) {
+ if c.availability != nil && c.availability.Disabled(model) {
+ return Route{}, fmt.Errorf("model %q is disabled after a failed availability check; restore it in the WebUI or wait for the next probe", model)
+ }
keyTiers := c.keyTierOrderLocked(model, hasZenKeys, hasGoKeys)
// OpenCode's public credential is a Zen-only lane. Every free model starts
// there, even if the current catalog only advertises it on Go: an upstream
@@ -291,6 +301,9 @@ func (c *Catalog) RouteForTier(model string, tier config.Tier, hasZenKeys, hasGo
}
c.mu.RLock()
defer c.mu.RUnlock()
+ if c.availability != nil && c.availability.Disabled(model) {
+ return Route{}, fmt.Errorf("model %q is disabled after a failed availability check", model)
+ }
catalogPending := len(c.zen) == 0 && len(c.goModels) == 0
advertised := c.zen[model]
if tier == config.TierGo {
diff --git a/internal/models/pricing.go b/internal/models/pricing.go
index 31d777d..9f5d58e 100644
--- a/internal/models/pricing.go
+++ b/internal/models/pricing.go
@@ -21,7 +21,7 @@ import (
)
const (
- modelsDevDefaultURL = "https://models.dev/api.json"
+ modelsDevDefaultURL = CapabilitiesURL
modelsDevRefresh = 24 * time.Hour
modelsDevTimeout = 30 * time.Second
)
diff --git a/internal/models/pricing_test.go b/internal/models/pricing_test.go
deleted file mode 100644
index 3284d5c..0000000
--- a/internal/models/pricing_test.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package models
-
-import (
- "testing"
-
- "opencode2api/internal/config"
- wire "opencode2api/internal/protocol"
-)
-
-// models.dev publishes limits per provider. The primary OpenCode provider
-// must win for duplicated model IDs, and other OpenCode tiers must still
-// contribute the models they alone describe.
-func TestDecodeModelsDevKeepsLimitsAndMergesTiers(t *testing.T) {
- payload := []byte(`{
- "opencode": {"id":"opencode","models":{
- "shared":{"id":"shared","limit":{"context":1000,"output":100},"cost":{"input":1,"output":2}},
- "zen-only":{"id":"zen-only","limit":{"context":2000,"input":1500,"output":200}}
- }},
- "opencode-go": {"id":"opencode-go","models":{
- "shared":{"id":"shared","limit":{"context":9000,"output":900},"cost":{"input":1,"output":2}},
- "go-only":{"id":"go-only","limit":{"context":4000,"output":400},"cost":{"input":0,"output":0}}
- }},
- "anthropic":{"id":"anthropic","models":{"claude":{"id":"claude","limit":{"context":7}}}}
- }`)
-
- models, err := decodeModelsDev(payload)
- if err != nil {
- t.Fatalf("decodeModelsDev: %v", err)
- }
- if _, exists := models["claude"]; exists {
- t.Fatal("non-OpenCode provider leaked into the metadata")
- }
-
- shared := models["shared"]
- if shared.ContextWindow != 1000 || shared.MaxOutput != 100 {
- t.Errorf("shared = ctx %d/%d, want the primary provider limits 1000/100", shared.ContextWindow, shared.MaxOutput)
- }
- if shared.Input == nil || *shared.Input != 1 {
- t.Errorf("shared input cost = %v, want 1", shared.Input)
- }
-
- zen := models["zen-only"]
- if zen.ContextWindow != 2000 || zen.MaxInput != 1500 || zen.MaxOutput != 200 {
- t.Errorf("zen-only = ctx %d, input %d, output %d; want 2000/1500/200", zen.ContextWindow, zen.MaxInput, zen.MaxOutput)
- }
-
- goOnly, exists := models["go-only"]
- if !exists {
- t.Fatal("go-only model missing; tiers must be merged instead of the first provider winning alone")
- }
- if goOnly.ContextWindow != 4000 || goOnly.MaxOutput != 400 {
- t.Errorf("go-only = ctx %d/%d, want 4000/400", goOnly.ContextWindow, goOnly.MaxOutput)
- }
- if models["go-only"].Output == nil || *models["go-only"].Output != 0 {
- t.Errorf("go-only output cost = %v, want zero output cost preserved", models["go-only"].Output)
- }
-}
-
-// OpenCode's capability catalog stays authoritative; models.dev only fills the
-// limits it omitted so discovery clients still get per-model numbers.
-func TestMetadataForTierFillsMissingLimitsFromModelsDev(t *testing.T) {
- catalog := NewCatalog(config.TierZen, nil)
- catalog.SetPricingStore(&PricingStore{models: map[string]Price{
- "alpha": {ID: "alpha", ContextWindow: 262144, MaxOutput: 32768},
- "beta": {ID: "beta", ContextWindow: 500000, MaxInput: 400000, MaxOutput: 64000},
- }})
- catalog.ReplaceWithCapabilities(
- []string{"alpha", "beta"},
- nil,
- map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}},
- nil,
- map[config.Tier]map[string]Metadata{config.TierZen: {
- "alpha": {ContextWindow: 1000000, MaxOutput: 128000},
- "beta": {Reasoning: true},
- }},
- )
-
- alpha := catalog.MetadataForTier("alpha", config.TierZen)
- if alpha.ContextWindow != 1000000 || alpha.MaxOutput != 128000 {
- t.Errorf("alpha = ctx %d/%d, want the catalog values 1000000/128000", alpha.ContextWindow, alpha.MaxOutput)
- }
-
- beta := catalog.MetadataForTier("beta", config.TierZen)
- if beta.ContextWindow != 500000 || beta.MaxInput != 400000 || beta.MaxOutput != 64000 {
- t.Errorf("beta = ctx %d, input %d, output %d; want 500000/400000/64000", beta.ContextWindow, beta.MaxInput, beta.MaxOutput)
- }
- if !beta.Reasoning {
- t.Error("beta lost its catalog capability flags while limits were filled")
- }
-
- if unknown := catalog.MetadataForTier("gamma", config.TierZen); unknown.ContextWindow != 0 {
- t.Errorf("gamma = ctx %d, want zero for a model no source describes", unknown.ContextWindow)
- }
-}
diff --git a/internal/rotation/state_test.go b/internal/rotation/state_test.go
deleted file mode 100644
index 1566cae..0000000
--- a/internal/rotation/state_test.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package rotation
-
-import (
- "opencode2api/internal/config"
- "path/filepath"
- "slices"
- "sync"
- "testing"
- "time"
-)
-
-func TestStickyPersistenceMembershipAndGeneration(t *testing.T) {
- path := filepath.Join(t.TempDir(), "state.json")
- cfg := config.RotationConfig{}
- cfg.Defaults()
- m, err := New(path, cfg)
- if err != nil {
- t.Fatal(err)
- }
- available := map[string]bool{"deepseek-v4.1-flash": true, "glm-5.3": true, "glm-5.3-flash": true, "z-model": true, "a-model": true}
- m.Sync(available)
- s := m.Snapshot()
- if !slices.Equal(s.Groups[1].Order, []string{"glm-5.3-flash", "a-model", "z-model"}) {
- t.Fatal(s.Groups[1].Order)
- }
- first, _ := m.Select("sota", nil)
- same, _ := m.Select("sota", nil)
- if first != same {
- t.Fatal("success should not rotate")
- }
- m.Fail(first, 15*time.Second, "error")
- next, _ := m.Select("sota", nil)
- if next.Model != "glm-5.3" {
- t.Fatal(next)
- }
- // Old inflight failures cannot undo a manual selection (nor can successes).
- if err := m.Manual("sota", "deepseek-v4.1-flash"); err != nil {
- t.Fatal(err)
- }
- before := m.Snapshot().Groups[0].Generation
- var wg sync.WaitGroup
- for i := 0; i < 20; i++ {
- wg.Add(1)
- go func() { defer wg.Done(); m.Fail(first, time.Second, "stale"); m.Snapshot() }()
- }
- wg.Wait()
- s = m.Snapshot()
- if s.Groups[0].Current != "deepseek-v4.1-flash" || s.Groups[0].Generation != before {
- t.Fatal("stale completion moved cursor")
- }
- // Reordering config and key-only reloads keep operational state.
- cfg.Sweet.Order = []string{"z-model", "a-model", "glm-5.3-flash"}
- m.Configure(cfg)
- available["0-new-model"] = true
- delete(available, "a-model")
- m.Sync(available)
- m2, err := New(path, cfg)
- if err != nil {
- t.Fatal(err)
- }
- m2.Sync(available)
- s = m2.Snapshot()
- if !slices.Equal(s.Groups[1].Order, []string{"z-model", "a-model", "glm-5.3-flash", "0-new-model"}) {
- t.Fatal(s.Groups[1].Order)
- }
- if s.Groups[1].Available["a-model"] {
- t.Fatal("delisted model available")
- }
- if s.Groups[0].Paused[first.Model].IsZero() {
- t.Fatal("pause not persisted")
- }
- if s.Groups[0].Current != "deepseek-v4.1-flash" {
- t.Fatal("current not persisted")
- }
-}
-func TestNoWrapDuplicatesAndUnavailable(t *testing.T) {
- m, _ := New("", config.RotationConfig{})
- m.Sync(map[string]bool{"glm-5.3": true, "kimi-k3": true})
- visited := map[string]bool{}
- for i := 0; i < 2; i++ {
- token, ok := m.Select("sota", visited)
- if !ok {
- t.Fatal(i)
- }
- visited[token.Model] = true
- m.Fail(token, time.Minute, "quota")
- }
- if _, ok := m.Select("sota", visited); ok {
- t.Fatal("revisited model")
- }
- if _, ok := m.Select("sota", nil); ok {
- t.Fatal("paused model selected")
- }
-}
diff --git a/webui/app.js b/webui/app.js
index eac26dd..c9bd51e 100644
--- a/webui/app.js
+++ b/webui/app.js
@@ -12,6 +12,7 @@ let csrf = "",
logRenderPending = false,
toastTimer = null;
const pages = {
+ availability: ["13", "免费模型可用性", "每小时探测,失败后禁用并每 24 小时复测。"],
rotation: ["12", "模型轮转", "共享当前模型、故障切换与尝试记录。"],
overview: ["01", "运行桌面", "最近一小时、进程累计与当前资源状态。"],
guide: ["02", "首次运行", "用六个检查点完成从配置到首个请求。"],
@@ -120,6 +121,7 @@ function openPage(page) {
}, 60000);
}
if (page === "rotation") loadRotation();
+ if (page === "availability") loadAvailability();
if (page === "api-keys") loadAPIKeys();
if (page === "playground" && !debugData) loadDebugModels();
if (page === "diagnostics") {
@@ -157,6 +159,7 @@ function fillConfig(value) {
$("#c-connect").value = value.performance.connect_timeout_seconds;
$("#c-cooldown").value = value.performance.failure_cooldown_seconds;
$("#c-attempt-timeout").value = value.performance.attempt_timeout_seconds;
+ $("#c-first-event-timeout").value = value.performance.first_event_timeout_seconds || 0;
$("#c-level").value = value.logging.level;
$("#c-ring").value = value.logging.ring_size;
$("#c-dump-bodies").checked = !!value.logging.dump_request_bodies;
@@ -225,6 +228,7 @@ $("#config-form").addEventListener("submit", async (event) => {
connect_timeout_seconds: number("#c-connect"),
failure_cooldown_seconds: number("#c-cooldown"),
attempt_timeout_seconds: number("#c-attempt-timeout"),
+ first_event_timeout_seconds: number("#c-first-event-timeout"),
},
logging: {
level: $("#c-level").value,
@@ -1383,3 +1387,53 @@ $("#rotation-form").onsubmit = async (event) => {
}
};
boot();
+
+async function loadAvailability() {
+ try {
+ const data = await api("/api/models/availability");
+ $("#availability-error").textContent = "";
+ $("#availability-models").replaceChildren();
+ for (const item of data.models) {
+ const row = document.createElement("tr");
+ const date = (value) =>
+ value && !value.startsWith("0001-") ? new Date(value).toLocaleString() : "待探测";
+ for (const value of [
+ item.model,
+ item.disabled ? "已禁用" : "已启用",
+ [item.channel, item.reason].filter(Boolean).join(" / ") || "待探测",
+ date(item.checked_at),
+ date(item.next_check),
+ ]) {
+ const cell = document.createElement("td");
+ cell.textContent = value;
+ row.append(cell);
+ }
+ const cell = document.createElement("td");
+ const button = document.createElement("button");
+ button.textContent = "恢复启用";
+ button.disabled = !item.disabled;
+ button.onclick = async () => {
+ button.disabled = true;
+ try {
+ await api("/api/models/restore", {
+ method: "POST",
+ body: JSON.stringify({ model: item.model }),
+ });
+ await loadAvailability();
+ await loadDebugModels();
+ } catch (error) {
+ $("#availability-error").textContent = error.message;
+ button.disabled = false;
+ }
+ };
+ cell.append(button);
+ row.append(cell);
+ $("#availability-models").append(row);
+ }
+ if (!data.models.length)
+ $("#availability-error").textContent = "当前模型目录中没有符合免费资格的模型。";
+ } catch (error) {
+ $("#availability-error").textContent = error.message;
+ }
+}
+$("#availability-refresh").onclick = loadAvailability;
diff --git a/webui/index.html b/webui/index.html
index 743b861..8a54c14 100644
--- a/webui/index.html
+++ b/webui/index.html
@@ -66,6 +66,9 @@
11API Key 管理
+