diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..a2c1af9
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,3 @@
+# Preserve verbatim upstream license notices, including their whitespace.
+agents/pi/LICENSE.node -whitespace
+agents/pi/dist/THIRD_PARTY_NOTICES.txt -whitespace
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ef901bc..54f44e9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -26,7 +26,9 @@ jobs:
with:
node-version: 24.21.0
cache: npm
- cache-dependency-path: internal/controlplane/web/package-lock.json
+ cache-dependency-path: |
+ internal/controlplane/web/package-lock.json
+ agents/pi/package-lock.json
- name: Test issue triage
run: node --test .github/scripts/issue-triage.test.cjs
- name: Confirm toolchain
@@ -40,6 +42,17 @@ jobs:
run: python3 scripts/verify-release-inventory.py
- name: Test release qualification boundaries
run: python3 -m unittest discover -s scripts/tests -p 'test_*.py'
+ - name: Verify Pi candidate inventory
+ run: python3 scripts/verify-pi-inventory.py
+ - name: Build and test pinned Pi runner
+ working-directory: agents/pi
+ run: |
+ npm ci --ignore-scripts
+ npm run build
+ node export-catalog.mjs
+ npm test
+ npm audit --audit-level=high
+ git diff --exit-code -- dist ../../internal/agentharness/pi-catalog.json
- name: Validate release SBOM
run: |
python3 scripts/generate-sbom.py /tmp/esf-ci-sbom.json
diff --git a/.gitignore b/.gitignore
index 52f70b3..1ab5bfa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,6 +11,7 @@ __pycache__/
/tools/brief_lab/dist/
internal/controlplane/web/node_modules/
/agents/opencode/node_modules/
+/agents/pi/node_modules/
!internal/controlplane/web/dist/
!internal/controlplane/web/dist/**
diff --git a/README.md b/README.md
index 49053f4..d45cd36 100644
--- a/README.md
+++ b/README.md
@@ -18,6 +18,8 @@ and adds factory orchestration. See [upstream attribution](docs/upstream.md).
## Features
- Named, operator-configured agent harnesses and repository policies.
+- Opt-in [Pi v1 harness candidate](docs/harness-pi.md) with bounded recovery
+ inside the same Cube microVM.
- Isolated execution in an existing CubeSandbox deployment.
- Deterministic verification gates; agent success alone is not factory success.
- Durable patches, logs, manifests, and verified cleanup outcomes.
diff --git a/agents/pi/LICENSE.node b/agents/pi/LICENSE.node
new file mode 100644
index 0000000..9cc3315
--- /dev/null
+++ b/agents/pi/LICENSE.node
@@ -0,0 +1,2946 @@
+Node.js is licensed for use as follows:
+
+"""
+Copyright Node.js contributors. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
+"""
+
+This license applies to parts of Node.js originating from the
+https://github.com/joyent/node repository:
+
+"""
+Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
+"""
+
+The Node.js license applies to all parts of Node.js that are not externally
+maintained libraries.
+
+The externally maintained libraries used by Node.js are:
+
+- Acorn, located at deps/acorn, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (C) 2012-2022 by various contributors (see AUTHORS)
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ """
+
+- c-ares, located at deps/cares, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) 1998 Massachusetts Institute of Technology
+ Copyright (c) 2007 - 2023 Daniel Stenberg with many contributors, see AUTHORS
+ file.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal in
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ the Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice (including the next
+ paragraph) shall be included in all copies or substantial portions of the
+ Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- merve, located at deps/merve, is licensed as follows:
+ """
+ Copyright 2026 Yagiz Nizipli
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal in
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ the Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- ittapi, located at deps/v8/third_party/ittapi, is licensed as follows:
+ """
+ Copyright (c) 2019 Intel Corporation. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- amaro, located at deps/amaro, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) Marco Ippolito and Amaro contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- swc, located at deps/amaro/dist, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2024 SWC contributors.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+
+- ICU, located at deps/icu-small, is licensed as follows:
+ """
+ UNICODE LICENSE V3
+
+ COPYRIGHT AND PERMISSION NOTICE
+
+ Copyright © 2016-2025 Unicode, Inc.
+
+ NOTICE TO USER: Carefully read the following legal agreement. BY
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of data files and any associated documentation (the "Data Files") or
+ software and any associated documentation (the "Software") to deal in the
+ Data Files or Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
+ copies of the Data Files or Software, and to permit persons to whom the
+ Data Files or Software are furnished to do so, provided that either (a)
+ this copyright and permission notice appear with all copies of the Data
+ Files or Software, or (b) this copyright and permission notice appear in
+ associated Documentation.
+
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
+ THIRD PARTY RIGHTS.
+
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
+ FILES OR SOFTWARE.
+
+ Except as contained in this notice, the name of a copyright holder shall
+ not be used in advertising or otherwise to promote the sale, use or other
+ dealings in these Data Files or Software without prior written
+ authorization of the copyright holder.
+
+ SPDX-License-Identifier: Unicode-3.0
+
+ ----------------------------------------------------------------------
+
+ Third-Party Software Licenses
+
+ This section contains third-party software notices and/or additional
+ terms for licensed third-party software components included within ICU
+ libraries.
+
+ ----------------------------------------------------------------------
+
+ ICU License - ICU 1.8.1 to ICU 57.1
+
+ COPYRIGHT AND PERMISSION NOTICE
+
+ Copyright (c) 1995-2016 International Business Machines Corporation and others
+ All rights reserved.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, and/or sell copies of the Software, and to permit persons
+ to whom the Software is furnished to do so, provided that the above
+ copyright notice(s) and this permission notice appear in all copies of
+ the Software and that both the above copyright notice(s) and this
+ permission notice appear in supporting documentation.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+ OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+ HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
+ SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
+ RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
+ CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+ Except as contained in this notice, the name of a copyright holder
+ shall not be used in advertising or otherwise to promote the sale, use
+ or other dealings in this Software without prior written authorization
+ of the copyright holder.
+
+ All trademarks and registered trademarks mentioned herein are the
+ property of their respective owners.
+
+ ----------------------------------------------------------------------
+
+ Chinese/Japanese Word Break Dictionary Data (cjdict.txt)
+
+ # The Google Chrome software developed by Google is licensed under
+ # the BSD license. Other software included in this distribution is
+ # provided under other licenses, as set forth below.
+ #
+ # The BSD License
+ # http://opensource.org/licenses/bsd-license.php
+ # Copyright (C) 2006-2008, Google Inc.
+ #
+ # All rights reserved.
+ #
+ # Redistribution and use in source and binary forms, with or without
+ # modification, are permitted provided that the following conditions are met:
+ #
+ # Redistributions of source code must retain the above copyright notice,
+ # this list of conditions and the following disclaimer.
+ # Redistributions in binary form must reproduce the above
+ # copyright notice, this list of conditions and the following
+ # disclaimer in the documentation and/or other materials provided with
+ # the distribution.
+ # Neither the name of Google Inc. nor the names of its
+ # contributors may be used to endorse or promote products derived from
+ # this software without specific prior written permission.
+ #
+ #
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ #
+ #
+ # The word list in cjdict.txt are generated by combining three word lists
+ # listed below with further processing for compound word breaking. The
+ # frequency is generated with an iterative training against Google web
+ # corpora.
+ #
+ # * Libtabe (Chinese)
+ # - https://sourceforge.net/project/?group_id=1519
+ # - Its license terms and conditions are shown below.
+ #
+ # * IPADIC (Japanese)
+ # - http://chasen.aist-nara.ac.jp/chasen/distribution.html
+ # - Its license terms and conditions are shown below.
+ #
+ # ---------COPYING.libtabe ---- BEGIN--------------------
+ #
+ # /*
+ # * Copyright (c) 1999 TaBE Project.
+ # * Copyright (c) 1999 Pai-Hsiang Hsiao.
+ # * All rights reserved.
+ # *
+ # * Redistribution and use in source and binary forms, with or without
+ # * modification, are permitted provided that the following conditions
+ # * are met:
+ # *
+ # * . Redistributions of source code must retain the above copyright
+ # * notice, this list of conditions and the following disclaimer.
+ # * . Redistributions in binary form must reproduce the above copyright
+ # * notice, this list of conditions and the following disclaimer in
+ # * the documentation and/or other materials provided with the
+ # * distribution.
+ # * . Neither the name of the TaBE Project nor the names of its
+ # * contributors may be used to endorse or promote products derived
+ # * from this software without specific prior written permission.
+ # *
+ # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ # * OF THE POSSIBILITY OF SUCH DAMAGE.
+ # */
+ #
+ # /*
+ # * Copyright (c) 1999 Computer Systems and Communication Lab,
+ # * Institute of Information Science, Academia
+ # * Sinica. All rights reserved.
+ # *
+ # * Redistribution and use in source and binary forms, with or without
+ # * modification, are permitted provided that the following conditions
+ # * are met:
+ # *
+ # * . Redistributions of source code must retain the above copyright
+ # * notice, this list of conditions and the following disclaimer.
+ # * . Redistributions in binary form must reproduce the above copyright
+ # * notice, this list of conditions and the following disclaimer in
+ # * the documentation and/or other materials provided with the
+ # * distribution.
+ # * . Neither the name of the Computer Systems and Communication Lab
+ # * nor the names of its contributors may be used to endorse or
+ # * promote products derived from this software without specific
+ # * prior written permission.
+ # *
+ # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ # * OF THE POSSIBILITY OF SUCH DAMAGE.
+ # */
+ #
+ # Copyright 1996 Chih-Hao Tsai @ Beckman Institute,
+ # University of Illinois
+ # c-tsai4@uiuc.edu http://casper.beckman.uiuc.edu/~c-tsai4
+ #
+ # ---------------COPYING.libtabe-----END--------------------------------
+ #
+ #
+ # ---------------COPYING.ipadic-----BEGIN-------------------------------
+ #
+ # Copyright 2000, 2001, 2002, 2003 Nara Institute of Science
+ # and Technology. All Rights Reserved.
+ #
+ # Use, reproduction, and distribution of this software is permitted.
+ # Any copy of this software, whether in its original form or modified,
+ # must include both the above copyright notice and the following
+ # paragraphs.
+ #
+ # Nara Institute of Science and Technology (NAIST),
+ # the copyright holders, disclaims all warranties with regard to this
+ # software, including all implied warranties of merchantability and
+ # fitness, in no event shall NAIST be liable for
+ # any special, indirect or consequential damages or any damages
+ # whatsoever resulting from loss of use, data or profits, whether in an
+ # action of contract, negligence or other tortuous action, arising out
+ # of or in connection with the use or performance of this software.
+ #
+ # A large portion of the dictionary entries
+ # originate from ICOT Free Software. The following conditions for ICOT
+ # Free Software applies to the current dictionary as well.
+ #
+ # Each User may also freely distribute the Program, whether in its
+ # original form or modified, to any third party or parties, PROVIDED
+ # that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear
+ # on, or be attached to, the Program, which is distributed substantially
+ # in the same form as set out herein and that such intended
+ # distribution, if actually made, will neither violate or otherwise
+ # contravene any of the laws and regulations of the countries having
+ # jurisdiction over the User or the intended distribution itself.
+ #
+ # NO WARRANTY
+ #
+ # The program was produced on an experimental basis in the course of the
+ # research and development conducted during the project and is provided
+ # to users as so produced on an experimental basis. Accordingly, the
+ # program is provided without any warranty whatsoever, whether express,
+ # implied, statutory or otherwise. The term "warranty" used herein
+ # includes, but is not limited to, any warranty of the quality,
+ # performance, merchantability and fitness for a particular purpose of
+ # the program and the nonexistence of any infringement or violation of
+ # any right of any third party.
+ #
+ # Each user of the program will agree and understand, and be deemed to
+ # have agreed and understood, that there is no warranty whatsoever for
+ # the program and, accordingly, the entire risk arising from or
+ # otherwise connected with the program is assumed by the user.
+ #
+ # Therefore, neither ICOT, the copyright holder, or any other
+ # organization that participated in or was otherwise related to the
+ # development of the program and their respective officials, directors,
+ # officers and other employees shall be held liable for any and all
+ # damages, including, without limitation, general, special, incidental
+ # and consequential damages, arising out of or otherwise in connection
+ # with the use or inability to use the program or any product, material
+ # or result produced or otherwise obtained by using the program,
+ # regardless of whether they have been advised of, or otherwise had
+ # knowledge of, the possibility of such damages at any time during the
+ # project or thereafter. Each user will be deemed to have agreed to the
+ # foregoing by his or her commencement of use of the program. The term
+ # "use" as used herein includes, but is not limited to, the use,
+ # modification, copying and distribution of the program and the
+ # production of secondary products from the program.
+ #
+ # In the case where the program, whether in its original form or
+ # modified, was distributed or delivered to or received by a user from
+ # any person, organization or entity other than ICOT, unless it makes or
+ # grants independently of ICOT any specific warranty to the user in
+ # writing, such person, organization or entity, will also be exempted
+ # from and not be held liable to the user for any such damages as noted
+ # above as far as the program is concerned.
+ #
+ # ---------------COPYING.ipadic-----END----------------------------------
+
+ ----------------------------------------------------------------------
+
+ Lao Word Break Dictionary Data (laodict.txt)
+
+ # Copyright (C) 2016 and later: Unicode, Inc. and others.
+ # License & terms of use: http://www.unicode.org/copyright.html
+ # Copyright (c) 2015 International Business Machines Corporation
+ # and others. All Rights Reserved.
+ #
+ # Project: https://github.com/rober42539/lao-dictionary
+ # Dictionary: https://github.com/rober42539/lao-dictionary/laodict.txt
+ # License: https://github.com/rober42539/lao-dictionary/LICENSE.txt
+ # (copied below)
+ #
+ # This file is derived from the above dictionary version of Nov 22, 2020
+ # ----------------------------------------------------------------------
+ # Copyright (C) 2013 Brian Eugene Wilson, Robert Martin Campbell.
+ # All rights reserved.
+ #
+ # Redistribution and use in source and binary forms, with or without
+ # modification, are permitted provided that the following conditions are met:
+ #
+ # Redistributions of source code must retain the above copyright notice, this
+ # list of conditions and the following disclaimer. Redistributions in binary
+ # form must reproduce the above copyright notice, this list of conditions and
+ # the following disclaimer in the documentation and/or other materials
+ # provided with the distribution.
+ #
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ # OF THE POSSIBILITY OF SUCH DAMAGE.
+ # --------------------------------------------------------------------------
+
+ ----------------------------------------------------------------------
+
+ Burmese Word Break Dictionary Data (burmesedict.txt)
+
+ # Copyright (c) 2014 International Business Machines Corporation
+ # and others. All Rights Reserved.
+ #
+ # This list is part of a project hosted at:
+ # github.com/kanyawtech/myanmar-karen-word-lists
+ #
+ # --------------------------------------------------------------------------
+ # Copyright (c) 2013, LeRoy Benjamin Sharon
+ # All rights reserved.
+ #
+ # Redistribution and use in source and binary forms, with or without
+ # modification, are permitted provided that the following conditions
+ # are met: Redistributions of source code must retain the above
+ # copyright notice, this list of conditions and the following
+ # disclaimer. Redistributions in binary form must reproduce the
+ # above copyright notice, this list of conditions and the following
+ # disclaimer in the documentation and/or other materials provided
+ # with the distribution.
+ #
+ # Neither the name Myanmar Karen Word Lists, nor the names of its
+ # contributors may be used to endorse or promote products derived
+ # from this software without specific prior written permission.
+ #
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ # SUCH DAMAGE.
+ # --------------------------------------------------------------------------
+
+ ----------------------------------------------------------------------
+
+ Time Zone Database
+
+ ICU uses the public domain data and code derived from Time Zone
+ Database for its time zone support. The ownership of the TZ database
+ is explained in BCP 175: Procedure for Maintaining the Time Zone
+ Database section 7.
+
+ # 7. Database Ownership
+ #
+ # The TZ database itself is not an IETF Contribution or an IETF
+ # document. Rather it is a pre-existing and regularly updated work
+ # that is in the public domain, and is intended to remain in the
+ # public domain. Therefore, BCPs 78 [RFC5378] and 79 [RFC3979] do
+ # not apply to the TZ Database or contributions that individuals make
+ # to it. Should any claims be made and substantiated against the TZ
+ # Database, the organization that is providing the IANA
+ # Considerations defined in this RFC, under the memorandum of
+ # understanding with the IETF, currently ICANN, may act in accordance
+ # with all competent court orders. No ownership claims will be made
+ # by ICANN or the IETF Trust on the database or the code. Any person
+ # making a contribution to the database or code waives all rights to
+ # future claims in that contribution or in the TZ Database.
+
+ ----------------------------------------------------------------------
+
+ Google double-conversion
+
+ Copyright 2006-2011, the V8 project authors. All rights reserved.
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ ----------------------------------------------------------------------
+
+ JSON parsing library (nlohmann/json)
+
+ File: vendor/json/upstream/single_include/nlohmann/json.hpp (only for ICU4C)
+
+ MIT License
+
+ Copyright (c) 2013-2022 Niels Lohmann
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+
+ ----------------------------------------------------------------------
+
+ File: aclocal.m4 (only for ICU4C)
+ Section: pkg.m4 - Macros to locate and utilise pkg-config.
+
+ Copyright © 2004 Scott James Remnant .
+ Copyright © 2012-2015 Dan Nicholson
+
+ 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 2 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, write to the Free Software
+ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+ 02111-1307, USA.
+
+ As a special exception to the GNU General Public License, if you
+ distribute this file as part of a program that contains a
+ configuration script generated by Autoconf, you may include it under
+ the same distribution terms that you use for the rest of that
+ program.
+
+ (The condition for the exception is fulfilled because
+ ICU4C includes a configuration script generated by Autoconf,
+ namely the `configure` script.)
+
+ ----------------------------------------------------------------------
+
+ File: config.guess (only for ICU4C)
+
+ This file 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 .
+
+ As a special exception to the GNU General Public License, if you
+ distribute this file as part of a program that contains a
+ configuration script generated by Autoconf, you may include it under
+ the same distribution terms that you use for the rest of that
+ program. This Exception is an additional permission under section 7
+ of the GNU General Public License, version 3 ("GPLv3").
+
+ (The condition for the exception is fulfilled because
+ ICU4C includes a configuration script generated by Autoconf,
+ namely the `configure` script.)
+
+ ----------------------------------------------------------------------
+
+ File: install-sh (only for ICU4C)
+
+ Copyright 1991 by the Massachusetts Institute of Technology
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation, and that the name of M.I.T. not be used in advertising or
+ publicity pertaining to distribution of the software without specific,
+ written prior permission. M.I.T. makes no representations about the
+ suitability of this software for any purpose. It is provided "as is"
+ without express or implied warranty.
+
+ ----------------------------------------------------------------------
+
+ File: sorttable.js (only for ICU4J)
+
+ The MIT Licence, for code from kryogenix.org
+
+ Code downloaded from the Browser Experiments section of kryogenix.org is
+ licenced under the so-called MIT licence. The licence is below.
+
+ Copyright (c) 1997-date Stuart Langridge
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the "Software"),
+ to deal in the Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ and/or sell copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following conditions:
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- libuv, located at deps/uv, is licensed as follows:
+ """
+ Copyright (c) 2015-present libuv project contributors.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to
+ deal in the Software without restriction, including without limitation the
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ IN THE SOFTWARE.
+ This license applies to parts of libuv originating from the
+ https://github.com/joyent/libuv repository:
+
+ ====
+
+ Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to
+ deal in the Software without restriction, including without limitation the
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ IN THE SOFTWARE.
+
+ ====
+
+ This license applies to all parts of libuv that are not externally
+ maintained libraries.
+
+ The externally maintained libraries used by libuv are:
+
+ - tree.h (from FreeBSD), copyright Niels Provos. Two clause BSD license.
+
+ - inet_pton and inet_ntop implementations, contained in src/inet.c, are
+ copyright the Internet Systems Consortium, Inc., and licensed under the ISC
+ license.
+ """
+
+- LIEF, located at deps/LIEF, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017 - 2025 R. Thomas
+ Copyright 2017 - 2025 Quarkslab
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+
+- llhttp, located at deps/llhttp, is licensed as follows:
+ """
+ This software is licensed under the MIT License.
+
+ Copyright Fedor Indutny, 2018.
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- corepack, located at deps/corepack, is licensed as follows:
+ """
+ **Copyright © Corepack contributors**
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- undici, located at deps/undici, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) Matteo Collina and Undici contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- postject, located at test/fixtures/postject-copy, is licensed as follows:
+ """
+ Postject is licensed for use as follows:
+
+ """
+ MIT License
+
+ Copyright (c) 2022 Postman, Inc
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+ The Postject license applies to all parts of Postject that are not externally
+ maintained libraries.
+
+ The externally maintained libraries used by Postject are:
+
+ - LIEF, located at vendor/LIEF, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017 - 2022 R. Thomas
+ Copyright 2017 - 2022 Quarkslab
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+ """
+
+- OpenSSL, located at deps/openssl, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+ """
+
+- Punycode.js, located at lib/punycode.js, is licensed as follows:
+ """
+ Copyright Mathias Bynens
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- V8, located at deps/v8, is licensed as follows:
+ """
+ This license applies to all parts of V8 that are not externally
+ maintained libraries. The externally maintained libraries used by V8
+ are:
+
+ - PCRE test suite, located in
+ test/mjsunit/third_party/regexp-pcre/regexp-pcre.js. This is based on the
+ test suite from PCRE-7.3, which is copyrighted by the University
+ of Cambridge and Google, Inc. The copyright notice and license
+ are embedded in regexp-pcre.js.
+
+ - Layout tests, located in test/mjsunit/third_party/object-keys. These are
+ based on layout tests from webkit.org which are copyrighted by
+ Apple Computer, Inc. and released under a 3-clause BSD license.
+
+ - Strongtalk assembler, the basis of the files assembler-arm-inl.h,
+ assembler-arm.cc, assembler-arm.h, assembler-ia32-inl.h,
+ assembler-ia32.cc, assembler-ia32.h, assembler-x64-inl.h,
+ assembler-x64.cc, assembler-x64.h, assembler.cc and assembler.h.
+ This code is copyrighted by Sun Microsystems Inc. and released
+ under a 3-clause BSD license.
+
+ - Valgrind client API header, located at third_party/valgrind/valgrind.h
+ This is released under the BSD license.
+
+ - The Wasm C/C++ API headers, located at third_party/wasm-api/wasm.{h,hh}
+ This is released under the Apache license. The API's upstream prototype
+ implementation also formed the basis of V8's implementation in
+ src/wasm/c-api.cc.
+
+ These libraries have their own licenses; we recommend you read them,
+ as their terms may differ from the terms below.
+
+ Further license information can be found in LICENSE files located in
+ sub-directories.
+
+ Copyright 2014, the V8 project authors. All rights reserved.
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- SipHash, located at deps/v8/src/third_party/siphash, is licensed as follows:
+ """
+ SipHash reference C implementation
+
+ Copyright (c) 2016 Jean-Philippe Aumasson
+
+ To the extent possible under law, the author(s) have dedicated all
+ copyright and related and neighboring rights to this software to the public
+ domain worldwide. This software is distributed without any warranty.
+ """
+
+- zlib, located at deps/zlib, is licensed as follows:
+ """
+ zlib.h -- interface of the 'zlib' general purpose compression library
+ version 1.3.2.1, February xxth, 2026
+
+ Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+ """
+
+- simdjson, located at deps/simdjson, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2018-2025 The simdjson authors
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+
+- simdutf, located at deps/v8/third_party/simdutf, is licensed as follows:
+ """
+ Copyright 2021 The simdutf authors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal in
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ the Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- ada, located at deps/ada, is licensed as follows:
+ """
+ Copyright 2023 Yagiz Nizipli and Daniel Lemire
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal in
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ the Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- minimatch, located at deps/minimatch, is licensed as follows:
+ """
+ # Blue Oak Model License
+
+ Version 1.0.0
+
+ ## Purpose
+
+ This license gives everyone as much permission to work with
+ this software as possible, while protecting contributors
+ from liability.
+
+ ## Acceptance
+
+ In order to receive this license, you must agree to its
+ rules. The rules of this license are both obligations
+ under that agreement and conditions to your license.
+ You must not do anything with this software that triggers
+ a rule that you cannot or will not follow.
+
+ ## Copyright
+
+ Each contributor licenses you to do everything with this
+ software that would otherwise infringe that contributor's
+ copyright in it.
+
+ ## Notices
+
+ You must ensure that everyone who gets a copy of
+ any part of this software from you, with or without
+ changes, also gets the text of this license or a link to
+ .
+
+ ## Excuse
+
+ If anyone notifies you in writing that you have not
+ complied with [Notices](#notices), you can keep your
+ license by taking all practical steps to comply within 30
+ days after the notice. If you do not do so, your license
+ ends immediately.
+
+ ## Patent
+
+ Each contributor licenses you to do everything with this
+ software that would otherwise infringe any patent claims
+ they can license or become able to license.
+
+ ## Reliability
+
+ No contributor can revoke this license.
+
+ ## No Liability
+
+ **_As far as the law allows, this software comes as is,
+ without any warranty or condition, and no contributor
+ will be liable to anyone for any damages related to this
+ software or this license, under any kind of legal claim._**
+ """
+
+- npm, located at deps/npm, is licensed as follows:
+ """
+ The npm application
+ Copyright (c) npm, Inc. and Contributors
+ Licensed on the terms of The Artistic License 2.0
+
+ Node package dependencies of the npm application
+ Copyright (c) their respective copyright owners
+ Licensed on their respective license terms
+
+ The npm public registry at https://registry.npmjs.org
+ and the npm website at https://www.npmjs.com
+ Operated by npm, Inc.
+ Use governed by terms published on https://www.npmjs.com
+
+ "Node.js"
+ Trademark Joyent, Inc., https://joyent.com
+ Neither npm nor npm, Inc. are affiliated with Joyent, Inc.
+
+ The Node.js application
+ Project of Node Foundation, https://nodejs.org
+
+ The npm Logo
+ Copyright (c) Mathias Pettersson and Brian Hammond
+
+ "Gubblebum Blocky" typeface
+ Copyright (c) Tjarda Koster, https://jelloween.deviantart.com
+ Used with permission
+
+ --------
+
+ The Artistic License 2.0
+
+ Copyright (c) 2000-2006, The Perl Foundation.
+
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ This license establishes the terms under which a given free software
+ Package may be copied, modified, distributed, and/or redistributed.
+ The intent is that the Copyright Holder maintains some artistic
+ control over the development of that Package while still keeping the
+ Package available as open source and free software.
+
+ You are always permitted to make arrangements wholly outside of this
+ license directly with the Copyright Holder of a given Package. If the
+ terms of this license do not permit the full use that you propose to
+ make of the Package, you should contact the Copyright Holder and seek
+ a different licensing arrangement.
+
+ Definitions
+
+ "Copyright Holder" means the individual(s) or organization(s)
+ named in the copyright notice for the entire Package.
+
+ "Contributor" means any party that has contributed code or other
+ material to the Package, in accordance with the Copyright Holder's
+ procedures.
+
+ "You" and "your" means any person who would like to copy,
+ distribute, or modify the Package.
+
+ "Package" means the collection of files distributed by the
+ Copyright Holder, and derivatives of that collection and/or of
+ those files. A given Package may consist of either the Standard
+ Version, or a Modified Version.
+
+ "Distribute" means providing a copy of the Package or making it
+ accessible to anyone else, or in the case of a company or
+ organization, to others outside of your company or organization.
+
+ "Distributor Fee" means any fee that you charge for Distributing
+ this Package or providing support for this Package to another
+ party. It does not mean licensing fees.
+
+ "Standard Version" refers to the Package if it has not been
+ modified, or has been modified only in ways explicitly requested
+ by the Copyright Holder.
+
+ "Modified Version" means the Package, if it has been changed, and
+ such changes were not explicitly requested by the Copyright
+ Holder.
+
+ "Original License" means this Artistic License as Distributed with
+ the Standard Version of the Package, in its current version or as
+ it may be modified by The Perl Foundation in the future.
+
+ "Source" form means the source code, documentation source, and
+ configuration files for the Package.
+
+ "Compiled" form means the compiled bytecode, object code, binary,
+ or any other form resulting from mechanical transformation or
+ translation of the Source form.
+
+ Permission for Use and Modification Without Distribution
+
+ (1) You are permitted to use the Standard Version and create and use
+ Modified Versions for any purpose without restriction, provided that
+ you do not Distribute the Modified Version.
+
+ Permissions for Redistribution of the Standard Version
+
+ (2) You may Distribute verbatim copies of the Source form of the
+ Standard Version of this Package in any medium without restriction,
+ either gratis or for a Distributor Fee, provided that you duplicate
+ all of the original copyright notices and associated disclaimers. At
+ your discretion, such verbatim copies may or may not include a
+ Compiled form of the Package.
+
+ (3) You may apply any bug fixes, portability changes, and other
+ modifications made available from the Copyright Holder. The resulting
+ Package will still be considered the Standard Version, and as such
+ will be subject to the Original License.
+
+ Distribution of Modified Versions of the Package as Source
+
+ (4) You may Distribute your Modified Version as Source (either gratis
+ or for a Distributor Fee, and with or without a Compiled form of the
+ Modified Version) provided that you clearly document how it differs
+ from the Standard Version, including, but not limited to, documenting
+ any non-standard features, executables, or modules, and provided that
+ you do at least ONE of the following:
+
+ (a) make the Modified Version available to the Copyright Holder
+ of the Standard Version, under the Original License, so that the
+ Copyright Holder may include your modifications in the Standard
+ Version.
+
+ (b) ensure that installation of your Modified Version does not
+ prevent the user installing or running the Standard Version. In
+ addition, the Modified Version must bear a name that is different
+ from the name of the Standard Version.
+
+ (c) allow anyone who receives a copy of the Modified Version to
+ make the Source form of the Modified Version available to others
+ under
+
+ (i) the Original License or
+
+ (ii) a license that permits the licensee to freely copy,
+ modify and redistribute the Modified Version using the same
+ licensing terms that apply to the copy that the licensee
+ received, and requires that the Source form of the Modified
+ Version, and of any works derived from it, be made freely
+ available in that license fees are prohibited but Distributor
+ Fees are allowed.
+
+ Distribution of Compiled Forms of the Standard Version
+ or Modified Versions without the Source
+
+ (5) You may Distribute Compiled forms of the Standard Version without
+ the Source, provided that you include complete instructions on how to
+ get the Source of the Standard Version. Such instructions must be
+ valid at the time of your distribution. If these instructions, at any
+ time while you are carrying out such distribution, become invalid, you
+ must provide new instructions on demand or cease further distribution.
+ If you provide valid instructions or cease distribution within thirty
+ days after you become aware that the instructions are invalid, then
+ you do not forfeit any of your rights under this license.
+
+ (6) You may Distribute a Modified Version in Compiled form without
+ the Source, provided that you comply with Section 4 with respect to
+ the Source of the Modified Version.
+
+ Aggregating or Linking the Package
+
+ (7) You may aggregate the Package (either the Standard Version or
+ Modified Version) with other packages and Distribute the resulting
+ aggregation provided that you do not charge a licensing fee for the
+ Package. Distributor Fees are permitted, and licensing fees for other
+ components in the aggregation are permitted. The terms of this license
+ apply to the use and Distribution of the Standard or Modified Versions
+ as included in the aggregation.
+
+ (8) You are permitted to link Modified and Standard Versions with
+ other works, to embed the Package in a larger work of your own, or to
+ build stand-alone binary or bytecode versions of applications that
+ include the Package, and Distribute the result without restriction,
+ provided the result does not expose a direct interface to the Package.
+
+ Items That are Not Considered Part of a Modified Version
+
+ (9) Works (including, but not limited to, modules and scripts) that
+ merely extend or make use of the Package, do not, by themselves, cause
+ the Package to be a Modified Version. In addition, such works are not
+ considered parts of the Package itself, and are not subject to the
+ terms of this license.
+
+ General Provisions
+
+ (10) Any use, modification, and distribution of the Standard or
+ Modified Versions is governed by this Artistic License. By using,
+ modifying or distributing the Package, you accept this license. Do not
+ use, modify, or distribute the Package, if you do not accept this
+ license.
+
+ (11) If your Modified Version has been derived from a Modified
+ Version made by someone other than you, you are nevertheless required
+ to ensure that your Modified Version complies with the requirements of
+ this license.
+
+ (12) This license does not grant you the right to use any trademark,
+ service mark, tradename, or logo of the Copyright Holder.
+
+ (13) This license includes the non-exclusive, worldwide,
+ free-of-charge patent license to make, have made, use, offer to sell,
+ sell, import and otherwise transfer the Package with respect to any
+ patent claims licensable by the Copyright Holder that are necessarily
+ infringed by the Package. If you institute patent litigation
+ (including a cross-claim or counterclaim) against any party alleging
+ that the Package constitutes direct or contributory patent
+ infringement, then this Artistic License to you shall terminate on the
+ date that such litigation is filed.
+
+ (14) Disclaimer of Warranty:
+ THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS
+ IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL
+ LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL
+ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+ DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ --------
+ """
+
+- GYP, located at tools/gyp, is licensed as follows:
+ """
+ Copyright (c) 2020 Node.js contributors. All rights reserved.
+ Copyright (c) 2009 Google Inc. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- inspector_protocol, located at deps/inspector_protocol, is licensed as follows:
+ """
+ // Copyright 2016 The Chromium Authors.
+ //
+ // Redistribution and use in source and binary forms, with or without
+ // modification, are permitted provided that the following conditions are
+ // met:
+ //
+ // * Redistributions of source code must retain the above copyright
+ // notice, this list of conditions and the following disclaimer.
+ // * Redistributions in binary form must reproduce the above
+ // copyright notice, this list of conditions and the following disclaimer
+ // in the documentation and/or other materials provided with the
+ // distribution.
+ // * Neither the name of Google Inc. nor the names of its
+ // contributors may be used to endorse or promote products derived from
+ // this software without specific prior written permission.
+ //
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- jinja2, located at tools/inspector_protocol/jinja2, is licensed as follows:
+ """
+ Copyright (c) 2009 by the Jinja Team, see AUTHORS for more details.
+
+ Some rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * The names of the contributors may not be used to endorse or
+ promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- markupsafe, located at tools/inspector_protocol/markupsafe, is licensed as follows:
+ """
+ Copyright (c) 2010 by Armin Ronacher and contributors. See AUTHORS
+ for more details.
+
+ Some rights reserved.
+
+ Redistribution and use in source and binary forms of the software as well
+ as documentation, with or without modification, are permitted provided
+ that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * The names of the contributors may not be used to endorse or
+ promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
+ NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+ OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ DAMAGE.
+ """
+
+- cpplint.py, located at tools/cpplint.py, is licensed as follows:
+ """
+ Copyright (c) 2009 Google Inc. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- gypi_to_gn.py, located at tools/gypi_to_gn.py, is licensed as follows:
+ """
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of Google LLC nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- gtest, located at deps/googletest, is licensed as follows:
+ """
+ Copyright 2008, Google Inc.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- nghttp2, located at deps/nghttp2, is licensed as follows:
+ """
+ The MIT License
+
+ Copyright (c) 2012, 2014, 2015, 2016 Tatsuhiro Tsujikawa
+ Copyright (c) 2012, 2014, 2015, 2016 nghttp2 contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- large_pages, located at src/large_pages, is licensed as follows:
+ """
+ Copyright (C) 2018 Intel Corporation
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"),
+ to deal in the Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ and/or sell copies of the Software, and to permit persons to whom
+ the Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
+ OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
+ OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- caja, located at lib/internal/freeze_intrinsics.js, is licensed as follows:
+ """
+ Adapted from SES/Caja - Copyright (C) 2011 Google Inc.
+ Copyright (C) 2018 Agoric
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+
+- brotli, located at deps/brotli, is licensed as follows:
+ """
+ Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ """
+
+- zstd, located at deps/zstd, is licensed as follows:
+ """
+ BSD License
+
+ For Zstandard software
+
+ Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name Facebook, nor Meta, nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- HdrHistogram, located at deps/histogram, is licensed as follows:
+ """
+ The code in this repository code was Written by Gil Tene, Michael Barker,
+ and Matt Warren, and released to the public domain, as explained at
+ http://creativecommons.org/publicdomain/zero/1.0/
+
+ For users of this code who wish to consume it under the "BSD" license
+ rather than under the public domain or CC0 contribution text mentioned
+ above, the code found under this directory is *also* provided under the
+ following license (commonly referred to as the BSD 2-Clause License). This
+ license does not detract from the above stated release of the code into
+ the public domain, and simply represents an additional license granted by
+ the Author.
+
+ -----------------------------------------------------------------------------
+ ** Beginning of "BSD 2-Clause License" text. **
+
+ Copyright (c) 2012, 2013, 2014 Gil Tene
+ Copyright (c) 2014 Michael Barker
+ Copyright (c) 2014 Matt Warren
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- node-heapdump, located at src/heap_utils.cc, is licensed as follows:
+ """
+ ISC License
+
+ Copyright (c) 2012, Ben Noordhuis
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted, provided that the above
+ copyright notice and this permission notice appear in all copies.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+ === src/compat.h src/compat-inl.h ===
+
+ ISC License
+
+ Copyright (c) 2014, StrongLoop Inc.
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted, provided that the above
+ copyright notice and this permission notice appear in all copies.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ """
+
+- rimraf, located at lib/internal/fs/rimraf.js, is licensed as follows:
+ """
+ The ISC License
+
+ Copyright (c) Isaac Z. Schlueter and Contributors
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted, provided that the above
+ copyright notice and this permission notice appear in all copies.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ """
+
+- uvwasi, located at deps/uvwasi, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) 2019 Colin Ihrig and Contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- ngtcp2, located at deps/ngtcp2/ngtcp2/, is licensed as follows:
+ """
+ The MIT License
+
+ Copyright (c) 2016 ngtcp2 contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- nghttp3, located at deps/ngtcp2/nghttp3/, is licensed as follows:
+ """
+ The MIT License
+
+ Copyright (c) 2019 nghttp3 contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- node-fs-extra, located at lib/internal/fs/cp, is licensed as follows:
+ """
+ (The MIT License)
+
+ Copyright (c) 2011-2017 JP Richardson
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
+ (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+ OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- on-exit-leak-free, located at lib/internal/process/finalization, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) 2021 Matteo Collina
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- sonic-boom, located at lib/internal/streams/fast-utf8-stream.js, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) 2017 Matteo Collina
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
diff --git a/agents/pi/LICENSE.pi b/agents/pi/LICENSE.pi
new file mode 100644
index 0000000..b0a8e9b
--- /dev/null
+++ b/agents/pi/LICENSE.pi
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Mario Zechner
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/agents/pi/build.mjs b/agents/pi/build.mjs
new file mode 100644
index 0000000..f0dead6
--- /dev/null
+++ b/agents/pi/build.mjs
@@ -0,0 +1,13 @@
+import { build } from 'esbuild';
+import * as fs from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { writeNotices } from './notices.mjs';
+
+const result = await build({ entryPoints: ['src/runner.mjs'], outfile: 'dist/pi-runner.mjs', bundle: true, platform: 'node', metafile: true,
+ format: 'esm', target: 'node22.19', sourcemap: false, minify: false, legalComments: 'eof',
+ banner: { js: "import { createRequire as esfCreateRequire } from 'node:module'; const require = esfCreateRequire(import.meta.url);" } });
+const bytes = await fs.readFile('dist/pi-runner.mjs');
+const digest = createHash('sha256').update(bytes).digest('hex');
+await fs.writeFile('dist/SHA256SUMS', `${digest} pi-runner.mjs\n`);
+await writeNotices(Object.keys(result.metafile.inputs));
+console.log(`Pi runner sha256 ${digest}`);
diff --git a/agents/pi/dist/SHA256SUMS b/agents/pi/dist/SHA256SUMS
new file mode 100644
index 0000000..0acdada
--- /dev/null
+++ b/agents/pi/dist/SHA256SUMS
@@ -0,0 +1 @@
+9dab48151c793cf3265af4058ea7aac8671d1778b31873ee25ac3fc24afe0e2c pi-runner.mjs
diff --git a/agents/pi/dist/THIRD_PARTY_NOTICES.txt b/agents/pi/dist/THIRD_PARTY_NOTICES.txt
new file mode 100644
index 0000000..1b91dec
--- /dev/null
+++ b/agents/pi/dist/THIRD_PARTY_NOTICES.txt
@@ -0,0 +1,3305 @@
+ESF Pi runner: bundled dependency and runtime notices
+
+
+===== @earendil-works/chord@1.0.3 (MIT) =====
+MIT License
+
+Copyright (c) 2025 Mario Zechner
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+===== @earendil-works/pi-ai@1.0.3 (MIT) =====
+MIT License
+
+Copyright (c) 2025 Mario Zechner
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+===== @earendil-works/pi-durable@1.0.3 (MIT) =====
+MIT License
+
+Copyright (c) 2025 Mario Zechner
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+===== diff@8.0.4 (BSD-3-Clause) =====
+BSD 3-Clause License
+
+Copyright (c) 2009-2015, Kevin Decker
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+===== openai@7.19.0 (Apache-2.0) =====
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 OpenAI
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+===== partial-json@0.1.7 (MIT) =====
+MIT License
+
+Copyright (c) 2023 Promplate Dev Team
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+===== typebox@1.3.27 (MIT) =====
+TypeBox
+
+The MIT License (MIT)
+
+Copyright (c) 2017-2026 Haydn Paterson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+===== Node.js 24.21.0 =====
+Node.js is licensed for use as follows:
+
+"""
+Copyright Node.js contributors. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
+"""
+
+This license applies to parts of Node.js originating from the
+https://github.com/joyent/node repository:
+
+"""
+Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
+"""
+
+The Node.js license applies to all parts of Node.js that are not externally
+maintained libraries.
+
+The externally maintained libraries used by Node.js are:
+
+- Acorn, located at deps/acorn, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (C) 2012-2022 by various contributors (see AUTHORS)
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ """
+
+- c-ares, located at deps/cares, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) 1998 Massachusetts Institute of Technology
+ Copyright (c) 2007 - 2023 Daniel Stenberg with many contributors, see AUTHORS
+ file.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal in
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ the Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice (including the next
+ paragraph) shall be included in all copies or substantial portions of the
+ Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- merve, located at deps/merve, is licensed as follows:
+ """
+ Copyright 2026 Yagiz Nizipli
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal in
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ the Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- ittapi, located at deps/v8/third_party/ittapi, is licensed as follows:
+ """
+ Copyright (c) 2019 Intel Corporation. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- amaro, located at deps/amaro, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) Marco Ippolito and Amaro contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- swc, located at deps/amaro/dist, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2024 SWC contributors.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+
+- ICU, located at deps/icu-small, is licensed as follows:
+ """
+ UNICODE LICENSE V3
+
+ COPYRIGHT AND PERMISSION NOTICE
+
+ Copyright © 2016-2025 Unicode, Inc.
+
+ NOTICE TO USER: Carefully read the following legal agreement. BY
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of data files and any associated documentation (the "Data Files") or
+ software and any associated documentation (the "Software") to deal in the
+ Data Files or Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
+ copies of the Data Files or Software, and to permit persons to whom the
+ Data Files or Software are furnished to do so, provided that either (a)
+ this copyright and permission notice appear with all copies of the Data
+ Files or Software, or (b) this copyright and permission notice appear in
+ associated Documentation.
+
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
+ THIRD PARTY RIGHTS.
+
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
+ FILES OR SOFTWARE.
+
+ Except as contained in this notice, the name of a copyright holder shall
+ not be used in advertising or otherwise to promote the sale, use or other
+ dealings in these Data Files or Software without prior written
+ authorization of the copyright holder.
+
+ SPDX-License-Identifier: Unicode-3.0
+
+ ----------------------------------------------------------------------
+
+ Third-Party Software Licenses
+
+ This section contains third-party software notices and/or additional
+ terms for licensed third-party software components included within ICU
+ libraries.
+
+ ----------------------------------------------------------------------
+
+ ICU License - ICU 1.8.1 to ICU 57.1
+
+ COPYRIGHT AND PERMISSION NOTICE
+
+ Copyright (c) 1995-2016 International Business Machines Corporation and others
+ All rights reserved.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, and/or sell copies of the Software, and to permit persons
+ to whom the Software is furnished to do so, provided that the above
+ copyright notice(s) and this permission notice appear in all copies of
+ the Software and that both the above copyright notice(s) and this
+ permission notice appear in supporting documentation.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+ OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+ HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
+ SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
+ RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
+ CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+ Except as contained in this notice, the name of a copyright holder
+ shall not be used in advertising or otherwise to promote the sale, use
+ or other dealings in this Software without prior written authorization
+ of the copyright holder.
+
+ All trademarks and registered trademarks mentioned herein are the
+ property of their respective owners.
+
+ ----------------------------------------------------------------------
+
+ Chinese/Japanese Word Break Dictionary Data (cjdict.txt)
+
+ # The Google Chrome software developed by Google is licensed under
+ # the BSD license. Other software included in this distribution is
+ # provided under other licenses, as set forth below.
+ #
+ # The BSD License
+ # http://opensource.org/licenses/bsd-license.php
+ # Copyright (C) 2006-2008, Google Inc.
+ #
+ # All rights reserved.
+ #
+ # Redistribution and use in source and binary forms, with or without
+ # modification, are permitted provided that the following conditions are met:
+ #
+ # Redistributions of source code must retain the above copyright notice,
+ # this list of conditions and the following disclaimer.
+ # Redistributions in binary form must reproduce the above
+ # copyright notice, this list of conditions and the following
+ # disclaimer in the documentation and/or other materials provided with
+ # the distribution.
+ # Neither the name of Google Inc. nor the names of its
+ # contributors may be used to endorse or promote products derived from
+ # this software without specific prior written permission.
+ #
+ #
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ #
+ #
+ # The word list in cjdict.txt are generated by combining three word lists
+ # listed below with further processing for compound word breaking. The
+ # frequency is generated with an iterative training against Google web
+ # corpora.
+ #
+ # * Libtabe (Chinese)
+ # - https://sourceforge.net/project/?group_id=1519
+ # - Its license terms and conditions are shown below.
+ #
+ # * IPADIC (Japanese)
+ # - http://chasen.aist-nara.ac.jp/chasen/distribution.html
+ # - Its license terms and conditions are shown below.
+ #
+ # ---------COPYING.libtabe ---- BEGIN--------------------
+ #
+ # /*
+ # * Copyright (c) 1999 TaBE Project.
+ # * Copyright (c) 1999 Pai-Hsiang Hsiao.
+ # * All rights reserved.
+ # *
+ # * Redistribution and use in source and binary forms, with or without
+ # * modification, are permitted provided that the following conditions
+ # * are met:
+ # *
+ # * . Redistributions of source code must retain the above copyright
+ # * notice, this list of conditions and the following disclaimer.
+ # * . Redistributions in binary form must reproduce the above copyright
+ # * notice, this list of conditions and the following disclaimer in
+ # * the documentation and/or other materials provided with the
+ # * distribution.
+ # * . Neither the name of the TaBE Project nor the names of its
+ # * contributors may be used to endorse or promote products derived
+ # * from this software without specific prior written permission.
+ # *
+ # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ # * OF THE POSSIBILITY OF SUCH DAMAGE.
+ # */
+ #
+ # /*
+ # * Copyright (c) 1999 Computer Systems and Communication Lab,
+ # * Institute of Information Science, Academia
+ # * Sinica. All rights reserved.
+ # *
+ # * Redistribution and use in source and binary forms, with or without
+ # * modification, are permitted provided that the following conditions
+ # * are met:
+ # *
+ # * . Redistributions of source code must retain the above copyright
+ # * notice, this list of conditions and the following disclaimer.
+ # * . Redistributions in binary form must reproduce the above copyright
+ # * notice, this list of conditions and the following disclaimer in
+ # * the documentation and/or other materials provided with the
+ # * distribution.
+ # * . Neither the name of the Computer Systems and Communication Lab
+ # * nor the names of its contributors may be used to endorse or
+ # * promote products derived from this software without specific
+ # * prior written permission.
+ # *
+ # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ # * OF THE POSSIBILITY OF SUCH DAMAGE.
+ # */
+ #
+ # Copyright 1996 Chih-Hao Tsai @ Beckman Institute,
+ # University of Illinois
+ # c-tsai4@uiuc.edu http://casper.beckman.uiuc.edu/~c-tsai4
+ #
+ # ---------------COPYING.libtabe-----END--------------------------------
+ #
+ #
+ # ---------------COPYING.ipadic-----BEGIN-------------------------------
+ #
+ # Copyright 2000, 2001, 2002, 2003 Nara Institute of Science
+ # and Technology. All Rights Reserved.
+ #
+ # Use, reproduction, and distribution of this software is permitted.
+ # Any copy of this software, whether in its original form or modified,
+ # must include both the above copyright notice and the following
+ # paragraphs.
+ #
+ # Nara Institute of Science and Technology (NAIST),
+ # the copyright holders, disclaims all warranties with regard to this
+ # software, including all implied warranties of merchantability and
+ # fitness, in no event shall NAIST be liable for
+ # any special, indirect or consequential damages or any damages
+ # whatsoever resulting from loss of use, data or profits, whether in an
+ # action of contract, negligence or other tortuous action, arising out
+ # of or in connection with the use or performance of this software.
+ #
+ # A large portion of the dictionary entries
+ # originate from ICOT Free Software. The following conditions for ICOT
+ # Free Software applies to the current dictionary as well.
+ #
+ # Each User may also freely distribute the Program, whether in its
+ # original form or modified, to any third party or parties, PROVIDED
+ # that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear
+ # on, or be attached to, the Program, which is distributed substantially
+ # in the same form as set out herein and that such intended
+ # distribution, if actually made, will neither violate or otherwise
+ # contravene any of the laws and regulations of the countries having
+ # jurisdiction over the User or the intended distribution itself.
+ #
+ # NO WARRANTY
+ #
+ # The program was produced on an experimental basis in the course of the
+ # research and development conducted during the project and is provided
+ # to users as so produced on an experimental basis. Accordingly, the
+ # program is provided without any warranty whatsoever, whether express,
+ # implied, statutory or otherwise. The term "warranty" used herein
+ # includes, but is not limited to, any warranty of the quality,
+ # performance, merchantability and fitness for a particular purpose of
+ # the program and the nonexistence of any infringement or violation of
+ # any right of any third party.
+ #
+ # Each user of the program will agree and understand, and be deemed to
+ # have agreed and understood, that there is no warranty whatsoever for
+ # the program and, accordingly, the entire risk arising from or
+ # otherwise connected with the program is assumed by the user.
+ #
+ # Therefore, neither ICOT, the copyright holder, or any other
+ # organization that participated in or was otherwise related to the
+ # development of the program and their respective officials, directors,
+ # officers and other employees shall be held liable for any and all
+ # damages, including, without limitation, general, special, incidental
+ # and consequential damages, arising out of or otherwise in connection
+ # with the use or inability to use the program or any product, material
+ # or result produced or otherwise obtained by using the program,
+ # regardless of whether they have been advised of, or otherwise had
+ # knowledge of, the possibility of such damages at any time during the
+ # project or thereafter. Each user will be deemed to have agreed to the
+ # foregoing by his or her commencement of use of the program. The term
+ # "use" as used herein includes, but is not limited to, the use,
+ # modification, copying and distribution of the program and the
+ # production of secondary products from the program.
+ #
+ # In the case where the program, whether in its original form or
+ # modified, was distributed or delivered to or received by a user from
+ # any person, organization or entity other than ICOT, unless it makes or
+ # grants independently of ICOT any specific warranty to the user in
+ # writing, such person, organization or entity, will also be exempted
+ # from and not be held liable to the user for any such damages as noted
+ # above as far as the program is concerned.
+ #
+ # ---------------COPYING.ipadic-----END----------------------------------
+
+ ----------------------------------------------------------------------
+
+ Lao Word Break Dictionary Data (laodict.txt)
+
+ # Copyright (C) 2016 and later: Unicode, Inc. and others.
+ # License & terms of use: http://www.unicode.org/copyright.html
+ # Copyright (c) 2015 International Business Machines Corporation
+ # and others. All Rights Reserved.
+ #
+ # Project: https://github.com/rober42539/lao-dictionary
+ # Dictionary: https://github.com/rober42539/lao-dictionary/laodict.txt
+ # License: https://github.com/rober42539/lao-dictionary/LICENSE.txt
+ # (copied below)
+ #
+ # This file is derived from the above dictionary version of Nov 22, 2020
+ # ----------------------------------------------------------------------
+ # Copyright (C) 2013 Brian Eugene Wilson, Robert Martin Campbell.
+ # All rights reserved.
+ #
+ # Redistribution and use in source and binary forms, with or without
+ # modification, are permitted provided that the following conditions are met:
+ #
+ # Redistributions of source code must retain the above copyright notice, this
+ # list of conditions and the following disclaimer. Redistributions in binary
+ # form must reproduce the above copyright notice, this list of conditions and
+ # the following disclaimer in the documentation and/or other materials
+ # provided with the distribution.
+ #
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ # OF THE POSSIBILITY OF SUCH DAMAGE.
+ # --------------------------------------------------------------------------
+
+ ----------------------------------------------------------------------
+
+ Burmese Word Break Dictionary Data (burmesedict.txt)
+
+ # Copyright (c) 2014 International Business Machines Corporation
+ # and others. All Rights Reserved.
+ #
+ # This list is part of a project hosted at:
+ # github.com/kanyawtech/myanmar-karen-word-lists
+ #
+ # --------------------------------------------------------------------------
+ # Copyright (c) 2013, LeRoy Benjamin Sharon
+ # All rights reserved.
+ #
+ # Redistribution and use in source and binary forms, with or without
+ # modification, are permitted provided that the following conditions
+ # are met: Redistributions of source code must retain the above
+ # copyright notice, this list of conditions and the following
+ # disclaimer. Redistributions in binary form must reproduce the
+ # above copyright notice, this list of conditions and the following
+ # disclaimer in the documentation and/or other materials provided
+ # with the distribution.
+ #
+ # Neither the name Myanmar Karen Word Lists, nor the names of its
+ # contributors may be used to endorse or promote products derived
+ # from this software without specific prior written permission.
+ #
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ # SUCH DAMAGE.
+ # --------------------------------------------------------------------------
+
+ ----------------------------------------------------------------------
+
+ Time Zone Database
+
+ ICU uses the public domain data and code derived from Time Zone
+ Database for its time zone support. The ownership of the TZ database
+ is explained in BCP 175: Procedure for Maintaining the Time Zone
+ Database section 7.
+
+ # 7. Database Ownership
+ #
+ # The TZ database itself is not an IETF Contribution or an IETF
+ # document. Rather it is a pre-existing and regularly updated work
+ # that is in the public domain, and is intended to remain in the
+ # public domain. Therefore, BCPs 78 [RFC5378] and 79 [RFC3979] do
+ # not apply to the TZ Database or contributions that individuals make
+ # to it. Should any claims be made and substantiated against the TZ
+ # Database, the organization that is providing the IANA
+ # Considerations defined in this RFC, under the memorandum of
+ # understanding with the IETF, currently ICANN, may act in accordance
+ # with all competent court orders. No ownership claims will be made
+ # by ICANN or the IETF Trust on the database or the code. Any person
+ # making a contribution to the database or code waives all rights to
+ # future claims in that contribution or in the TZ Database.
+
+ ----------------------------------------------------------------------
+
+ Google double-conversion
+
+ Copyright 2006-2011, the V8 project authors. All rights reserved.
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ ----------------------------------------------------------------------
+
+ JSON parsing library (nlohmann/json)
+
+ File: vendor/json/upstream/single_include/nlohmann/json.hpp (only for ICU4C)
+
+ MIT License
+
+ Copyright (c) 2013-2022 Niels Lohmann
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+
+ ----------------------------------------------------------------------
+
+ File: aclocal.m4 (only for ICU4C)
+ Section: pkg.m4 - Macros to locate and utilise pkg-config.
+
+ Copyright © 2004 Scott James Remnant .
+ Copyright © 2012-2015 Dan Nicholson
+
+ 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 2 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, write to the Free Software
+ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+ 02111-1307, USA.
+
+ As a special exception to the GNU General Public License, if you
+ distribute this file as part of a program that contains a
+ configuration script generated by Autoconf, you may include it under
+ the same distribution terms that you use for the rest of that
+ program.
+
+ (The condition for the exception is fulfilled because
+ ICU4C includes a configuration script generated by Autoconf,
+ namely the `configure` script.)
+
+ ----------------------------------------------------------------------
+
+ File: config.guess (only for ICU4C)
+
+ This file 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 .
+
+ As a special exception to the GNU General Public License, if you
+ distribute this file as part of a program that contains a
+ configuration script generated by Autoconf, you may include it under
+ the same distribution terms that you use for the rest of that
+ program. This Exception is an additional permission under section 7
+ of the GNU General Public License, version 3 ("GPLv3").
+
+ (The condition for the exception is fulfilled because
+ ICU4C includes a configuration script generated by Autoconf,
+ namely the `configure` script.)
+
+ ----------------------------------------------------------------------
+
+ File: install-sh (only for ICU4C)
+
+ Copyright 1991 by the Massachusetts Institute of Technology
+
+ Permission to use, copy, modify, distribute, and sell this software and its
+ documentation for any purpose is hereby granted without fee, provided that
+ the above copyright notice appear in all copies and that both that
+ copyright notice and this permission notice appear in supporting
+ documentation, and that the name of M.I.T. not be used in advertising or
+ publicity pertaining to distribution of the software without specific,
+ written prior permission. M.I.T. makes no representations about the
+ suitability of this software for any purpose. It is provided "as is"
+ without express or implied warranty.
+
+ ----------------------------------------------------------------------
+
+ File: sorttable.js (only for ICU4J)
+
+ The MIT Licence, for code from kryogenix.org
+
+ Code downloaded from the Browser Experiments section of kryogenix.org is
+ licenced under the so-called MIT licence. The licence is below.
+
+ Copyright (c) 1997-date Stuart Langridge
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the "Software"),
+ to deal in the Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ and/or sell copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following conditions:
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- libuv, located at deps/uv, is licensed as follows:
+ """
+ Copyright (c) 2015-present libuv project contributors.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to
+ deal in the Software without restriction, including without limitation the
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ IN THE SOFTWARE.
+ This license applies to parts of libuv originating from the
+ https://github.com/joyent/libuv repository:
+
+ ====
+
+ Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to
+ deal in the Software without restriction, including without limitation the
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ IN THE SOFTWARE.
+
+ ====
+
+ This license applies to all parts of libuv that are not externally
+ maintained libraries.
+
+ The externally maintained libraries used by libuv are:
+
+ - tree.h (from FreeBSD), copyright Niels Provos. Two clause BSD license.
+
+ - inet_pton and inet_ntop implementations, contained in src/inet.c, are
+ copyright the Internet Systems Consortium, Inc., and licensed under the ISC
+ license.
+ """
+
+- LIEF, located at deps/LIEF, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017 - 2025 R. Thomas
+ Copyright 2017 - 2025 Quarkslab
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+
+- llhttp, located at deps/llhttp, is licensed as follows:
+ """
+ This software is licensed under the MIT License.
+
+ Copyright Fedor Indutny, 2018.
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- corepack, located at deps/corepack, is licensed as follows:
+ """
+ **Copyright © Corepack contributors**
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- undici, located at deps/undici, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) Matteo Collina and Undici contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- postject, located at test/fixtures/postject-copy, is licensed as follows:
+ """
+ Postject is licensed for use as follows:
+
+ """
+ MIT License
+
+ Copyright (c) 2022 Postman, Inc
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+ The Postject license applies to all parts of Postject that are not externally
+ maintained libraries.
+
+ The externally maintained libraries used by Postject are:
+
+ - LIEF, located at vendor/LIEF, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017 - 2022 R. Thomas
+ Copyright 2017 - 2022 Quarkslab
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+ """
+
+- OpenSSL, located at deps/openssl, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+ """
+
+- Punycode.js, located at lib/punycode.js, is licensed as follows:
+ """
+ Copyright Mathias Bynens
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- V8, located at deps/v8, is licensed as follows:
+ """
+ This license applies to all parts of V8 that are not externally
+ maintained libraries. The externally maintained libraries used by V8
+ are:
+
+ - PCRE test suite, located in
+ test/mjsunit/third_party/regexp-pcre/regexp-pcre.js. This is based on the
+ test suite from PCRE-7.3, which is copyrighted by the University
+ of Cambridge and Google, Inc. The copyright notice and license
+ are embedded in regexp-pcre.js.
+
+ - Layout tests, located in test/mjsunit/third_party/object-keys. These are
+ based on layout tests from webkit.org which are copyrighted by
+ Apple Computer, Inc. and released under a 3-clause BSD license.
+
+ - Strongtalk assembler, the basis of the files assembler-arm-inl.h,
+ assembler-arm.cc, assembler-arm.h, assembler-ia32-inl.h,
+ assembler-ia32.cc, assembler-ia32.h, assembler-x64-inl.h,
+ assembler-x64.cc, assembler-x64.h, assembler.cc and assembler.h.
+ This code is copyrighted by Sun Microsystems Inc. and released
+ under a 3-clause BSD license.
+
+ - Valgrind client API header, located at third_party/valgrind/valgrind.h
+ This is released under the BSD license.
+
+ - The Wasm C/C++ API headers, located at third_party/wasm-api/wasm.{h,hh}
+ This is released under the Apache license. The API's upstream prototype
+ implementation also formed the basis of V8's implementation in
+ src/wasm/c-api.cc.
+
+ These libraries have their own licenses; we recommend you read them,
+ as their terms may differ from the terms below.
+
+ Further license information can be found in LICENSE files located in
+ sub-directories.
+
+ Copyright 2014, the V8 project authors. All rights reserved.
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- SipHash, located at deps/v8/src/third_party/siphash, is licensed as follows:
+ """
+ SipHash reference C implementation
+
+ Copyright (c) 2016 Jean-Philippe Aumasson
+
+ To the extent possible under law, the author(s) have dedicated all
+ copyright and related and neighboring rights to this software to the public
+ domain worldwide. This software is distributed without any warranty.
+ """
+
+- zlib, located at deps/zlib, is licensed as follows:
+ """
+ zlib.h -- interface of the 'zlib' general purpose compression library
+ version 1.3.2.1, February xxth, 2026
+
+ Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+ """
+
+- simdjson, located at deps/simdjson, is licensed as follows:
+ """
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2018-2025 The simdjson authors
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+
+- simdutf, located at deps/v8/third_party/simdutf, is licensed as follows:
+ """
+ Copyright 2021 The simdutf authors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal in
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ the Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- ada, located at deps/ada, is licensed as follows:
+ """
+ Copyright 2023 Yagiz Nizipli and Daniel Lemire
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
+ this software and associated documentation files (the "Software"), to deal in
+ the Software without restriction, including without limitation the rights to
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ the Software, and to permit persons to whom the Software is furnished to do so,
+ subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- minimatch, located at deps/minimatch, is licensed as follows:
+ """
+ # Blue Oak Model License
+
+ Version 1.0.0
+
+ ## Purpose
+
+ This license gives everyone as much permission to work with
+ this software as possible, while protecting contributors
+ from liability.
+
+ ## Acceptance
+
+ In order to receive this license, you must agree to its
+ rules. The rules of this license are both obligations
+ under that agreement and conditions to your license.
+ You must not do anything with this software that triggers
+ a rule that you cannot or will not follow.
+
+ ## Copyright
+
+ Each contributor licenses you to do everything with this
+ software that would otherwise infringe that contributor's
+ copyright in it.
+
+ ## Notices
+
+ You must ensure that everyone who gets a copy of
+ any part of this software from you, with or without
+ changes, also gets the text of this license or a link to
+ .
+
+ ## Excuse
+
+ If anyone notifies you in writing that you have not
+ complied with [Notices](#notices), you can keep your
+ license by taking all practical steps to comply within 30
+ days after the notice. If you do not do so, your license
+ ends immediately.
+
+ ## Patent
+
+ Each contributor licenses you to do everything with this
+ software that would otherwise infringe any patent claims
+ they can license or become able to license.
+
+ ## Reliability
+
+ No contributor can revoke this license.
+
+ ## No Liability
+
+ **_As far as the law allows, this software comes as is,
+ without any warranty or condition, and no contributor
+ will be liable to anyone for any damages related to this
+ software or this license, under any kind of legal claim._**
+ """
+
+- npm, located at deps/npm, is licensed as follows:
+ """
+ The npm application
+ Copyright (c) npm, Inc. and Contributors
+ Licensed on the terms of The Artistic License 2.0
+
+ Node package dependencies of the npm application
+ Copyright (c) their respective copyright owners
+ Licensed on their respective license terms
+
+ The npm public registry at https://registry.npmjs.org
+ and the npm website at https://www.npmjs.com
+ Operated by npm, Inc.
+ Use governed by terms published on https://www.npmjs.com
+
+ "Node.js"
+ Trademark Joyent, Inc., https://joyent.com
+ Neither npm nor npm, Inc. are affiliated with Joyent, Inc.
+
+ The Node.js application
+ Project of Node Foundation, https://nodejs.org
+
+ The npm Logo
+ Copyright (c) Mathias Pettersson and Brian Hammond
+
+ "Gubblebum Blocky" typeface
+ Copyright (c) Tjarda Koster, https://jelloween.deviantart.com
+ Used with permission
+
+ --------
+
+ The Artistic License 2.0
+
+ Copyright (c) 2000-2006, The Perl Foundation.
+
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ This license establishes the terms under which a given free software
+ Package may be copied, modified, distributed, and/or redistributed.
+ The intent is that the Copyright Holder maintains some artistic
+ control over the development of that Package while still keeping the
+ Package available as open source and free software.
+
+ You are always permitted to make arrangements wholly outside of this
+ license directly with the Copyright Holder of a given Package. If the
+ terms of this license do not permit the full use that you propose to
+ make of the Package, you should contact the Copyright Holder and seek
+ a different licensing arrangement.
+
+ Definitions
+
+ "Copyright Holder" means the individual(s) or organization(s)
+ named in the copyright notice for the entire Package.
+
+ "Contributor" means any party that has contributed code or other
+ material to the Package, in accordance with the Copyright Holder's
+ procedures.
+
+ "You" and "your" means any person who would like to copy,
+ distribute, or modify the Package.
+
+ "Package" means the collection of files distributed by the
+ Copyright Holder, and derivatives of that collection and/or of
+ those files. A given Package may consist of either the Standard
+ Version, or a Modified Version.
+
+ "Distribute" means providing a copy of the Package or making it
+ accessible to anyone else, or in the case of a company or
+ organization, to others outside of your company or organization.
+
+ "Distributor Fee" means any fee that you charge for Distributing
+ this Package or providing support for this Package to another
+ party. It does not mean licensing fees.
+
+ "Standard Version" refers to the Package if it has not been
+ modified, or has been modified only in ways explicitly requested
+ by the Copyright Holder.
+
+ "Modified Version" means the Package, if it has been changed, and
+ such changes were not explicitly requested by the Copyright
+ Holder.
+
+ "Original License" means this Artistic License as Distributed with
+ the Standard Version of the Package, in its current version or as
+ it may be modified by The Perl Foundation in the future.
+
+ "Source" form means the source code, documentation source, and
+ configuration files for the Package.
+
+ "Compiled" form means the compiled bytecode, object code, binary,
+ or any other form resulting from mechanical transformation or
+ translation of the Source form.
+
+ Permission for Use and Modification Without Distribution
+
+ (1) You are permitted to use the Standard Version and create and use
+ Modified Versions for any purpose without restriction, provided that
+ you do not Distribute the Modified Version.
+
+ Permissions for Redistribution of the Standard Version
+
+ (2) You may Distribute verbatim copies of the Source form of the
+ Standard Version of this Package in any medium without restriction,
+ either gratis or for a Distributor Fee, provided that you duplicate
+ all of the original copyright notices and associated disclaimers. At
+ your discretion, such verbatim copies may or may not include a
+ Compiled form of the Package.
+
+ (3) You may apply any bug fixes, portability changes, and other
+ modifications made available from the Copyright Holder. The resulting
+ Package will still be considered the Standard Version, and as such
+ will be subject to the Original License.
+
+ Distribution of Modified Versions of the Package as Source
+
+ (4) You may Distribute your Modified Version as Source (either gratis
+ or for a Distributor Fee, and with or without a Compiled form of the
+ Modified Version) provided that you clearly document how it differs
+ from the Standard Version, including, but not limited to, documenting
+ any non-standard features, executables, or modules, and provided that
+ you do at least ONE of the following:
+
+ (a) make the Modified Version available to the Copyright Holder
+ of the Standard Version, under the Original License, so that the
+ Copyright Holder may include your modifications in the Standard
+ Version.
+
+ (b) ensure that installation of your Modified Version does not
+ prevent the user installing or running the Standard Version. In
+ addition, the Modified Version must bear a name that is different
+ from the name of the Standard Version.
+
+ (c) allow anyone who receives a copy of the Modified Version to
+ make the Source form of the Modified Version available to others
+ under
+
+ (i) the Original License or
+
+ (ii) a license that permits the licensee to freely copy,
+ modify and redistribute the Modified Version using the same
+ licensing terms that apply to the copy that the licensee
+ received, and requires that the Source form of the Modified
+ Version, and of any works derived from it, be made freely
+ available in that license fees are prohibited but Distributor
+ Fees are allowed.
+
+ Distribution of Compiled Forms of the Standard Version
+ or Modified Versions without the Source
+
+ (5) You may Distribute Compiled forms of the Standard Version without
+ the Source, provided that you include complete instructions on how to
+ get the Source of the Standard Version. Such instructions must be
+ valid at the time of your distribution. If these instructions, at any
+ time while you are carrying out such distribution, become invalid, you
+ must provide new instructions on demand or cease further distribution.
+ If you provide valid instructions or cease distribution within thirty
+ days after you become aware that the instructions are invalid, then
+ you do not forfeit any of your rights under this license.
+
+ (6) You may Distribute a Modified Version in Compiled form without
+ the Source, provided that you comply with Section 4 with respect to
+ the Source of the Modified Version.
+
+ Aggregating or Linking the Package
+
+ (7) You may aggregate the Package (either the Standard Version or
+ Modified Version) with other packages and Distribute the resulting
+ aggregation provided that you do not charge a licensing fee for the
+ Package. Distributor Fees are permitted, and licensing fees for other
+ components in the aggregation are permitted. The terms of this license
+ apply to the use and Distribution of the Standard or Modified Versions
+ as included in the aggregation.
+
+ (8) You are permitted to link Modified and Standard Versions with
+ other works, to embed the Package in a larger work of your own, or to
+ build stand-alone binary or bytecode versions of applications that
+ include the Package, and Distribute the result without restriction,
+ provided the result does not expose a direct interface to the Package.
+
+ Items That are Not Considered Part of a Modified Version
+
+ (9) Works (including, but not limited to, modules and scripts) that
+ merely extend or make use of the Package, do not, by themselves, cause
+ the Package to be a Modified Version. In addition, such works are not
+ considered parts of the Package itself, and are not subject to the
+ terms of this license.
+
+ General Provisions
+
+ (10) Any use, modification, and distribution of the Standard or
+ Modified Versions is governed by this Artistic License. By using,
+ modifying or distributing the Package, you accept this license. Do not
+ use, modify, or distribute the Package, if you do not accept this
+ license.
+
+ (11) If your Modified Version has been derived from a Modified
+ Version made by someone other than you, you are nevertheless required
+ to ensure that your Modified Version complies with the requirements of
+ this license.
+
+ (12) This license does not grant you the right to use any trademark,
+ service mark, tradename, or logo of the Copyright Holder.
+
+ (13) This license includes the non-exclusive, worldwide,
+ free-of-charge patent license to make, have made, use, offer to sell,
+ sell, import and otherwise transfer the Package with respect to any
+ patent claims licensable by the Copyright Holder that are necessarily
+ infringed by the Package. If you institute patent litigation
+ (including a cross-claim or counterclaim) against any party alleging
+ that the Package constitutes direct or contributory patent
+ infringement, then this Artistic License to you shall terminate on the
+ date that such litigation is filed.
+
+ (14) Disclaimer of Warranty:
+ THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS
+ IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL
+ LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL
+ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+ DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF
+ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ --------
+ """
+
+- GYP, located at tools/gyp, is licensed as follows:
+ """
+ Copyright (c) 2020 Node.js contributors. All rights reserved.
+ Copyright (c) 2009 Google Inc. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- inspector_protocol, located at deps/inspector_protocol, is licensed as follows:
+ """
+ // Copyright 2016 The Chromium Authors.
+ //
+ // Redistribution and use in source and binary forms, with or without
+ // modification, are permitted provided that the following conditions are
+ // met:
+ //
+ // * Redistributions of source code must retain the above copyright
+ // notice, this list of conditions and the following disclaimer.
+ // * Redistributions in binary form must reproduce the above
+ // copyright notice, this list of conditions and the following disclaimer
+ // in the documentation and/or other materials provided with the
+ // distribution.
+ // * Neither the name of Google Inc. nor the names of its
+ // contributors may be used to endorse or promote products derived from
+ // this software without specific prior written permission.
+ //
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- jinja2, located at tools/inspector_protocol/jinja2, is licensed as follows:
+ """
+ Copyright (c) 2009 by the Jinja Team, see AUTHORS for more details.
+
+ Some rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * The names of the contributors may not be used to endorse or
+ promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- markupsafe, located at tools/inspector_protocol/markupsafe, is licensed as follows:
+ """
+ Copyright (c) 2010 by Armin Ronacher and contributors. See AUTHORS
+ for more details.
+
+ Some rights reserved.
+
+ Redistribution and use in source and binary forms of the software as well
+ as documentation, with or without modification, are permitted provided
+ that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * The names of the contributors may not be used to endorse or
+ promote products derived from this software without specific
+ prior written permission.
+
+ THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
+ NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+ OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ DAMAGE.
+ """
+
+- cpplint.py, located at tools/cpplint.py, is licensed as follows:
+ """
+ Copyright (c) 2009 Google Inc. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- gypi_to_gn.py, located at tools/gypi_to_gn.py, is licensed as follows:
+ """
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of Google LLC nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- gtest, located at deps/googletest, is licensed as follows:
+ """
+ Copyright 2008, Google Inc.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+ * Neither the name of Google Inc. nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- nghttp2, located at deps/nghttp2, is licensed as follows:
+ """
+ The MIT License
+
+ Copyright (c) 2012, 2014, 2015, 2016 Tatsuhiro Tsujikawa
+ Copyright (c) 2012, 2014, 2015, 2016 nghttp2 contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- large_pages, located at src/large_pages, is licensed as follows:
+ """
+ Copyright (C) 2018 Intel Corporation
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"),
+ to deal in the Software without restriction, including without limitation
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ and/or sell copies of the Software, and to permit persons to whom
+ the Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
+ OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
+ OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- caja, located at lib/internal/freeze_intrinsics.js, is licensed as follows:
+ """
+ Adapted from SES/Caja - Copyright (C) 2011 Google Inc.
+ Copyright (C) 2018 Agoric
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ """
+
+- brotli, located at deps/brotli, is licensed as follows:
+ """
+ Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ """
+
+- zstd, located at deps/zstd, is licensed as follows:
+ """
+ BSD License
+
+ For Zstandard software
+
+ Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modification,
+ are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name Facebook, nor Meta, nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- HdrHistogram, located at deps/histogram, is licensed as follows:
+ """
+ The code in this repository code was Written by Gil Tene, Michael Barker,
+ and Matt Warren, and released to the public domain, as explained at
+ http://creativecommons.org/publicdomain/zero/1.0/
+
+ For users of this code who wish to consume it under the "BSD" license
+ rather than under the public domain or CC0 contribution text mentioned
+ above, the code found under this directory is *also* provided under the
+ following license (commonly referred to as the BSD 2-Clause License). This
+ license does not detract from the above stated release of the code into
+ the public domain, and simply represents an additional license granted by
+ the Author.
+
+ -----------------------------------------------------------------------------
+ ** Beginning of "BSD 2-Clause License" text. **
+
+ Copyright (c) 2012, 2013, 2014 Gil Tene
+ Copyright (c) 2014 Michael Barker
+ Copyright (c) 2014 Matt Warren
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ THE POSSIBILITY OF SUCH DAMAGE.
+ """
+
+- node-heapdump, located at src/heap_utils.cc, is licensed as follows:
+ """
+ ISC License
+
+ Copyright (c) 2012, Ben Noordhuis
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted, provided that the above
+ copyright notice and this permission notice appear in all copies.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+ === src/compat.h src/compat-inl.h ===
+
+ ISC License
+
+ Copyright (c) 2014, StrongLoop Inc.
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted, provided that the above
+ copyright notice and this permission notice appear in all copies.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ """
+
+- rimraf, located at lib/internal/fs/rimraf.js, is licensed as follows:
+ """
+ The ISC License
+
+ Copyright (c) Isaac Z. Schlueter and Contributors
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted, provided that the above
+ copyright notice and this permission notice appear in all copies.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ """
+
+- uvwasi, located at deps/uvwasi, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) 2019 Colin Ihrig and Contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- ngtcp2, located at deps/ngtcp2/ngtcp2/, is licensed as follows:
+ """
+ The MIT License
+
+ Copyright (c) 2016 ngtcp2 contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- nghttp3, located at deps/ngtcp2/nghttp3/, is licensed as follows:
+ """
+ The MIT License
+
+ Copyright (c) 2019 nghttp3 contributors
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- node-fs-extra, located at lib/internal/fs/cp, is licensed as follows:
+ """
+ (The MIT License)
+
+ Copyright (c) 2011-2017 JP Richardson
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
+ (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+ OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ """
+
+- on-exit-leak-free, located at lib/internal/process/finalization, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) 2021 Matteo Collina
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+- sonic-boom, located at lib/internal/streams/fast-utf8-stream.js, is licensed as follows:
+ """
+ MIT License
+
+ Copyright (c) 2017 Matteo Collina
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
diff --git a/agents/pi/dist/pi-runner.mjs b/agents/pi/dist/pi-runner.mjs
new file mode 100644
index 0000000..3840e3c
--- /dev/null
+++ b/agents/pi/dist/pi-runner.mjs
@@ -0,0 +1,48423 @@
+import { createRequire as esfCreateRequire } from 'node:module'; const require = esfCreateRequire(import.meta.url);
+var __create = Object.create;
+var __defProp = Object.defineProperty;
+var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+var __getOwnPropNames = Object.getOwnPropertyNames;
+var __getProtoOf = Object.getPrototypeOf;
+var __hasOwnProp = Object.prototype.hasOwnProperty;
+var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
+}) : x)(function(x) {
+ if (typeof require !== "undefined") return require.apply(this, arguments);
+ throw Error('Dynamic require of "' + x + '" is not supported');
+});
+var __esm = (fn, res) => function __init() {
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
+};
+var __commonJS = (cb, mod) => function __require2() {
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
+};
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+};
+var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
+ // If the importer is in node compatibility mode or this is not an ESM
+ // file that has been converted to a CommonJS file using a Babel-
+ // compatible transform (i.e. "__esModule" has not been set), then set
+ // "default" to the CommonJS "module.exports" for node compatibility.
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
+ mod
+));
+
+// node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js
+var FifoQueue, EventStream, AssistantMessageEventStream;
+var init_event_stream = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js"() {
+ FifoQueue = class {
+ incoming = [];
+ outgoing = [];
+ get length() {
+ return this.incoming.length + this.outgoing.length;
+ }
+ enqueue(value) {
+ this.incoming.push(value);
+ }
+ dequeue() {
+ if (this.outgoing.length === 0) {
+ while (this.incoming.length > 0) {
+ this.outgoing.push(this.incoming.pop());
+ }
+ }
+ return this.outgoing.pop();
+ }
+ };
+ EventStream = class {
+ queue = new FifoQueue();
+ waiting = new FifoQueue();
+ done = false;
+ finalResultPromise;
+ resolveFinalResult;
+ isComplete;
+ extractResult;
+ constructor(isComplete, extractResult) {
+ this.isComplete = isComplete;
+ this.extractResult = extractResult;
+ this.finalResultPromise = new Promise((resolve3) => {
+ this.resolveFinalResult = resolve3;
+ });
+ }
+ push(event) {
+ if (this.done)
+ return;
+ if (this.isComplete(event)) {
+ this.done = true;
+ this.resolveFinalResult(this.extractResult(event));
+ }
+ const waiter = this.waiting.dequeue();
+ if (waiter) {
+ waiter({ value: event, done: false });
+ } else {
+ this.queue.enqueue(event);
+ }
+ }
+ end(result) {
+ this.done = true;
+ if (result !== void 0) {
+ this.resolveFinalResult(result);
+ }
+ while (this.waiting.length > 0) {
+ const waiter = this.waiting.dequeue();
+ waiter({ value: void 0, done: true });
+ }
+ }
+ async *[Symbol.asyncIterator]() {
+ while (true) {
+ if (this.queue.length > 0) {
+ yield this.queue.dequeue();
+ } else if (this.done) {
+ return;
+ } else {
+ const result = await new Promise((resolve3) => this.waiting.enqueue(resolve3));
+ if (result.done)
+ return;
+ yield result.value;
+ }
+ }
+ }
+ result() {
+ return this.finalResultPromise;
+ }
+ };
+ AssistantMessageEventStream = class extends EventStream {
+ constructor() {
+ super((event) => event.type === "done" || event.type === "error", (event) => {
+ if (event.type === "done") {
+ return event.message;
+ } else if (event.type === "error") {
+ return event.error;
+ }
+ throw new Error("Unexpected event type for final result");
+ });
+ }
+ };
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/api/lazy.js
+function createSetupErrorMessage(model, error) {
+ return {
+ role: "assistant",
+ content: [],
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
+ },
+ stopReason: "error",
+ errorMessage: error instanceof Error ? error.message : String(error),
+ timestamp: Date.now()
+ };
+}
+function hasResult(source) {
+ return typeof source.result === "function";
+}
+async function forwardStream(target, source) {
+ for await (const event of source) {
+ target.push(event);
+ }
+ target.end(hasResult(source) ? await source.result() : void 0);
+}
+function lazyStream(model, setup) {
+ const outer = new AssistantMessageEventStream();
+ setup().then((inner) => forwardStream(outer, inner)).catch((error) => {
+ const message = createSetupErrorMessage(model, error);
+ outer.push({ type: "error", reason: "error", error: message });
+ outer.end(message);
+ });
+ return outer;
+}
+function lazyApi(load, capabilities) {
+ const api = {
+ stream: (model, context, options) => lazyStream(model, async () => (await load()).stream(model, context, options)),
+ streamSimple: (model, context, options) => lazyStream(model, async () => (await load()).streamSimple(model, context, options))
+ };
+ if (capabilities?.fetchDeferred) {
+ api.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
+ const implementation = await load();
+ if (!implementation.fetchDeferred)
+ throw new Error("API does not support deferred responses");
+ return implementation.fetchDeferred(model, handle, options);
+ });
+ }
+ if (capabilities?.cancelDeferred) {
+ api.cancelDeferred = async (model, handle, options) => {
+ const implementation = await load();
+ if (!implementation.cancelDeferred)
+ throw new Error("API cannot cancel deferred responses");
+ await implementation.cancelDeferred(model, handle, options);
+ };
+ }
+ return api;
+}
+var init_lazy = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/lazy.js"() {
+ init_event_stream();
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/auth/context.js
+function getProcessEnv() {
+ const proc = globalThis.process;
+ return proc?.env;
+}
+function defaultProviderAuthContext() {
+ return {
+ async env(name) {
+ const value = getProcessEnv()?.[name];
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
+ },
+ async fileExists(path5) {
+ try {
+ const fs3 = await importNodeModule("node:fs/promises");
+ let resolved = path5;
+ if (resolved.startsWith("~")) {
+ const os = await importNodeModule("node:os");
+ resolved = os.homedir() + resolved.slice(1);
+ }
+ await fs3.access(resolved);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+ };
+}
+var __rewriteRelativeImportExtension, importNodeModule;
+var init_context = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/auth/context.js"() {
+ __rewriteRelativeImportExtension = function(path5, preserveJsx) {
+ if (typeof path5 === "string" && /^\.\.?\//.test(path5)) {
+ return path5.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
+ });
+ }
+ return path5;
+ };
+ importNodeModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/abort.js
+function abortReason(signal) {
+ if (signal.reason !== void 0)
+ return signal.reason;
+ const error = new Error("The operation was aborted");
+ error.name = "AbortError";
+ return error;
+}
+function operationSignal(signal) {
+ return signal ?? new AbortController().signal;
+}
+function raceWithAbortSignal(operation, signal) {
+ if (signal.aborted) {
+ void operation.catch(() => {
+ });
+ return Promise.reject(abortReason(signal));
+ }
+ return new Promise((resolve3, reject) => {
+ let settled = false;
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
+ const onAbort = () => {
+ if (settled)
+ return;
+ settled = true;
+ cleanup();
+ reject(abortReason(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ void operation.then((value) => {
+ if (settled)
+ return;
+ settled = true;
+ cleanup();
+ resolve3(value);
+ }, (error) => {
+ if (settled)
+ return;
+ settled = true;
+ cleanup();
+ reject(error);
+ });
+ if (signal.aborted)
+ onAbort();
+ });
+}
+var init_abort = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/abort.js"() {
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js
+var InMemoryCredentialStore;
+var init_credential_store = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js"() {
+ init_abort();
+ InMemoryCredentialStore = class {
+ credentials = /* @__PURE__ */ new Map();
+ chains = /* @__PURE__ */ new Map();
+ /** Serialize tasks per provider id without releasing the chain before active work settles. */
+ enqueue(providerId, task, options) {
+ const signal = operationSignal(options?.signal);
+ const previous = this.chains.get(providerId) ?? Promise.resolve();
+ const queued2 = (async () => {
+ await previous.catch(() => {
+ });
+ signal.throwIfAborted();
+ return task();
+ })();
+ const tail = queued2.catch(() => {
+ });
+ this.chains.set(providerId, tail);
+ void tail.then(() => {
+ if (this.chains.get(providerId) === tail)
+ this.chains.delete(providerId);
+ });
+ return raceWithAbortSignal(queued2, signal);
+ }
+ async read(providerId, options) {
+ options?.signal?.throwIfAborted();
+ return this.credentials.get(providerId);
+ }
+ async list(options) {
+ options?.signal?.throwIfAborted();
+ return [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));
+ }
+ modify(providerId, fn, options) {
+ return this.enqueue(providerId, async () => {
+ const current = this.credentials.get(providerId);
+ const next = await fn(current);
+ options?.signal?.throwIfAborted();
+ if (next !== void 0)
+ this.credentials.set(providerId, next);
+ return next ?? current;
+ }, options);
+ }
+ delete(providerId, options) {
+ return this.enqueue(providerId, async () => {
+ this.credentials.delete(providerId);
+ }, options);
+ }
+ };
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/diagnostics.js
+function formatThrownValue(value) {
+ if (value instanceof Error)
+ return value.message || value.name;
+ if (typeof value === "string")
+ return value;
+ return String(value);
+}
+var init_diagnostics = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/diagnostics.js"() {
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/models-error.js
+function withCauseDetail(message, cause) {
+ if (cause === void 0 || cause === null)
+ return message;
+ const detail = formatThrownValue(cause).trim();
+ if (!detail || message.includes(detail))
+ return message;
+ return `${message}: ${detail}`;
+}
+var ModelsError;
+var init_models_error = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/models-error.js"() {
+ init_diagnostics();
+ ModelsError = class extends Error {
+ code;
+ constructor(code, message, options) {
+ super(withCauseDetail(message, options?.cause), options);
+ this.name = "ModelsError";
+ this.code = code;
+ }
+ };
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/auth/resolve.js
+function resolveProviderAuth(provider, credentials, authContext, overrides) {
+ const signal = operationSignal(overrides?.signal);
+ return raceWithAbortSignal(resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal), signal);
+}
+async function resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal) {
+ signal.throwIfAborted();
+ const requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;
+ if (overrides?.apiKey !== void 0 && provider.auth.apiKey) {
+ return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, {
+ type: "api_key",
+ key: overrides.apiKey,
+ env: overrides.env
+ }, signal);
+ }
+ const stored = await readCredential(credentials, provider.id, signal);
+ if (stored) {
+ if (stored.type === "oauth" && provider.auth.oauth) {
+ return resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored, signal, overrides?.minOAuthValidityMs);
+ }
+ if (stored.type === "api_key" && provider.auth.apiKey) {
+ const credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;
+ return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);
+ }
+ return void 0;
+ }
+ return provider.auth.apiKey ? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, void 0, signal) : void 0;
+}
+function overlayEnvAuthContext(base, env) {
+ return {
+ env: async (name) => env[name] || await base.env(name),
+ fileExists: (path5) => base.fileExists(path5)
+ };
+}
+async function refreshStoredOAuthCredential(credentials, providerId, oauth, needsRefresh, signal) {
+ let post;
+ const lockWait = new AbortController();
+ const cancelLockWait = () => lockWait.abort(signal.reason);
+ signal.addEventListener("abort", cancelLockWait, { once: true });
+ if (signal.aborted)
+ cancelLockWait();
+ try {
+ post = await credentials.modify(providerId, async (current) => {
+ signal.removeEventListener("abort", cancelLockWait);
+ signal.throwIfAborted();
+ if (current?.type !== "oauth")
+ return void 0;
+ if (!needsRefresh(current))
+ return void 0;
+ try {
+ return await oauth.refresh(current, AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS));
+ } catch (error) {
+ throw new ModelsError("oauth", `OAuth refresh failed for ${providerId}`, { cause: error });
+ }
+ }, { signal: lockWait.signal });
+ } catch (error) {
+ if (error instanceof ModelsError)
+ throw error;
+ signal.throwIfAborted();
+ throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
+ } finally {
+ signal.removeEventListener("abort", cancelLockWait);
+ }
+ return post?.type === "oauth" ? post : void 0;
+}
+async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal, minOAuthValidityMs) {
+ const minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);
+ const expiresSoon = (credential2) => Date.now() + minimumValidityMs >= credential2.expires;
+ let credential = stored;
+ if (expiresSoon(credential)) {
+ const post = await refreshStoredOAuthCredential(credentials, providerId, oauth, expiresSoon, signal);
+ if (!post)
+ return void 0;
+ credential = post;
+ if (minOAuthValidityMs !== void 0 && expiresSoon(credential)) {
+ throw new ModelsError("oauth", `OAuth refresh returned a token that expires too soon for ${providerId}`);
+ }
+ }
+ try {
+ return { auth: await oauth.toAuth(credential), source: "OAuth" };
+ } catch (error) {
+ throw new ModelsError("oauth", `OAuth auth derivation failed for ${providerId}`, { cause: error });
+ }
+}
+async function resolveApiKey(authContext, apiKey, providerId, credential, signal) {
+ try {
+ return await apiKey.resolve({ ctx: authContext, credential, signal });
+ } catch (error) {
+ throw new ModelsError("auth", `API key auth failed for provider ${providerId}`, { cause: error });
+ }
+}
+async function readCredential(credentials, providerId, signal) {
+ try {
+ return await credentials.read(providerId, { signal });
+ } catch (error) {
+ throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
+ }
+}
+var DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, DEFAULT_OAUTH_REFRESH_TIMEOUT_MS;
+var init_resolve = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/auth/resolve.js"() {
+ init_abort();
+ init_models_error();
+ init_models_error();
+ DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1e3;
+ DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15e3;
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/models-store.js
+var InMemoryModelsStore;
+var init_models_store = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/models-store.js"() {
+ InMemoryModelsStore = class {
+ entries = /* @__PURE__ */ new Map();
+ async read(providerId, options) {
+ options?.signal?.throwIfAborted();
+ const entry = this.entries.get(providerId);
+ return entry ? structuredClone(entry) : void 0;
+ }
+ async write(providerId, entry, options) {
+ options?.signal?.throwIfAborted();
+ this.entries.set(providerId, structuredClone(entry));
+ }
+ async delete(providerId, options) {
+ options?.signal?.throwIfAborted();
+ this.entries.delete(providerId);
+ }
+ };
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/model-operations.js
+function getModelType(model) {
+ return model.type ?? "chat";
+}
+function isModelType(model, type) {
+ return getModelType(model) === type;
+}
+function assertChatModel(model) {
+ if (!isModelType(model, "chat")) {
+ throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not a chat model`);
+ }
+}
+function assertImageModel(model) {
+ if (!isModelType(model, "image")) {
+ throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not an image model`);
+ }
+}
+function assertClassifierModel(model) {
+ if (!isModelType(model, "classifier")) {
+ throw new ModelsError("provider", `Model ${model.provider}/${model.id} is not a classifier model`);
+ }
+}
+function imageErrorResult(model, error, aborted = false) {
+ return {
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ output: [],
+ stopReason: aborted ? "aborted" : "error",
+ errorMessage: error instanceof Error ? error.message : String(error),
+ timestamp: Date.now()
+ };
+}
+function classifierErrorResult(model, error, aborted = false) {
+ return {
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ answers: {},
+ stopReason: aborted ? "aborted" : "error",
+ errorMessage: error instanceof Error ? error.message : String(error),
+ timestamp: Date.now()
+ };
+}
+var init_model_operations = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/model-operations.js"() {
+ init_models_error();
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/text.js
+function contentText(content, separator = "\n") {
+ if (typeof content === "string")
+ return content;
+ return content.filter((block) => block.type === "text").map((block) => block.text).join(separator);
+}
+function getSystemMessageText(message) {
+ const parts2 = [contentText(message.content)];
+ for (const text of Object.values(message.sections ?? {})) {
+ if (text !== null)
+ parts2.push(text);
+ }
+ return parts2.filter((part) => part.length > 0).join("\n\n");
+}
+function renderSystemMessageUpdate(message) {
+ const parts2 = [];
+ const text = contentText(message.content);
+ if (text.length > 0)
+ parts2.push(text);
+ for (const [name, value] of Object.entries(message.sections ?? {})) {
+ parts2.push(value === null ? `Removed system prompt section "${name}".` : `Updated system prompt section "${name}":
+
+${value}`);
+ }
+ return parts2.join("\n\n");
+}
+var init_text = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/text.js"() {
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/transcript.js
+function createInitialSystemMessage(systemPrompt, tools) {
+ const hasSystemPrompt = systemPrompt !== void 0 && systemPrompt.length > 0;
+ const hasTools = tools !== void 0 && tools.length > 0;
+ if (!hasSystemPrompt && !hasTools)
+ return void 0;
+ return {
+ role: "system",
+ content: systemPrompt ?? "",
+ ...hasTools ? { toolsAdded: tools } : {},
+ timestamp: 0
+ };
+}
+function normalizeContext(context) {
+ const initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);
+ const messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;
+ return { messages };
+}
+function isSystemMessage(message) {
+ return message.role === "system";
+}
+function getInitialSystemMessage(messages) {
+ const first = messages[0];
+ return first && isSystemMessage(first) ? first : void 0;
+}
+function getCurrentTools(messages) {
+ const tools = /* @__PURE__ */ new Map();
+ for (const message of messages) {
+ if (!isSystemMessage(message))
+ continue;
+ for (const tool of message.toolsRemoved ?? [])
+ tools.delete(tool.name);
+ for (const tool of message.toolsAdded ?? [])
+ tools.set(tool.name, tool);
+ }
+ return [...tools.values()];
+}
+function getCurrentSystemMessage(messages) {
+ const content = [];
+ const sections = /* @__PURE__ */ new Map();
+ let timestamp;
+ for (const message of messages) {
+ if (!isSystemMessage(message))
+ continue;
+ timestamp ??= message.timestamp;
+ const text = contentText(message.content);
+ if (text.length > 0)
+ content.push(text);
+ for (const [name, value] of Object.entries(message.sections ?? {})) {
+ if (value === null)
+ sections.delete(name);
+ else
+ sections.set(name, value);
+ }
+ }
+ const tools = getCurrentTools(messages);
+ if (timestamp === void 0 && tools.length === 0)
+ return void 0;
+ return {
+ role: "system",
+ content: content.join("\n\n"),
+ ...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {},
+ ...tools.length > 0 ? { toolsAdded: tools } : {},
+ timestamp: timestamp ?? 0
+ };
+}
+function collapseSystemMessages(context) {
+ const head = getCurrentSystemMessage(context.messages);
+ const messages = context.messages.filter((message) => message.role !== "system");
+ return { messages: head ? [head, ...messages] : messages };
+}
+function resolveTranscript(context, supportsMidConvoSystemMessages) {
+ return supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);
+}
+function toToolDeclaration(tool) {
+ return {
+ name: tool.name,
+ description: tool.description,
+ parameters: JSON.parse(JSON.stringify(tool.parameters)),
+ ...tool.constrainedSampling === void 0 ? {} : { constrainedSampling: tool.constrainedSampling }
+ };
+}
+function declarationsEqual(left, right) {
+ return JSON.stringify(toToolDeclaration(left)) === JSON.stringify(toToolDeclaration(right));
+}
+function getDeclaredTools(messages) {
+ const definitions = /* @__PURE__ */ new Map();
+ for (const message of messages) {
+ if (!isSystemMessage(message))
+ continue;
+ for (const tool of message.toolsAdded ?? [])
+ definitions.set(tool.name, tool);
+ }
+ return [...definitions.values()];
+}
+function hasNonAdditiveToolChanges(messages) {
+ const declared = /* @__PURE__ */ new Set();
+ for (const message of messages) {
+ if (!isSystemMessage(message))
+ continue;
+ if ((message.toolsRemoved?.length ?? 0) > 0)
+ return true;
+ for (const tool of message.toolsAdded ?? []) {
+ if (declared.has(tool.name))
+ return true;
+ declared.add(tool.name);
+ }
+ }
+ return false;
+}
+function resolveTranscriptTools(messages, supportsToolAdditions) {
+ const anchorsAdditions = supportsToolAdditions && !hasNonAdditiveToolChanges(messages);
+ return {
+ requestTools: anchorsAdditions ? getInitialSystemMessage(messages)?.toolsAdded ?? [] : getCurrentTools(messages),
+ anchorsAdditions
+ };
+}
+var init_transcript = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/transcript.js"() {
+ init_text();
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/models.js
+function hasKnownModelType(model) {
+ return Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model));
+}
+function withKnownModelTypes(entry) {
+ return { ...entry, models: entry.models.filter(hasKnownModelType) };
+}
+function mergeHeaders(base, override) {
+ if (!base && !override)
+ return void 0;
+ const merged = { ...base };
+ for (const [name, value] of Object.entries(override ?? {})) {
+ const lowerName = name.toLowerCase();
+ for (const existingName of Object.keys(merged)) {
+ if (existingName.toLowerCase() === lowerName)
+ delete merged[existingName];
+ }
+ merged[name] = value;
+ }
+ return merged;
+}
+function createModels(options) {
+ return new ModelsImpl(options);
+}
+function createProvider(input) {
+ const single = input.api && typeof input.api.stream === "function" ? input.api : void 0;
+ const byApi = single || !input.api ? void 0 : input.api;
+ const images = input.images;
+ const classifiers = input.classifiers;
+ const streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== void 0);
+ const imageImplementations = Object.values(images ?? {}).filter((entry) => entry !== void 0);
+ const classifierImplementations = Object.values(classifiers ?? {}).filter((entry) => entry !== void 0);
+ if (streams.length === 0 && imageImplementations.length === 0 && classifierImplementations.length === 0) {
+ throw new Error(`Provider ${input.id}: at least one of "api", "images", or "classifiers" is required.`);
+ }
+ const baselineModels = input.models;
+ let dynamicModels = [];
+ const fetchModels = input.fetchModels;
+ const currentModels = () => {
+ const merged = [...baselineModels];
+ for (const model of dynamicModels) {
+ const index3 = merged.findIndex((entry) => getModelType(entry) === getModelType(model) && entry.id === model.id);
+ if (index3 >= 0)
+ merged[index3] = model;
+ else
+ merged.push(model);
+ }
+ return merged;
+ };
+ const apiFor = (model) => single ?? byApi?.[model.api];
+ const dispatch = (model, run2) => {
+ const streams2 = apiFor(model);
+ if (!streams2) {
+ return lazyStream(model, async () => {
+ throw new ModelsError("stream", `Provider ${input.id} has no API implementation for "${model.api}"`);
+ });
+ }
+ return run2(streams2);
+ };
+ const provider = {
+ id: input.id,
+ name: input.name ?? input.id,
+ baseUrl: input.baseUrl,
+ headers: input.headers,
+ auth: input.auth,
+ getModels: () => currentModels().filter((model) => isModelType(model, "chat")),
+ getAllModels: currentModels,
+ refreshModels: fetchModels ? async (context) => {
+ if (context.stored) {
+ const restored = context.stored.models.filter((model) => model.provider === input.id).map((model) => model);
+ if (!await context.publish({
+ update: () => {
+ dynamicModels = restored;
+ }
+ })) {
+ return;
+ }
+ }
+ if (!context.allowNetwork || context.signal.aborted)
+ return;
+ const fetched = await fetchModels(context);
+ if (context.signal.aborted)
+ return;
+ const refreshed = fetched.filter(hasKnownModelType);
+ await context.publish({
+ persist: { models: refreshed, checkedAt: Date.now() },
+ update: () => {
+ dynamicModels = refreshed;
+ }
+ });
+ } : void 0,
+ filterModels: input.filterModels,
+ filterAllModels: input.filterAllModels,
+ stream: (model, context, options) => dispatch(model, (streams2) => streams2.stream(model, context, options)),
+ streamSimple: (model, context, options) => dispatch(model, (streams2) => streams2.streamSimple(model, context, options))
+ };
+ if (streams.some((entry) => entry.fetchDeferred !== void 0)) {
+ provider.fetchDeferred = (model, handle, options) => lazyStream(model, async () => {
+ const implementation = apiFor(model);
+ if (!implementation?.fetchDeferred) {
+ throw new ModelsError("provider", `Provider ${input.id} does not support deferred responses for "${model.api}"`);
+ }
+ return implementation.fetchDeferred(model, handle, options);
+ });
+ }
+ if (streams.some((entry) => entry.cancelDeferred !== void 0)) {
+ provider.cancelDeferred = async (model, handle, options) => {
+ const implementation = apiFor(model);
+ if (!implementation?.cancelDeferred) {
+ throw new ModelsError("provider", `Provider ${input.id} cannot cancel deferred responses for "${model.api}"`);
+ }
+ await implementation.cancelDeferred(model, handle, options);
+ };
+ }
+ if (images && imageImplementations.length > 0) {
+ provider.generateImages = async (model, context, options) => {
+ const implementation = images[model.api];
+ if (!implementation) {
+ return imageErrorResult(model, new ModelsError("provider", `Provider ${input.id} has no image generation implementation for "${model.api}"`));
+ }
+ return implementation.generateImages(model, context, options);
+ };
+ }
+ if (classifiers && classifierImplementations.length > 0) {
+ provider.classify = async (model, context, options) => {
+ const implementation = classifiers[model.api];
+ if (!implementation) {
+ return classifierErrorResult(model, new ModelsError("provider", `Provider ${input.id} has no classifier implementation for "${model.api}"`));
+ }
+ return implementation.classify(model, context, options);
+ };
+ }
+ return provider;
+}
+function calculateCost(model, usage) {
+ const inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;
+ let rates = model.cost;
+ let matchedThreshold = -1;
+ for (const tier of model.cost.tiers ?? []) {
+ if (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {
+ rates = tier;
+ matchedThreshold = tier.inputTokensAbove;
+ }
+ }
+ const longWrite = usage.cacheWrite1h ?? 0;
+ const shortWrite = usage.cacheWrite - longWrite;
+ usage.cost.input = rates.input / 1e6 * usage.input;
+ usage.cost.output = rates.output / 1e6 * usage.output;
+ usage.cost.cacheRead = rates.cacheRead / 1e6 * usage.cacheRead;
+ usage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1e6;
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
+ return usage.cost;
+}
+function getSupportedThinkingLevels(model) {
+ if (!model.reasoning)
+ return ["off"];
+ return EXTENDED_THINKING_LEVELS.filter((level) => {
+ const mapped = model.thinkingLevelMap?.[level];
+ if (mapped === null)
+ return false;
+ if (level === "xhigh" || level === "max")
+ return mapped !== void 0;
+ return true;
+ });
+}
+function clampThinkingLevel(model, level) {
+ const availableLevels = getSupportedThinkingLevels(model);
+ if (availableLevels.includes(level))
+ return level;
+ const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);
+ if (requestedIndex === -1)
+ return availableLevels[0] ?? "off";
+ for (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {
+ const candidate = EXTENDED_THINKING_LEVELS[i];
+ if (availableLevels.includes(candidate))
+ return candidate;
+ }
+ for (let i = requestedIndex - 1; i >= 0; i--) {
+ const candidate = EXTENDED_THINKING_LEVELS[i];
+ if (availableLevels.includes(candidate))
+ return candidate;
+ }
+ return availableLevels[0] ?? "off";
+}
+var KNOWN_MODEL_TYPES, ModelsImpl, EXTENDED_THINKING_LEVELS;
+var init_models = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/models.js"() {
+ init_lazy();
+ init_context();
+ init_credential_store();
+ init_resolve();
+ init_models_store();
+ init_abort();
+ init_model_operations();
+ init_transcript();
+ KNOWN_MODEL_TYPES = { chat: true, image: true, classifier: true };
+ ModelsImpl = class {
+ providers = /* @__PURE__ */ new Map();
+ credentials;
+ modelsStore;
+ authContext;
+ refreshGenerations = /* @__PURE__ */ new Map();
+ refreshControllers = /* @__PURE__ */ new Map();
+ publicationChains = /* @__PURE__ */ new Map();
+ constructor(options) {
+ this.credentials = options?.credentials ?? new InMemoryCredentialStore();
+ this.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();
+ this.authContext = options?.authContext ?? defaultProviderAuthContext();
+ }
+ setProvider(provider) {
+ this.supersedeProviderRefresh(provider.id);
+ this.providers.set(provider.id, provider);
+ }
+ deleteProvider(id) {
+ this.supersedeProviderRefresh(id);
+ this.providers.delete(id);
+ }
+ clearProviders() {
+ for (const id of /* @__PURE__ */ new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) {
+ this.supersedeProviderRefresh(id);
+ }
+ this.providers.clear();
+ }
+ getProviders() {
+ return Array.from(this.providers.values());
+ }
+ getProvider(id) {
+ return this.providers.get(id);
+ }
+ getModels(provider) {
+ if (provider !== void 0) {
+ const entry = this.providers.get(provider);
+ if (!entry)
+ return [];
+ try {
+ return entry.getModels();
+ } catch {
+ return [];
+ }
+ }
+ const models = [];
+ for (const entry of this.providers.values()) {
+ try {
+ models.push(...entry.getModels());
+ } catch {
+ }
+ }
+ return models;
+ }
+ getAllModels(provider) {
+ if (provider !== void 0) {
+ const entry = this.providers.get(provider);
+ if (!entry)
+ return [];
+ try {
+ return entry.getAllModels?.() ?? entry.getModels();
+ } catch {
+ return [];
+ }
+ }
+ const models = [];
+ for (const entry of this.providers.values()) {
+ try {
+ models.push(...entry.getAllModels?.() ?? entry.getModels());
+ } catch {
+ }
+ }
+ return models;
+ }
+ getModelsOfType(type, provider) {
+ return this.getAllModels(provider).filter((model) => isModelType(model, type));
+ }
+ getModel(provider, id) {
+ return this.getModels(provider).find((model) => model.id === id);
+ }
+ getModelOfType(type, provider, id) {
+ return this.getModelsOfType(type, provider).find((model) => model.id === id);
+ }
+ supersedeProviderRefresh(providerId) {
+ const generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;
+ this.refreshGenerations.set(providerId, generation);
+ const previous = this.refreshControllers.get(providerId);
+ if (previous) {
+ this.refreshControllers.delete(providerId);
+ previous.abort();
+ }
+ return generation;
+ }
+ beginProviderRefresh(providerId) {
+ const generation = this.supersedeProviderRefresh(providerId);
+ const controller = new AbortController();
+ this.refreshControllers.set(providerId, controller);
+ return { generation, controller };
+ }
+ publishProviderModels(providerId, generation, signal, publication) {
+ const previous = this.publicationChains.get(providerId) ?? Promise.resolve();
+ const queued2 = (async () => {
+ await previous.catch(() => {
+ });
+ if (signal.aborted || this.refreshGenerations.get(providerId) !== generation)
+ return false;
+ if (publication.persist === null) {
+ await this.modelsStore.delete(providerId, { signal });
+ } else if (publication.persist !== void 0) {
+ await this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });
+ }
+ if (signal.aborted || this.refreshGenerations.get(providerId) !== generation)
+ return false;
+ publication.update?.();
+ return true;
+ })();
+ const tail = queued2.catch(() => {
+ });
+ this.publicationChains.set(providerId, tail);
+ void tail.then(() => {
+ if (this.publicationChains.get(providerId) === tail)
+ this.publicationChains.delete(providerId);
+ });
+ return raceWithAbortSignal(queued2, signal);
+ }
+ async runProviderRefreshPhase(provider, credential, allowNetwork, force, generation, signal) {
+ const stored = await this.modelsStore.read(provider.id, { signal });
+ await provider.refreshModels({
+ credential,
+ stored: stored ? withKnownModelTypes(structuredClone(stored)) : void 0,
+ publish: (publication) => this.publishProviderModels(provider.id, generation, signal, publication),
+ allowNetwork,
+ force: allowNetwork ? force : void 0,
+ signal
+ });
+ }
+ async refresh(options = {}) {
+ const allowNetwork = options.allowNetwork ?? true;
+ const callerSignal = operationSignal(options.signal);
+ const errors = /* @__PURE__ */ new Map();
+ if (callerSignal.aborted)
+ return { aborted: true, errors };
+ const selected = options.providers ? new Set(options.providers) : void 0;
+ const refreshable = Array.from(this.providers.values()).filter((provider) => provider.refreshModels !== void 0 && (!selected || selected.has(provider.id)));
+ const refresh = Promise.all(refreshable.map(async (provider) => {
+ const { generation, controller } = this.beginProviderRefresh(provider.id);
+ const signal = AbortSignal.any([callerSignal, controller.signal]);
+ const operation = (async () => {
+ let storedCredential;
+ let credentialError;
+ try {
+ storedCredential = await this.readCredential(provider.id, signal);
+ } catch (error) {
+ credentialError = error;
+ }
+ await this.runProviderRefreshPhase(provider, storedCredential, false, void 0, generation, signal);
+ if (credentialError !== void 0)
+ throw credentialError;
+ if (!allowNetwork || signal.aborted)
+ return;
+ const credential = await this.resolveRefreshCredential(provider, storedCredential, signal);
+ if (!credential)
+ return;
+ await this.runProviderRefreshPhase(provider, credential, true, options.force, generation, signal);
+ })();
+ try {
+ await raceWithAbortSignal(operation, signal);
+ } catch (error) {
+ if (!signal.aborted) {
+ errors.set(provider.id, error instanceof Error ? error : new ModelsError("model_source", `Model refresh failed for ${provider.id}`, { cause: error }));
+ }
+ } finally {
+ if (this.refreshControllers.get(provider.id) === controller) {
+ this.refreshControllers.delete(provider.id);
+ }
+ }
+ }));
+ try {
+ await raceWithAbortSignal(refresh, callerSignal);
+ } catch (error) {
+ if (!callerSignal.aborted)
+ throw error;
+ }
+ return { aborted: callerSignal.aborted, errors: new Map(errors) };
+ }
+ async resolveRefreshCredential(provider, stored, signal) {
+ if (stored?.type === "oauth") {
+ const oauth = provider.auth.oauth;
+ if (!oauth)
+ return void 0;
+ if (Date.now() < stored.expires)
+ return stored;
+ if (signal.aborted)
+ return void 0;
+ return refreshStoredOAuthCredential(this.credentials, provider.id, oauth, (current) => Date.now() >= current.expires, signal);
+ }
+ const apiKey = provider.auth.apiKey;
+ if (!apiKey)
+ return void 0;
+ const credential = stored?.type === "api_key" ? stored : void 0;
+ const result = await apiKey.resolve({ ctx: this.authContext, credential, signal });
+ if (!result)
+ return void 0;
+ return { type: "api_key", key: result.auth.apiKey, env: result.env };
+ }
+ async readCredential(providerId, signal) {
+ try {
+ return await this.credentials.read(providerId, { signal });
+ } catch (error) {
+ throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
+ }
+ }
+ async checkProviderAuth(provider, credential, signal) {
+ if (credential?.type === "oauth") {
+ return provider.auth.oauth ? { source: "OAuth", type: "oauth" } : void 0;
+ }
+ const apiKey = provider.auth.apiKey;
+ if (!apiKey)
+ return void 0;
+ if (apiKey.check) {
+ try {
+ return await apiKey.check({
+ ctx: this.authContext,
+ credential: credential?.type === "api_key" ? credential : void 0,
+ signal
+ });
+ } catch (error) {
+ throw new ModelsError("auth", `API key auth check failed for provider ${provider.id}`, { cause: error });
+ }
+ }
+ const resolution = await resolveProviderAuth(provider, this.credentials, this.authContext, { signal });
+ return resolution ? { source: resolution.source, type: "api_key" } : void 0;
+ }
+ checkAuth(providerId, options) {
+ const signal = operationSignal(options?.signal);
+ const check = (async () => {
+ signal.throwIfAborted();
+ const provider = this.providers.get(providerId);
+ if (!provider)
+ return void 0;
+ return this.checkProviderAuth(provider, await this.readCredential(providerId, signal), signal);
+ })();
+ return raceWithAbortSignal(check, signal);
+ }
+ async getAuthenticatedProviders(providerId, signal) {
+ signal.throwIfAborted();
+ const providers = providerId ? [this.providers.get(providerId)].filter((entry) => entry !== void 0) : this.getProviders();
+ const checks = await Promise.all(providers.map(async (provider) => {
+ const credential = await this.readCredential(provider.id, signal);
+ return { provider, credential, auth: await this.checkProviderAuth(provider, credential, signal) };
+ }));
+ return checks.filter((entry) => entry.auth !== void 0);
+ }
+ getAvailable(providerId, options) {
+ const signal = operationSignal(options?.signal);
+ const available = (async () => {
+ const providers = await this.getAuthenticatedProviders(providerId, signal);
+ return providers.flatMap(({ provider, credential }) => {
+ const models = provider.getModels();
+ return provider.filterModels?.(models, credential) ?? models;
+ });
+ })();
+ return raceWithAbortSignal(available, signal);
+ }
+ async getAvailableOfType(type, providerId, options) {
+ return (await this.getAllAvailable(providerId, options)).filter((model) => isModelType(model, type));
+ }
+ getAllAvailable(providerId, options) {
+ const signal = operationSignal(options?.signal);
+ const available = (async () => {
+ const providers = await this.getAuthenticatedProviders(providerId, signal);
+ return providers.flatMap(({ provider, credential }) => {
+ const models = provider.getAllModels?.() ?? provider.getModels();
+ if (provider.filterAllModels)
+ return provider.filterAllModels(models, credential);
+ if (!provider.filterModels)
+ return models;
+ const availableChatIds = new Set(provider.filterModels(provider.getModels(), credential).map((model) => model.id));
+ return models.filter((model) => !isModelType(model, "chat") || availableChatIds.has(model.id));
+ });
+ })();
+ return raceWithAbortSignal(available, signal);
+ }
+ async getAuth(providerOrModel, overrides) {
+ const signal = operationSignal(overrides?.signal);
+ const providerId = typeof providerOrModel === "string" ? providerOrModel : providerOrModel.provider;
+ const provider = this.providers.get(providerId);
+ if (!provider)
+ return void 0;
+ const result = await resolveProviderAuth(provider, this.credentials, this.authContext, { ...overrides, signal });
+ if (!result || typeof providerOrModel === "string" || !providerOrModel.headers)
+ return result;
+ return {
+ ...result,
+ auth: {
+ ...result.auth,
+ headers: mergeHeaders(result.auth.headers, providerOrModel.headers)
+ }
+ };
+ }
+ async login(providerId, type, interaction, options) {
+ const signal = operationSignal(interaction.signal);
+ signal.throwIfAborted();
+ const provider = this.providers.get(providerId);
+ if (!provider)
+ throw new ModelsError("provider", `Unknown provider: ${providerId}`);
+ const method = type === "oauth" ? provider.auth.oauth : provider.auth.apiKey;
+ if (!method?.login) {
+ throw new ModelsError("auth", `${provider.name} does not support ${type} login`);
+ }
+ const loginOperation = method.login({ ...interaction, signal }, options);
+ const credential = await raceWithAbortSignal(loginOperation, signal);
+ let mutationStarted = false;
+ let markMutationStarted;
+ const started = new Promise((resolve3) => {
+ markMutationStarted = resolve3;
+ });
+ const mutation = this.credentials.modify(providerId, async () => {
+ mutationStarted = true;
+ markMutationStarted?.();
+ return credential;
+ }, { signal });
+ void mutation.catch(() => {
+ });
+ try {
+ await new Promise((resolve3, reject) => {
+ const onAbort = () => {
+ if (!mutationStarted)
+ reject(signal.reason);
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ void Promise.race([started, mutation]).then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve3();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ if (signal.aborted)
+ onAbort();
+ });
+ await mutation;
+ } catch (error) {
+ signal.throwIfAborted();
+ throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
+ }
+ return credential;
+ }
+ async logout(providerId, options) {
+ const signal = operationSignal(options?.signal);
+ signal.throwIfAborted();
+ try {
+ await this.credentials.delete(providerId, { signal });
+ } catch (error) {
+ signal.throwIfAborted();
+ throw new ModelsError("auth", `Credential store delete failed for ${providerId}`, { cause: error });
+ }
+ }
+ requireProvider(model) {
+ const provider = this.providers.get(model.provider);
+ if (!provider) {
+ throw new ModelsError("provider", `Unknown provider: ${model.provider}`);
+ }
+ return provider;
+ }
+ requireChatProvider(model) {
+ assertChatModel(model);
+ return this.requireProvider(model);
+ }
+ async applyAuth(model, options) {
+ this.requireProvider(model);
+ const resolution = await this.getAuth(model, {
+ apiKey: options?.apiKey,
+ env: options?.env,
+ signal: options?.signal
+ });
+ if (!resolution) {
+ throw new ModelsError("auth", `Provider is not configured: ${model.provider}`);
+ }
+ const auth = resolution.auth;
+ const apiKey = options?.apiKey ?? auth.apiKey;
+ let headers = mergeHeaders(auth.headers, options?.headers);
+ if (options?.transformHeaders)
+ headers = await options.transformHeaders(headers ?? {});
+ const env = resolution.env || options?.env ? { ...resolution.env ?? {}, ...options?.env ?? {} } : void 0;
+ const requestModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;
+ const { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};
+ const requestOptions = { ...providerOptions, apiKey, headers, env };
+ return { requestModel, requestOptions };
+ }
+ stream(model, context, options) {
+ const transcript = normalizeContext(context);
+ return lazyStream(model, async () => {
+ const provider = this.requireChatProvider(model);
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
+ return provider.stream(requestModel, transcript, requestOptions);
+ });
+ }
+ async complete(model, context, options) {
+ return this.stream(model, context, options).result();
+ }
+ streamSimple(model, context, options) {
+ const transcript = normalizeContext(context);
+ return lazyStream(model, async () => {
+ const provider = this.requireChatProvider(model);
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
+ return provider.streamSimple(requestModel, transcript, requestOptions);
+ });
+ }
+ async completeSimple(model, context, options) {
+ return this.streamSimple(model, context, options).result();
+ }
+ streamDeferred(model, handle, options) {
+ return lazyStream(model, async () => {
+ const provider = this.requireChatProvider(model);
+ if (!provider.fetchDeferred) {
+ throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
+ }
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
+ return provider.fetchDeferred(requestModel, handle, requestOptions);
+ });
+ }
+ async fetchDeferred(model, handle, options) {
+ return this.streamDeferred(model, handle, options).result();
+ }
+ async cancelDeferred(model, handle, options) {
+ const provider = this.requireChatProvider(model);
+ if (!provider.cancelDeferred) {
+ throw new ModelsError("provider", `Provider ${model.provider} does not support deferred responses`);
+ }
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
+ await provider.cancelDeferred(requestModel, handle, requestOptions);
+ }
+ async generateImages(model, context, options) {
+ try {
+ assertImageModel(model);
+ const provider = this.requireProvider(model);
+ if (!provider.generateImages) {
+ throw new ModelsError("provider", `Provider ${model.provider} does not support image generation`);
+ }
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
+ return await provider.generateImages(requestModel, context, requestOptions);
+ } catch (error) {
+ return imageErrorResult(model, error, options?.signal?.aborted);
+ }
+ }
+ async classify(model, context, options) {
+ try {
+ assertClassifierModel(model);
+ const provider = this.requireProvider(model);
+ if (!provider.classify) {
+ throw new ModelsError("provider", `Provider ${model.provider} does not support classification`);
+ }
+ const { requestModel, requestOptions } = await this.applyAuth(model, options);
+ return await provider.classify(requestModel, context, requestOptions);
+ } catch (error) {
+ return classifierErrorResult(model, error, options?.signal?.aborted);
+ }
+ }
+ };
+ EXTENDED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
+ }
+});
+
+// node_modules/openai/internal/tslib.mjs
+function __classPrivateFieldSet(receiver, state3, value, kind, f) {
+ if (kind === "m")
+ throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f)
+ throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state3 === "function" ? receiver !== state3 || !f : !state3.has(receiver))
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state3.set(receiver, value), value;
+}
+function __classPrivateFieldGet(receiver, state3, kind, f) {
+ if (kind === "a" && !f)
+ throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state3 === "function" ? receiver !== state3 || !f : !state3.has(receiver))
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state3.get(receiver);
+}
+var init_tslib = __esm({
+ "node_modules/openai/internal/tslib.mjs"() {
+ }
+});
+
+// node_modules/openai/internal/utils/uuid.mjs
+var uuid4;
+var init_uuid = __esm({
+ "node_modules/openai/internal/utils/uuid.mjs"() {
+ uuid4 = function() {
+ const { crypto: crypto2 } = globalThis;
+ if (crypto2?.randomUUID) {
+ uuid4 = crypto2.randomUUID.bind(crypto2);
+ return crypto2.randomUUID();
+ }
+ const u8 = new Uint8Array(1);
+ const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
+ return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
+ };
+ }
+});
+
+// node_modules/openai/internal/errors.mjs
+function isAbortError(err2) {
+ return typeof err2 === "object" && err2 !== null && // Spec-compliant fetch implementations
+ ("name" in err2 && err2.name === "AbortError" || // Expo fetch
+ "message" in err2 && String(err2.message).includes("FetchRequestCanceledException"));
+}
+var castToError;
+var init_errors = __esm({
+ "node_modules/openai/internal/errors.mjs"() {
+ castToError = (err2) => {
+ if (err2 instanceof Error)
+ return err2;
+ if (typeof err2 === "object" && err2 !== null) {
+ try {
+ if (Object.prototype.toString.call(err2) === "[object Error]") {
+ const hasCause = "cause" in err2;
+ const error = new Error(err2.message, hasCause ? { cause: err2.cause } : {});
+ if (err2.stack)
+ error.stack = err2.stack;
+ if (hasCause && !Object.prototype.hasOwnProperty.call(error, "cause"))
+ error.cause = err2.cause;
+ if (err2.name)
+ error.name = err2.name;
+ return error;
+ }
+ } catch {
+ }
+ try {
+ return new Error(JSON.stringify(err2));
+ } catch {
+ }
+ }
+ return new Error(err2);
+ };
+ }
+});
+
+// node_modules/openai/core/error.mjs
+var OpenAIError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, LengthFinishReasonError, ContentFilterFinishReasonError, InvalidWebhookSignatureError, OAuthError, SubjectTokenProviderError;
+var init_error = __esm({
+ "node_modules/openai/core/error.mjs"() {
+ init_errors();
+ OpenAIError = class extends Error {
+ };
+ APIError = class _APIError extends OpenAIError {
+ constructor(status, error, message, headers) {
+ super(`${_APIError.makeMessage(status, error, message)}`);
+ this.status = status;
+ this.headers = headers;
+ this.requestID = headers?.get("x-request-id");
+ this.error = error;
+ const data = error;
+ this.code = data?.["code"];
+ this.param = data?.["param"];
+ this.type = data?.["type"];
+ }
+ static makeMessage(status, error, message) {
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
+ if (status && msg) {
+ return `${status} ${msg}`;
+ }
+ if (status) {
+ return `${status} status code (no body)`;
+ }
+ if (msg) {
+ return msg;
+ }
+ return "(no status code or body)";
+ }
+ static generate(status, errorResponse, message, headers) {
+ if (!status || !headers) {
+ return new APIConnectionError({ message, cause: castToError(errorResponse) });
+ }
+ const error = errorResponse?.["error"];
+ if (status === 400) {
+ return new BadRequestError(status, error, message, headers);
+ }
+ if (status === 401) {
+ return new AuthenticationError(status, error, message, headers);
+ }
+ if (status === 403) {
+ return new PermissionDeniedError(status, error, message, headers);
+ }
+ if (status === 404) {
+ return new NotFoundError(status, error, message, headers);
+ }
+ if (status === 409) {
+ return new ConflictError(status, error, message, headers);
+ }
+ if (status === 422) {
+ return new UnprocessableEntityError(status, error, message, headers);
+ }
+ if (status === 429) {
+ return new RateLimitError(status, error, message, headers);
+ }
+ if (status >= 500) {
+ return new InternalServerError(status, error, message, headers);
+ }
+ return new _APIError(status, error, message, headers);
+ }
+ };
+ APIUserAbortError = class extends APIError {
+ constructor({ message } = {}) {
+ super(void 0, void 0, message || "Request was aborted.", void 0);
+ }
+ };
+ APIConnectionError = class extends APIError {
+ constructor({ message, cause }) {
+ super(void 0, void 0, message || "Connection error.", void 0);
+ if (cause)
+ this.cause = cause;
+ }
+ };
+ APIConnectionTimeoutError = class extends APIConnectionError {
+ constructor({ message } = {}) {
+ super({ message: message ?? "Request timed out." });
+ }
+ };
+ BadRequestError = class extends APIError {
+ };
+ AuthenticationError = class extends APIError {
+ };
+ PermissionDeniedError = class extends APIError {
+ };
+ NotFoundError = class extends APIError {
+ };
+ ConflictError = class extends APIError {
+ };
+ UnprocessableEntityError = class extends APIError {
+ };
+ RateLimitError = class extends APIError {
+ };
+ InternalServerError = class extends APIError {
+ };
+ LengthFinishReasonError = class extends OpenAIError {
+ constructor() {
+ super(`Could not parse response content as the length limit was reached`);
+ }
+ };
+ ContentFilterFinishReasonError = class extends OpenAIError {
+ constructor() {
+ super(`Could not parse response content as the request was rejected by the content filter`);
+ }
+ };
+ InvalidWebhookSignatureError = class extends Error {
+ constructor(message) {
+ super(message);
+ }
+ };
+ OAuthError = class extends APIError {
+ constructor(status, error, headers) {
+ let finalMessage = "OAuth2 authentication error";
+ let error_code = void 0;
+ if (error && typeof error === "object") {
+ const errorData = error;
+ error_code = errorData["error"];
+ const description = errorData["error_description"];
+ if (description && typeof description === "string") {
+ finalMessage = description;
+ } else if (error_code) {
+ finalMessage = error_code;
+ }
+ }
+ super(status, error, finalMessage, headers);
+ this.error_code = error_code;
+ }
+ };
+ SubjectTokenProviderError = class extends OpenAIError {
+ constructor(message, provider, cause) {
+ super(message);
+ this.provider = provider;
+ this.cause = cause;
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/utils/values.mjs
+function maybeObj(x) {
+ if (typeof x !== "object") {
+ return {};
+ }
+ return x ?? {};
+}
+function isEmptyObj(obj) {
+ if (!obj)
+ return true;
+ for (const _k in obj)
+ return false;
+ return true;
+}
+function hasOwn(obj, key) {
+ return Object.prototype.hasOwnProperty.call(obj, key);
+}
+function isObj(obj) {
+ return obj != null && typeof obj === "object" && !Array.isArray(obj);
+}
+var startsWithSchemeRegexp, isAbsoluteURL, isArray, isReadonlyArray, validatePositiveInteger, safeJSON;
+var init_values = __esm({
+ "node_modules/openai/internal/utils/values.mjs"() {
+ init_error();
+ startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
+ isAbsoluteURL = (url) => {
+ return startsWithSchemeRegexp.test(url);
+ };
+ isArray = (val) => (isArray = Array.isArray, isArray(val));
+ isReadonlyArray = isArray;
+ validatePositiveInteger = (name, n) => {
+ if (typeof n !== "number" || !Number.isInteger(n)) {
+ throw new OpenAIError(`${name} must be an integer`);
+ }
+ if (n < 0) {
+ throw new OpenAIError(`${name} must be a positive integer`);
+ }
+ return n;
+ };
+ safeJSON = (text) => {
+ try {
+ return JSON.parse(text);
+ } catch (err2) {
+ return void 0;
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/utils/sleep.mjs
+var sleep;
+var init_sleep = __esm({
+ "node_modules/openai/internal/utils/sleep.mjs"() {
+ sleep = (ms, ...signals) => new Promise((resolve3, reject) => {
+ const activeSignals = [...new Set(signals.filter((signal) => signal != null))];
+ let timeout;
+ let settled = false;
+ const cleanup = () => {
+ for (const signal of activeSignals) {
+ try {
+ signal.removeEventListener("abort", abort);
+ } catch {
+ }
+ }
+ };
+ const settle2 = (callback) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ if (timeout !== void 0) {
+ clearTimeout(timeout);
+ timeout = void 0;
+ }
+ cleanup();
+ callback();
+ };
+ const abort = () => {
+ settle2(() => reject());
+ };
+ if (activeSignals.some((signal) => signal.aborted)) {
+ abort();
+ return;
+ }
+ timeout = setTimeout(() => {
+ settle2(resolve3);
+ }, ms);
+ for (const signal of activeSignals) {
+ if (settled) {
+ break;
+ }
+ try {
+ signal.addEventListener("abort", abort, { once: true });
+ } catch (error) {
+ settle2(() => reject(error));
+ }
+ }
+ if (activeSignals.some((signal) => signal.aborted)) {
+ abort();
+ }
+ });
+ }
+});
+
+// node_modules/openai/internal/utils/abort.mjs
+function subscribeWeakly(signal, reference, registry) {
+ let subscription = subscriptions.get(signal);
+ if (!subscription) {
+ const callbacks = /* @__PURE__ */ new Set();
+ const abort = () => {
+ subscriptions.delete(signal);
+ for (const callback of callbacks) {
+ registry.unregister(callback);
+ callback.deref()?.();
+ }
+ callbacks.clear();
+ };
+ subscription = { callbacks, abort };
+ signal.addEventListener("abort", abort, { once: true });
+ subscriptions.set(signal, subscription);
+ }
+ const owner = subscription;
+ owner.callbacks.add(reference);
+ return () => {
+ owner.callbacks.delete(reference);
+ registry.unregister(reference);
+ if (owner.callbacks.size === 0) {
+ if (subscriptions.get(signal) === owner) {
+ subscriptions.delete(signal);
+ }
+ signal.removeEventListener("abort", owner.abort);
+ }
+ };
+}
+function releaseOnAbort(signal, callbacks, abort) {
+ signal.addEventListener("abort", () => callbacks.deref()?.delete(abort), { once: true });
+}
+function retainRequestAbortCallback(owner, abort, requestSignal) {
+ if (typeof weakGlobals.WeakRef === "function" && finalizer && !requestSignal.aborted) {
+ let callbacks = callbackOwners.get(owner);
+ if (!callbacks) {
+ callbacks = /* @__PURE__ */ new Set();
+ callbackOwners.set(owner, callbacks);
+ }
+ callbacks.add(abort);
+ releaseOnAbort(requestSignal, new weakGlobals.WeakRef(callbacks), abort);
+ }
+}
+function addRequestAbortListener(signal, abort, requestSignal) {
+ if (signal.aborted) {
+ abort();
+ return () => {
+ };
+ }
+ if (typeof weakGlobals.WeakRef !== "function" || !finalizer) {
+ signal.addEventListener("abort", abort, { once: true });
+ return () => signal.removeEventListener("abort", abort);
+ }
+ const reference = new weakGlobals.WeakRef(abort);
+ const cleanup = subscribeWeakly(signal, reference, finalizer);
+ finalizer.register(abort, cleanup, reference);
+ retainRequestAbortCallback(requestSignal, abort, requestSignal);
+ return cleanup;
+}
+var weakGlobals, finalizer, callbackOwners, subscriptions;
+var init_abort2 = __esm({
+ "node_modules/openai/internal/utils/abort.mjs"() {
+ weakGlobals = globalThis;
+ finalizer = // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Weak references and finalizers are optional host capabilities, so probe them before constructing either.
+ typeof weakGlobals.FinalizationRegistry === "function" ? new weakGlobals.FinalizationRegistry((cleanup) => {
+ try {
+ cleanup();
+ } catch {
+ }
+ }) : void 0;
+ callbackOwners = /* @__PURE__ */ new WeakMap();
+ subscriptions = /* @__PURE__ */ new WeakMap();
+ }
+});
+
+// node_modules/openai/internal/shims.mjs
+function getDefaultFetch() {
+ if (typeof fetch !== "undefined") {
+ return fetch;
+ }
+ throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
+}
+function makeReadableStream(...args) {
+ const ReadableStream2 = globalThis.ReadableStream;
+ if (typeof ReadableStream2 === "undefined") {
+ throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
+ }
+ return new ReadableStream2(...args);
+}
+function ReadableStreamFrom(iterable) {
+ let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
+ return makeReadableStream({
+ start() {
+ },
+ async pull(controller) {
+ const { done, value } = await iter.next();
+ if (done) {
+ controller.close();
+ } else {
+ controller.enqueue(value);
+ }
+ },
+ async cancel() {
+ await iter.return?.();
+ }
+ });
+}
+function ReadableStreamToAsyncIterable(stream3) {
+ if (stream3[Symbol.asyncIterator])
+ return stream3;
+ const reader = stream3.getReader();
+ return {
+ async next() {
+ try {
+ const result = await reader.read();
+ if (result?.done)
+ reader.releaseLock();
+ return result;
+ } catch (e) {
+ reader.releaseLock();
+ throw e;
+ }
+ },
+ async return() {
+ const cancelPromise = reader.cancel();
+ reader.releaseLock();
+ await cancelPromise;
+ return { done: true, value: void 0 };
+ },
+ [Symbol.asyncIterator]() {
+ return this;
+ }
+ };
+}
+async function CancelReadableStream(stream3) {
+ if (stream3 === null || typeof stream3 !== "object")
+ return;
+ if (stream3[Symbol.asyncIterator]) {
+ await stream3[Symbol.asyncIterator]().return?.();
+ return;
+ }
+ const reader = stream3.getReader();
+ const cancelPromise = reader.cancel();
+ reader.releaseLock();
+ await cancelPromise;
+}
+var init_shims = __esm({
+ "node_modules/openai/internal/shims.mjs"() {
+ }
+});
+
+// node_modules/openai/internal/utils/bytes.mjs
+function encodeUTF8(str) {
+ let encoder4;
+ return (encodeUTF8_ ?? (encoder4 = new globalThis.TextEncoder(), encodeUTF8_ = encoder4.encode.bind(encoder4)))(str);
+}
+function decodeUTF8(bytes) {
+ let decoder2;
+ return (decodeUTF8_ ?? (decoder2 = new globalThis.TextDecoder(), decodeUTF8_ = decoder2.decode.bind(decoder2)))(bytes);
+}
+var encodeUTF8_, decodeUTF8_;
+var init_bytes = __esm({
+ "node_modules/openai/internal/utils/bytes.mjs"() {
+ }
+});
+
+// node_modules/openai/internal/decoders/line.mjs
+function findNewlineIndex(buffer, start, end) {
+ const newline = 10;
+ const carriage = 13;
+ for (let i = start; i < end; i++) {
+ if (buffer[i] === newline) {
+ return { preceding: i, index: i + 1, carriage: false };
+ }
+ if (buffer[i] === carriage) {
+ return { preceding: i, index: i + 1, carriage: true };
+ }
+ }
+ return null;
+}
+function findDoubleNewlineIndex(buffer) {
+ for (let i = 0; i < buffer.length - 1; i++) {
+ const firstEndingLength = lineEndingLength(buffer, i);
+ if (firstEndingLength > 0) {
+ const secondEndingIndex = i + firstEndingLength;
+ const secondEndingLength = lineEndingLength(buffer, secondEndingIndex);
+ if (secondEndingLength > 0) {
+ return secondEndingIndex + secondEndingLength;
+ }
+ }
+ }
+ return -1;
+}
+function lineEndingLength(buffer, index3) {
+ const newline = 10;
+ const carriage = 13;
+ if (buffer[index3] === newline) {
+ return 1;
+ }
+ if (buffer[index3] === carriage) {
+ return buffer[index3 + 1] === newline ? 2 : 1;
+ }
+ return 0;
+}
+var _LineDecoder_instances, _LineDecoder_buffer, _LineDecoder_start, _LineDecoder_end, _LineDecoder_searchIndex, _LineDecoder_skipLeadingLF, _LineDecoder_append, MAX_RETAINED_BUFFER_BYTES, LineDecoder;
+var init_line = __esm({
+ "node_modules/openai/internal/decoders/line.mjs"() {
+ init_tslib();
+ init_bytes();
+ MAX_RETAINED_BUFFER_BYTES = 64 * 1024;
+ LineDecoder = class {
+ /** Creates a decoder with no buffered bytes or pending newline continuation. */
+ constructor() {
+ _LineDecoder_instances.add(this);
+ _LineDecoder_buffer.set(this, void 0);
+ _LineDecoder_start.set(this, void 0);
+ _LineDecoder_end.set(this, void 0);
+ _LineDecoder_searchIndex.set(this, void 0);
+ _LineDecoder_skipLeadingLF.set(this, void 0);
+ __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
+ __classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
+ __classPrivateFieldSet(this, _LineDecoder_end, 0, "f");
+ __classPrivateFieldSet(this, _LineDecoder_searchIndex, 0, "f");
+ __classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
+ }
+ /**
+ * Appends a text or UTF-8 byte chunk and returns every newly completed line.
+ *
+ * Incomplete lines remain buffered for the next call. A trailing `\r`
+ * completes its line immediately, and a following `\n` is consumed as its
+ * continuation. `null` and `undefined` are ignored and do not flush buffered
+ * content.
+ */
+ decode(chunk) {
+ if (chunk == null) {
+ return [];
+ }
+ let binaryChunk;
+ if (chunk instanceof ArrayBuffer) {
+ binaryChunk = new Uint8Array(chunk);
+ } else if (typeof chunk === "string") {
+ binaryChunk = encodeUTF8(chunk);
+ } else {
+ binaryChunk = chunk;
+ }
+ if (binaryChunk.length === 0) {
+ return [];
+ }
+ if (__classPrivateFieldGet(this, _LineDecoder_skipLeadingLF, "f")) {
+ __classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
+ if (binaryChunk[0] === 10) {
+ binaryChunk = binaryChunk.subarray(1);
+ }
+ if (binaryChunk.length === 0) {
+ return [];
+ }
+ }
+ __classPrivateFieldGet(this, _LineDecoder_instances, "m", _LineDecoder_append).call(this, binaryChunk);
+ const lines2 = [];
+ let patternIndex;
+ while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_searchIndex, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f"))) != null) {
+ const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), patternIndex.preceding));
+ lines2.push(line);
+ __classPrivateFieldSet(this, _LineDecoder_start, patternIndex.index, "f");
+ if (patternIndex.carriage) {
+ if (__classPrivateFieldGet(this, _LineDecoder_start, "f") < __classPrivateFieldGet(this, _LineDecoder_end, "f") && __classPrivateFieldGet(this, _LineDecoder_buffer, "f")[__classPrivateFieldGet(this, _LineDecoder_start, "f")] === 10) {
+ __classPrivateFieldSet(this, _LineDecoder_start, __classPrivateFieldGet(this, _LineDecoder_start, "f") + 1, "f");
+ } else if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) {
+ __classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, true, "f");
+ }
+ }
+ __classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_start, "f"), "f");
+ }
+ __classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_end, "f"), "f");
+ if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) {
+ __classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
+ __classPrivateFieldSet(this, _LineDecoder_end, 0, "f");
+ __classPrivateFieldSet(this, _LineDecoder_searchIndex, 0, "f");
+ if (__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > MAX_RETAINED_BUFFER_BYTES) {
+ __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
+ }
+ } else if (lines2.length > 0 && __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > MAX_RETAINED_BUFFER_BYTES) {
+ const length = __classPrivateFieldGet(this, _LineDecoder_end, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f");
+ if (length <= MAX_RETAINED_BUFFER_BYTES || __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > length * 4) {
+ const capacity = length <= MAX_RETAINED_BUFFER_BYTES ? Math.min(Math.max(length * 2, 256), MAX_RETAINED_BUFFER_BYTES) : length * 2;
+ const buffer = new Uint8Array(capacity);
+ buffer.set(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f")));
+ __classPrivateFieldSet(this, _LineDecoder_buffer, buffer, "f");
+ __classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
+ __classPrivateFieldSet(this, _LineDecoder_end, length, "f");
+ __classPrivateFieldSet(this, _LineDecoder_searchIndex, length, "f");
+ }
+ }
+ return lines2;
+ }
+ /** Emits the remaining unterminated line, or returns an empty array when idle. */
+ flush() {
+ __classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
+ if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) {
+ return [];
+ }
+ return this.decode("\n");
+ }
+ };
+ _LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_start = /* @__PURE__ */ new WeakMap(), _LineDecoder_end = /* @__PURE__ */ new WeakMap(), _LineDecoder_searchIndex = /* @__PURE__ */ new WeakMap(), _LineDecoder_skipLeadingLF = /* @__PURE__ */ new WeakMap(), _LineDecoder_instances = /* @__PURE__ */ new WeakSet(), _LineDecoder_append = function _LineDecoder_append2(chunk) {
+ if (__classPrivateFieldGet(this, _LineDecoder_end, "f") + chunk.length > __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
+ const length = __classPrivateFieldGet(this, _LineDecoder_end, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f");
+ if (__classPrivateFieldGet(this, _LineDecoder_start, "f") >= __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length / 2 && length + chunk.length <= __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
+ __classPrivateFieldGet(this, _LineDecoder_buffer, "f").copyWithin(0, __classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f"));
+ } else {
+ const capacity = Math.max(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length * 2, length + chunk.length, 256);
+ const buffer = new Uint8Array(capacity);
+ buffer.set(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f")));
+ __classPrivateFieldSet(this, _LineDecoder_buffer, buffer, "f");
+ }
+ __classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_searchIndex, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f"), "f");
+ __classPrivateFieldSet(this, _LineDecoder_end, length, "f");
+ __classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
+ }
+ __classPrivateFieldGet(this, _LineDecoder_buffer, "f").set(chunk, __classPrivateFieldGet(this, _LineDecoder_end, "f"));
+ __classPrivateFieldSet(this, _LineDecoder_end, __classPrivateFieldGet(this, _LineDecoder_end, "f") + chunk.length, "f");
+ };
+ LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
+ LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
+ }
+});
+
+// node_modules/openai/internal/utils/log.mjs
+function noop() {
+}
+function makeLogFn(fnLevel, logger, logLevel) {
+ if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
+ return noop;
+ } else {
+ return logger[fnLevel].bind(logger);
+ }
+}
+function loggerFor(client) {
+ const logger = client.logger;
+ const logLevel = client.logLevel ?? "off";
+ if (!logger) {
+ return noopLogger;
+ }
+ const cachedLogger = cachedLoggers.get(logger);
+ if (cachedLogger && cachedLogger[0] === logLevel) {
+ return cachedLogger[1];
+ }
+ const levelLogger = {
+ error: makeLogFn("error", logger, logLevel),
+ warn: makeLogFn("warn", logger, logLevel),
+ info: makeLogFn("info", logger, logLevel),
+ debug: makeLogFn("debug", logger, logLevel)
+ };
+ cachedLoggers.set(logger, [logLevel, levelLogger]);
+ return levelLogger;
+}
+function isSensitiveQueryParameter(name) {
+ const normalized = name.toLowerCase().replace(/[-_]/gu, "");
+ return sensitiveQueryNames.has(normalized) || sensitiveQueryNames.has(normalized.replace(/^x/u, ""));
+}
+function isSensitiveHeader(name) {
+ return sensitiveHeaderNames.has(name.toLowerCase().replace(/_/gu, "-")) || isSensitiveQueryParameter(name);
+}
+function redactURL(value) {
+ const url = new URL(value);
+ url.username = "";
+ url.password = "";
+ url.hash = "";
+ for (const name of url.searchParams.keys()) {
+ if (isSensitiveQueryParameter(name)) {
+ url.searchParams.set(name, "***");
+ }
+ }
+ return url.href;
+}
+var levelNumbers, parseLogLevel, noopLogger, cachedLoggers, sensitiveQueryNames, sensitiveHeaderNames, formatRequestDetails;
+var init_log = __esm({
+ "node_modules/openai/internal/utils/log.mjs"() {
+ init_values();
+ levelNumbers = {
+ off: 0,
+ error: 200,
+ warn: 300,
+ info: 400,
+ debug: 500
+ };
+ parseLogLevel = (maybeLevel, sourceName, client) => {
+ if (!maybeLevel) {
+ return void 0;
+ }
+ if (hasOwn(levelNumbers, maybeLevel)) {
+ return maybeLevel;
+ }
+ loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
+ return void 0;
+ };
+ noopLogger = {
+ error: noop,
+ warn: noop,
+ info: noop,
+ debug: noop
+ };
+ cachedLoggers = /* @__PURE__ */ new WeakMap();
+ sensitiveQueryNames = /* @__PURE__ */ new Set([
+ "apikey",
+ "accesstoken",
+ "refreshtoken",
+ "sessiontoken",
+ "sessionid",
+ "idtoken",
+ "authtoken",
+ "authorization",
+ "token",
+ "password",
+ "clientsecret",
+ "signingsecret",
+ "xamzsecuritytoken",
+ "xamzsignature",
+ "xamzcredential"
+ ]);
+ sensitiveHeaderNames = /* @__PURE__ */ new Set([
+ "authorization",
+ "proxy-authorization",
+ "api-key",
+ "x-api-key",
+ "x-amz-security-token",
+ "cookie",
+ "set-cookie",
+ "x-session-token",
+ "x-session-id",
+ "x-auth-token",
+ "x-id-token"
+ ]);
+ formatRequestDetails = (details) => {
+ if (details.options) {
+ details.options = { ...details.options };
+ delete details.options["headers"];
+ if (details.options.path) {
+ const path5 = details.options.path;
+ const redacted = new URL(redactURL(new URL(path5, "https://redacted.invalid").href));
+ details.options.path = redacted.origin === "https://redacted.invalid" ? `${path5.startsWith("/") ? "/" : ""}${redacted.pathname.slice(1)}${redacted.search}` : redacted.href;
+ }
+ if (details.options.query) {
+ details.options.query = Object.fromEntries(Object.entries(details.options.query).map(([name, value]) => [
+ name,
+ isSensitiveQueryParameter(name) ? "***" : value
+ ]));
+ }
+ }
+ if (details.url) {
+ details.url = redactURL(details.url);
+ }
+ if (details.headers) {
+ details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, isSensitiveHeader(name) ? "***" : value]));
+ }
+ if ("retryOfRequestLogID" in details) {
+ if (details.retryOfRequestLogID) {
+ details.retryOf = details.retryOfRequestLogID;
+ }
+ delete details.retryOfRequestLogID;
+ }
+ return details;
+ };
+ }
+});
+
+// node_modules/openai/core/streaming.mjs
+function isTransportAbortError(error) {
+ return !(error instanceof APIError) && isAbortError(error);
+}
+function createStreamTeeQueue() {
+ let entries = [];
+ let head = 0;
+ let canceled = false;
+ return {
+ get length() {
+ return entries.length - head;
+ },
+ get canceled() {
+ return canceled;
+ },
+ enqueue(value) {
+ if (!canceled) {
+ entries.push(value);
+ }
+ },
+ dequeue() {
+ if (head === entries.length) {
+ return void 0;
+ }
+ const value = entries[head];
+ entries[head] = void 0;
+ head += 1;
+ if (head === entries.length) {
+ entries = [];
+ head = 0;
+ } else if (head >= 1024 && head * 2 >= entries.length) {
+ entries = entries.slice(head);
+ head = 0;
+ }
+ return value;
+ },
+ cancel() {
+ canceled = true;
+ entries.length = 0;
+ head = 0;
+ }
+ };
+}
+function createAbortableSSESource(body, signal) {
+ const reader = typeof body.getReader === "function" ? body.getReader() : void 0;
+ const source = reader ? {
+ next: () => reader.read(),
+ return: () => reader.cancel()
+ } : ReadableStreamToAsyncIterable(body)[Symbol.asyncIterator]();
+ const ended = { value: void 0, done: true };
+ let closed = false;
+ let canceled = false;
+ let cancellation;
+ let interrupt;
+ const waitForAbort = () => (
+ // oxlint-disable-next-line promise/avoid-new -- AbortSignal callbacks need a portable Promise bridge.
+ new Promise((resolve3) => {
+ interrupt = resolve3;
+ })
+ );
+ const cancel = () => {
+ if (canceled || closed) {
+ return cancellation;
+ }
+ canceled = true;
+ try {
+ cancellation = Promise.resolve(source.return?.());
+ } catch (error) {
+ cancellation = Promise.reject(error);
+ }
+ cancellation.catch(() => void 0);
+ return cancellation;
+ };
+ const abort = () => {
+ queueMicrotask(() => {
+ interrupt?.();
+ cancel();
+ });
+ };
+ const iterator = {
+ async next() {
+ if (signal.aborted) {
+ return ended;
+ }
+ const aborted = waitForAbort().then(() => ended);
+ try {
+ const result = await Promise.race([source.next(), aborted]);
+ if (signal.aborted) {
+ return ended;
+ }
+ if (result.done) {
+ closed = true;
+ return ended;
+ }
+ return { value: result.value, done: false };
+ } catch (error) {
+ if (signal.aborted && (isAbortError(error) || error === signal.reason)) {
+ return ended;
+ }
+ throw error;
+ } finally {
+ interrupt = void 0;
+ }
+ },
+ async return() {
+ const pending = cancel();
+ if (pending && !signal.aborted) {
+ const aborted = waitForAbort();
+ try {
+ if (!signal.aborted) {
+ await Promise.race([pending, aborted]);
+ }
+ } finally {
+ interrupt = void 0;
+ }
+ }
+ return ended;
+ },
+ [Symbol.asyncIterator]() {
+ return this;
+ }
+ };
+ return {
+ iterator,
+ start() {
+ signal.addEventListener("abort", abort, { once: true });
+ if (signal.aborted) {
+ abort();
+ }
+ },
+ async cleanup(failed) {
+ let cleanupError;
+ try {
+ signal.removeEventListener("abort", abort);
+ } catch (error) {
+ cleanupError = error;
+ }
+ if (!closed) {
+ const pending = cancel();
+ if (pending && !failed && !signal.aborted) {
+ try {
+ await pending;
+ } catch (error) {
+ cleanupError ?? (cleanupError = error);
+ }
+ }
+ }
+ if (reader) {
+ try {
+ reader.releaseLock();
+ } catch (error) {
+ cleanupError ?? (cleanupError = error);
+ }
+ }
+ if (cleanupError !== void 0 && !failed && !signal.aborted) {
+ throw cleanupError;
+ }
+ }
+ };
+}
+async function* _iterSSEMessages(response, controller) {
+ if (!response.body) {
+ controller.abort();
+ if (globalThis.navigator !== void 0 && globalThis.navigator.product === "ReactNative") {
+ throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
+ }
+ throw new OpenAIError(`Attempted to iterate over a response with no body`);
+ }
+ const sseDecoder = new SSEDecoder();
+ const lineDecoder = new LineDecoder();
+ const { signal } = controller;
+ const source = createAbortableSSESource(response.body, signal);
+ let failed = false;
+ try {
+ source.start();
+ for await (const sseChunk of iterSSEChunks(source.iterator)) {
+ if (signal.aborted) {
+ return;
+ }
+ for (const line of lineDecoder.decode(sseChunk)) {
+ if (signal.aborted) {
+ return;
+ }
+ const sse = sseDecoder.decode(line);
+ if (sse) {
+ yield sse;
+ }
+ }
+ }
+ if (signal.aborted) {
+ return;
+ }
+ for (const line of lineDecoder.flush()) {
+ if (signal.aborted) {
+ return;
+ }
+ const sse = sseDecoder.decode(line);
+ if (sse) {
+ yield sse;
+ }
+ }
+ if (signal.aborted) {
+ return;
+ }
+ const pending = sseDecoder.flush();
+ if (pending) {
+ yield pending;
+ }
+ } catch (error) {
+ failed = true;
+ if (!signal.aborted || !isAbortError(error) && error !== signal.reason) {
+ throw error;
+ }
+ } finally {
+ await source.cleanup(failed);
+ }
+}
+async function* iterSSEChunks(iterator) {
+ let data = new Uint8Array();
+ let dataStart = 0;
+ let dataEnd = 0;
+ let searchStartIndex = 0;
+ for await (const chunk of iterator) {
+ if (chunk == null) {
+ continue;
+ }
+ let binaryChunk;
+ if (chunk instanceof ArrayBuffer) {
+ binaryChunk = new Uint8Array(chunk);
+ } else if (typeof chunk === "string") {
+ binaryChunk = encodeUTF8(chunk);
+ } else {
+ binaryChunk = chunk;
+ }
+ if (dataEnd + binaryChunk.length > data.length) {
+ const bufferedLength = dataEnd - dataStart;
+ if (dataStart >= data.length / 2 && bufferedLength + binaryChunk.length <= data.length) {
+ data.copyWithin(0, dataStart, dataEnd);
+ } else {
+ const newData = new Uint8Array(Math.max(data.length * 2, bufferedLength + binaryChunk.length));
+ newData.set(data.subarray(dataStart, dataEnd));
+ data = newData;
+ }
+ searchStartIndex -= dataStart;
+ dataStart = 0;
+ dataEnd = bufferedLength;
+ }
+ data.set(binaryChunk, dataEnd);
+ dataEnd += binaryChunk.length;
+ let patternIndex;
+ while ((patternIndex = findDoubleNewlineIndex(data.subarray(searchStartIndex, dataEnd))) !== -1) {
+ patternIndex += searchStartIndex;
+ yield data.slice(dataStart, patternIndex);
+ dataStart = patternIndex;
+ searchStartIndex = dataStart;
+ }
+ searchStartIndex = Math.max(dataStart, dataEnd - DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES);
+ }
+ if (dataEnd > dataStart) {
+ yield data.slice(dataStart, dataEnd);
+ }
+}
+function partition(str, delimiter) {
+ const index3 = str.indexOf(delimiter);
+ if (index3 !== -1) {
+ return [str.slice(0, index3), delimiter, str.slice(index3 + delimiter.length)];
+ }
+ return [str, "", ""];
+}
+var _Stream_instances, _Stream_client, _Stream_isTeeBranch, _Stream_cancelIterator, Stream, DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES, SSEDecoder;
+var init_streaming = __esm({
+ "node_modules/openai/core/streaming.mjs"() {
+ init_tslib();
+ init_error();
+ init_shims();
+ init_line();
+ init_errors();
+ init_bytes();
+ init_log();
+ Stream = class _Stream {
+ /** Wraps an asynchronous event iterator and the controller that owns its request. */
+ constructor(iterator, controller, client) {
+ _Stream_instances.add(this);
+ _Stream_client.set(this, void 0);
+ _Stream_isTeeBranch.set(this, false);
+ this.iterator = iterator;
+ this.controller = controller;
+ __classPrivateFieldSet(this, _Stream_client, client, "f");
+ }
+ /**
+ * Decodes an SSE response into parsed JSON events.
+ *
+ * The resulting stream can be consumed only once, ignores events after `[DONE]`, and
+ * surfaces API error payloads as `APIError` instances. When
+ * `synthesizeEventData` is enabled, each item also includes its SSE event name.
+ */
+ static fromSSEResponse(response, controller, client, synthesizeEventData) {
+ let consumed = false;
+ const logger = client ? loggerFor(client) : console;
+ async function* iterator() {
+ if (consumed) {
+ throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
+ }
+ consumed = true;
+ let done = false;
+ let receivedCompletionSentinel = false;
+ const messages = _iterSSEMessages(response, controller);
+ const closeMessages = messages.return.bind(messages);
+ messages.return = (value) => {
+ if (!receivedCompletionSentinel) {
+ controller.abort();
+ }
+ return closeMessages(value);
+ };
+ try {
+ for await (const sse of messages) {
+ if (sse.data === "[DONE]") {
+ receivedCompletionSentinel = true;
+ break;
+ }
+ if (sse.event === null || !sse.event.startsWith("thread.")) {
+ let data;
+ try {
+ data = JSON.parse(sse.data);
+ } catch {
+ logger.error(`Could not parse message into JSON:`);
+ logger.error(`From chunk:`);
+ throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
+ }
+ if (sse.event === "error") {
+ throw new APIError(void 0, data?.error ?? data, void 0, response.headers);
+ }
+ if (data && data.error) {
+ throw new APIError(void 0, data.error, void 0, response.headers);
+ }
+ yield synthesizeEventData ? { event: sse.event, data } : data;
+ } else {
+ let data;
+ try {
+ data = JSON.parse(sse.data);
+ } catch {
+ logger.error(`Could not parse message into JSON:`);
+ logger.error(`From chunk:`);
+ throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
+ }
+ yield { event: sse.event, data };
+ }
+ }
+ done = true;
+ } catch (e) {
+ if (receivedCompletionSentinel || isTransportAbortError(e) || controller.signal.aborted && e === controller.signal.reason) {
+ return;
+ }
+ throw e;
+ } finally {
+ if (!done) {
+ controller.abort();
+ }
+ }
+ }
+ return new _Stream(iterator, controller, client);
+ }
+ /**
+ * Generates a Stream from a newline-separated ReadableStream
+ * where each item is a JSON value.
+ */
+ static fromReadableStream(readableStream, controller, client) {
+ let consumed = false;
+ async function* iterLines() {
+ const lineDecoder = new LineDecoder();
+ const reader = readableStream.getReader();
+ let closed = false;
+ let cancelPromise;
+ const cancel = () => {
+ cancelPromise ?? (cancelPromise = reader.cancel());
+ cancelPromise.catch(() => void 0);
+ };
+ controller.signal.addEventListener("abort", cancel, { once: true });
+ try {
+ if (controller.signal.aborted) {
+ cancel();
+ return;
+ }
+ while (true) {
+ const { value: chunk, done } = await reader.read();
+ if (done) {
+ closed = true;
+ break;
+ }
+ if (controller.signal.aborted) {
+ return;
+ }
+ for (const line of lineDecoder.decode(chunk)) {
+ if (controller.signal.aborted) {
+ return;
+ }
+ yield line;
+ }
+ }
+ if (controller.signal.aborted) {
+ return;
+ }
+ for (const line of lineDecoder.flush()) {
+ if (controller.signal.aborted) {
+ return;
+ }
+ yield line;
+ }
+ } finally {
+ controller.signal.removeEventListener("abort", cancel);
+ if (!closed) {
+ cancel();
+ }
+ reader.releaseLock();
+ }
+ }
+ async function* iterator() {
+ if (consumed) {
+ throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
+ }
+ consumed = true;
+ let done = false;
+ try {
+ for await (const line of iterLines()) {
+ if (line) {
+ let data;
+ try {
+ data = JSON.parse(line);
+ } catch (error) {
+ if (error instanceof SyntaxError) {
+ throw new SyntaxError("Error reading response: malformed newline-delimited JSON.");
+ }
+ throw error;
+ }
+ yield data;
+ }
+ }
+ done = true;
+ } catch (e) {
+ if (controller.signal.aborted || isAbortError(e)) {
+ return;
+ }
+ throw e;
+ } finally {
+ if (!done) {
+ controller.abort();
+ }
+ }
+ }
+ return new _Stream(iterator, controller, client);
+ }
+ /** Starts consuming this stream; attempting to consume it again throws. */
+ [(_Stream_client = /* @__PURE__ */ new WeakMap(), _Stream_isTeeBranch = /* @__PURE__ */ new WeakMap(), _Stream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
+ return this.iterator();
+ }
+ /**
+ * Splits the stream into two streams which can be
+ * independently read from at different speeds.
+ * Closing a branch discards its buffered events without stopping its sibling.
+ * Future reads on that branch finish immediately; previously issued `next()`
+ * promises remain shared with its sibling and may still resolve with events.
+ * Closing both branches invokes the source iterator's `return()` when available.
+ * For {@link Stream.fromReadableStream}, closing both branches before iteration
+ * starts does not cancel the supplied readable; cancel that readable directly.
+ */
+ tee() {
+ const { controller } = this;
+ const left = createStreamTeeQueue();
+ const right = createStreamTeeQueue();
+ const iterator = this.iterator();
+ const teeIterator = (queue) => ({
+ next: () => {
+ if (queue.canceled) {
+ return Promise.resolve({ value: void 0, done: true });
+ }
+ if (queue.length === 0) {
+ const result = iterator.next();
+ left.enqueue(result);
+ right.enqueue(result);
+ }
+ return queue.dequeue();
+ },
+ return: async () => {
+ if (!queue.canceled) {
+ queue.cancel();
+ if (left.canceled && right.canceled) {
+ await __classPrivateFieldGet(this, _Stream_instances, "m", _Stream_cancelIterator).call(this, iterator, controller);
+ }
+ }
+ return { value: void 0, done: true };
+ }
+ });
+ const branch = (queue) => {
+ const stream3 = new _Stream(() => teeIterator(queue), controller, __classPrivateFieldGet(this, _Stream_client, "f"));
+ __classPrivateFieldSet(stream3, _Stream_isTeeBranch, true, "f");
+ return stream3;
+ };
+ return [branch(left), branch(right)];
+ }
+ /**
+ * Converts this stream to a newline-separated ReadableStream of
+ * JSON stringified values in the stream
+ * which can be turned back into a Stream with `Stream.fromReadableStream()`.
+ * Canceling a response-backed readable aborts its request. Canceling a tee
+ * branch discards its buffered events and leaves sibling consumers running.
+ * Read or serialization failures also release the iterator without replacing the original error.
+ */
+ toReadableStream() {
+ const { controller } = this;
+ let iter;
+ let cancellation;
+ const cancel = () => cancellation ?? (cancellation = __classPrivateFieldGet(this, _Stream_instances, "m", _Stream_cancelIterator).call(this, iter, controller));
+ return makeReadableStream({
+ start: async () => {
+ iter = this[Symbol.asyncIterator]();
+ },
+ async pull(ctrl) {
+ try {
+ const { value, done } = await iter.next();
+ if (done) {
+ return ctrl.close();
+ }
+ const bytes = encodeUTF8(JSON.stringify(value) + "\n");
+ ctrl.enqueue(bytes);
+ } catch (err2) {
+ ctrl.error(err2);
+ void cancel().catch(() => void 0);
+ }
+ },
+ cancel
+ });
+ }
+ };
+ _Stream_cancelIterator = async function _Stream_cancelIterator2(iterator, controller) {
+ const returnMethod = iterator.return;
+ if (returnMethod) {
+ if (!__classPrivateFieldGet(this, _Stream_isTeeBranch, "f")) {
+ controller.abort();
+ }
+ await Reflect.apply(returnMethod, iterator, []);
+ }
+ };
+ DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES = 3;
+ SSEDecoder = class {
+ constructor() {
+ this.event = null;
+ this.data = [];
+ this.chunks = [];
+ }
+ decode(line) {
+ if (line.endsWith("\r")) {
+ line = line.slice(0, -1);
+ }
+ if (!line) {
+ if (!this.event && !this.data.length) {
+ return null;
+ }
+ const sse = {
+ event: this.event,
+ data: this.data.join("\n"),
+ raw: this.chunks
+ };
+ this.event = null;
+ this.data = [];
+ this.chunks = [];
+ return sse;
+ }
+ this.chunks.push(line);
+ if (line.startsWith(":")) {
+ return null;
+ }
+ const [fieldname, , initialValue] = partition(line, ":");
+ let value = initialValue;
+ if (value.startsWith(" ")) {
+ value = value.slice(1);
+ }
+ if (fieldname === "event") {
+ this.event = value;
+ } else if (fieldname === "data") {
+ this.data.push(value);
+ }
+ return null;
+ }
+ /**
+ * Emits a pending event at EOF when the stream omitted the trailing blank
+ * line. Returns `null` when no event is in progress so a record that already
+ * ended with a blank line is not delivered twice.
+ */
+ flush() {
+ return this.decode("");
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/parse.mjs
+async function defaultParseResponse(client, props) {
+ const { response, requestLogID, retryOfRequestLogID, startTime } = props;
+ let jsonBodyLength;
+ const body = await (async () => {
+ if (props.options.stream) {
+ loggerFor(client).debug("response", response.status, response.url, response.headers, response.body);
+ if (props.options.__streamClass) {
+ return props.options.__streamClass.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
+ }
+ return Stream.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
+ }
+ if (response.status === 204) {
+ return null;
+ }
+ if (props.options.__binaryResponse) {
+ return response;
+ }
+ const contentType = response.headers.get("content-type");
+ const mediaType = contentType?.split(";")[0]?.trim().toLowerCase();
+ const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
+ if (isJSON) {
+ const contentLength = response.headers.get("content-length");
+ if (contentLength === "0") {
+ return void 0;
+ }
+ const bodyText = await response.text();
+ if (!bodyText) {
+ return void 0;
+ }
+ const json = JSON.parse(bodyText);
+ jsonBodyLength = bodyText.length;
+ return addRequestID(json, response);
+ }
+ const text = await response.text();
+ return text;
+ })().catch((error) => {
+ throw asAbortError(error, props.controller.signal);
+ });
+ if (client.logLevel === "debug") {
+ loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: response.url,
+ status: response.status,
+ body: jsonBodyLength === void 0 ? body : { type: "json", length: jsonBodyLength },
+ durationMs: Date.now() - startTime
+ }));
+ }
+ return body;
+}
+function asAbortError(error, signal) {
+ if (!signal.aborted || error !== signal.reason || isAbortError(error)) {
+ return error;
+ }
+ const message = "This operation was aborted";
+ const DOMExceptionConstructor = globalThis.DOMException;
+ return typeof DOMExceptionConstructor === "function" ? new DOMExceptionConstructor(message, "AbortError") : Object.assign(new Error(message), { name: "AbortError" });
+}
+function addRequestID(value, response) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return value;
+ }
+ return Object.defineProperty(value, "_request_id", {
+ value: response.headers.get("x-request-id"),
+ enumerable: false
+ });
+}
+var init_parse = __esm({
+ "node_modules/openai/internal/parse.mjs"() {
+ init_streaming();
+ init_errors();
+ init_log();
+ }
+});
+
+// node_modules/openai/version.mjs
+var VERSION;
+var init_version = __esm({
+ "node_modules/openai/version.mjs"() {
+ VERSION = "7.19.0";
+ }
+});
+
+// node_modules/openai/internal/detect-platform.mjs
+function getDetectedPlatform() {
+ if (typeof Deno !== "undefined" && Deno.build != null) {
+ return "deno";
+ }
+ if (typeof EdgeRuntime !== "undefined") {
+ return "edge";
+ }
+ if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
+ return "node";
+ }
+ return "unknown";
+}
+function getBrowserInfo() {
+ if (typeof navigator === "undefined" || !navigator) {
+ return null;
+ }
+ const browserPatterns = [
+ { key: "edge", pattern: /\bEdg(?:e|A|iOS)?\b(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
+ ];
+ for (const { key, pattern } of browserPatterns) {
+ const match = pattern.exec(navigator.userAgent);
+ if (match) {
+ const major = match[1] || 0;
+ const minor = match[2] || 0;
+ const patch = match[3] || 0;
+ return { browser: key, version: `${major}.${minor}.${patch}` };
+ }
+ }
+ return null;
+}
+var isRunningInBrowser, getPlatformProperties, normalizeArch, normalizePlatform, _platformHeaders, getPlatformHeaders;
+var init_detect_platform = __esm({
+ "node_modules/openai/internal/detect-platform.mjs"() {
+ init_version();
+ isRunningInBrowser = () => {
+ return (
+ // @ts-ignore
+ typeof window !== "undefined" && // @ts-ignore
+ typeof window.document !== "undefined" && // @ts-ignore
+ typeof navigator !== "undefined"
+ );
+ };
+ getPlatformProperties = () => {
+ const detectedPlatform = getDetectedPlatform();
+ if (detectedPlatform === "deno") {
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": normalizePlatform(Deno.build.os),
+ "X-Stainless-Arch": normalizeArch(Deno.build.arch),
+ "X-Stainless-Runtime": "deno",
+ "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
+ };
+ }
+ if (typeof EdgeRuntime !== "undefined") {
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": "Unknown",
+ "X-Stainless-Arch": `other:${EdgeRuntime}`,
+ "X-Stainless-Runtime": "edge",
+ "X-Stainless-Runtime-Version": globalThis.process?.version ?? "unknown"
+ };
+ }
+ if (detectedPlatform === "node") {
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"),
+ "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"),
+ "X-Stainless-Runtime": "node",
+ "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
+ };
+ }
+ const browserInfo = getBrowserInfo();
+ if (browserInfo) {
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": "Unknown",
+ "X-Stainless-Arch": "unknown",
+ "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
+ "X-Stainless-Runtime-Version": browserInfo.version
+ };
+ }
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": "Unknown",
+ "X-Stainless-Arch": "unknown",
+ "X-Stainless-Runtime": "unknown",
+ "X-Stainless-Runtime-Version": "unknown"
+ };
+ };
+ normalizeArch = (arch) => {
+ if (arch === "x32")
+ return "x32";
+ if (arch === "x86_64" || arch === "x64")
+ return "x64";
+ if (arch === "arm")
+ return "arm";
+ if (arch === "aarch64" || arch === "arm64")
+ return "arm64";
+ if (arch)
+ return `other:${arch}`;
+ return "unknown";
+ };
+ normalizePlatform = (platform) => {
+ platform = platform.toLowerCase();
+ if (platform.includes("ios"))
+ return "iOS";
+ if (platform === "android")
+ return "Android";
+ if (platform === "darwin")
+ return "MacOS";
+ if (platform === "win32")
+ return "Windows";
+ if (platform === "freebsd")
+ return "FreeBSD";
+ if (platform === "openbsd")
+ return "OpenBSD";
+ if (platform === "linux")
+ return "Linux";
+ if (platform)
+ return `Other:${platform}`;
+ return "Unknown";
+ };
+ getPlatformHeaders = () => {
+ return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
+ };
+ }
+});
+
+// node_modules/openai/internal/request-options.mjs
+function observeJSONRequestBody(body, observer) {
+ let observers = jsonRequestBodyObservers.get(body);
+ if (!observers) {
+ observers = /* @__PURE__ */ new Set();
+ jsonRequestBodyObservers.set(body, observers);
+ }
+ observers.add(observer);
+ return () => {
+ const active = jsonRequestBodyObservers.get(body);
+ if (!active) {
+ return;
+ }
+ active.delete(observer);
+ if (active.size === 0) {
+ jsonRequestBodyObservers.delete(body);
+ }
+ };
+}
+var jsonRequestBodyObservers, FallbackEncoder;
+var init_request_options = __esm({
+ "node_modules/openai/internal/request-options.mjs"() {
+ jsonRequestBodyObservers = /* @__PURE__ */ new WeakMap();
+ FallbackEncoder = ({ headers, body }) => {
+ const observers = typeof body === "object" && body !== null ? jsonRequestBodyObservers.get(body) : void 0;
+ let encoded;
+ if (!observers || observers.size === 0) {
+ encoded = JSON.stringify(body);
+ } else {
+ const active = [...observers];
+ encoded = JSON.stringify(body, function(key, value) {
+ let observed = value;
+ for (const observer of active) {
+ const replacement = observer.value(this, key, observed);
+ if (replacement !== void 0) {
+ observed = replacement;
+ }
+ }
+ return observed;
+ });
+ for (const observer of active) {
+ observer.complete();
+ }
+ }
+ return {
+ bodyHeaders: {
+ "content-type": "application/json"
+ },
+ body: encoded
+ };
+ };
+ }
+});
+
+// node_modules/openai/internal/qs/formats.mjs
+var default_format, default_formatter, formatters, RFC1738;
+var init_formats = __esm({
+ "node_modules/openai/internal/qs/formats.mjs"() {
+ default_format = "RFC3986";
+ default_formatter = String;
+ formatters = {
+ RFC1738: (v) => String(v).replace(/%20/g, "+"),
+ RFC3986: default_formatter
+ };
+ RFC1738 = "RFC1738";
+ }
+});
+
+// node_modules/openai/internal/qs/utils.mjs
+function is_buffer(obj) {
+ if (!obj || typeof obj !== "object") {
+ return false;
+ }
+ return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
+}
+function maybe_map(val, fn) {
+ if (isArray(val)) {
+ const mapped = [];
+ for (const item of val) {
+ mapped.push(fn(item));
+ }
+ return mapped;
+ }
+ return fn(val);
+}
+var cachedHas, has, hex_table, limit, encode;
+var init_utils = __esm({
+ "node_modules/openai/internal/qs/utils.mjs"() {
+ init_formats();
+ init_values();
+ has = (obj, key) => {
+ const resolvedHas = cachedHas ?? Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty);
+ cachedHas = resolvedHas;
+ return resolvedHas(obj, key);
+ };
+ hex_table = /* @__PURE__ */ (() => {
+ const array = [];
+ for (let i = 0; i < 256; ++i) {
+ array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
+ }
+ return array;
+ })();
+ limit = 1024;
+ encode = (str, _defaultEncoder, charset, _kind, format) => {
+ if (str.length === 0) {
+ return str;
+ }
+ let string = str;
+ if (typeof str === "symbol") {
+ string = Symbol.prototype.toString.call(str);
+ } else if (typeof str !== "string") {
+ string = String(str);
+ }
+ if (charset === "iso-8859-1") {
+ return escape(string).replace(/%u[0-9a-f]{4}/gi, ($0) => "%26%23" + Number.parseInt($0.slice(2), 16) + "%3B");
+ }
+ let out = "";
+ for (let j = 0; j < string.length; ) {
+ let segmentEnd = Math.min((Math.floor(j / limit) + 1) * limit, string.length);
+ if (segmentEnd < string.length && string.codePointAt(segmentEnd - 1) > 65535) {
+ segmentEnd += 1;
+ }
+ const segment = string.length >= limit ? string.slice(j, segmentEnd) : string;
+ const arr = [];
+ for (let i = 0; i < segment.length; ++i) {
+ let c = segment.charCodeAt(i);
+ if (c === 45 || // -
+ c === 46 || // .
+ c === 95 || // _
+ c === 126 || // ~
+ c >= 48 && c <= 57 || // 0-9
+ c >= 65 && c <= 90 || // a-z
+ c >= 97 && c <= 122 || // A-Z
+ format === RFC1738 && (c === 40 || c === 41)) {
+ arr[arr.length] = segment.charAt(i);
+ continue;
+ }
+ if (c < 128) {
+ arr[arr.length] = hex_table[c];
+ continue;
+ }
+ if (c < 2048) {
+ arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63];
+ continue;
+ }
+ if (c < 55296 || c >= 57344) {
+ arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63];
+ continue;
+ }
+ i += 1;
+ c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023);
+ arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63];
+ }
+ out += arr.join("");
+ j = segmentEnd;
+ }
+ return out;
+ };
+ }
+});
+
+// node_modules/openai/internal/qs/stringify.mjs
+function is_non_nullish_primitive(v) {
+ return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
+}
+function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder4, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
+ let obj = object;
+ let tmp_sc = sideChannel;
+ let step = 0;
+ let find_flag = false;
+ while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
+ const pos = tmp_sc.get(object);
+ step += 1;
+ if (pos !== void 0) {
+ if (pos === step) {
+ throw new RangeError("Cyclic object value");
+ } else {
+ find_flag = true;
+ }
+ }
+ if (tmp_sc.get(sentinel) === void 0) {
+ step = 0;
+ }
+ }
+ if (typeof filter === "function") {
+ obj = filter(prefix, obj);
+ } else if (obj instanceof Date) {
+ obj = serializeDate?.(obj);
+ } else if (generateArrayPrefix === "comma" && isArray(obj)) {
+ obj = maybe_map(obj, (value) => {
+ if (value instanceof Date) {
+ return serializeDate?.(value);
+ }
+ return value;
+ });
+ }
+ if (obj === null) {
+ if (strictNullHandling) {
+ return encoder4 && !encodeValuesOnly ? (
+ // @ts-expect-error
+ encoder4(prefix, defaults.encoder, charset, "key", format)
+ ) : prefix;
+ }
+ obj = "";
+ }
+ if (is_non_nullish_primitive(obj) || is_buffer(obj)) {
+ if (encoder4) {
+ const key_value = encodeValuesOnly ? prefix : (
+ // @ts-expect-error
+ encoder4(prefix, defaults.encoder, charset, "key", format)
+ );
+ return [
+ formatter?.(key_value) + "=" + // @ts-expect-error
+ formatter?.(encoder4(obj, defaults.encoder, charset, "value", format))
+ ];
+ }
+ return [formatter?.(prefix) + "=" + formatter?.(String(obj))];
+ }
+ const values = [];
+ if (obj === void 0) {
+ return values;
+ }
+ let obj_keys;
+ if (generateArrayPrefix === "comma" && isArray(obj)) {
+ if (encodeValuesOnly && encoder4) {
+ obj = maybe_map(obj, encoder4);
+ }
+ obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
+ } else if (isArray(filter)) {
+ obj_keys = filter;
+ } else {
+ const keys = Object.keys(obj);
+ if (sort) {
+ keys.sort(sort);
+ }
+ obj_keys = keys;
+ }
+ const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
+ const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
+ if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
+ return adjusted_prefix + "[]";
+ }
+ for (const key of obj_keys) {
+ const value = (
+ // @ts-ignore
+ typeof key === "object" && key.value !== void 0 ? key.value : obj[key]
+ );
+ if (skipNulls && value === null) {
+ continue;
+ }
+ const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
+ let key_prefix;
+ if (isArray(obj)) {
+ key_prefix = typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix;
+ } else {
+ key_prefix = adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
+ }
+ sideChannel.set(object, step);
+ const valueSideChannel = new WeakMap([[sentinel, sideChannel]]);
+ push_to_array(values, inner_stringify(
+ value,
+ key_prefix,
+ generateArrayPrefix,
+ commaRoundTrip,
+ allowEmptyArrays,
+ strictNullHandling,
+ skipNulls,
+ encodeDotInKeys,
+ // @ts-ignore
+ generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder4,
+ filter,
+ sort,
+ allowDots,
+ serializeDate,
+ format,
+ formatter,
+ encodeValuesOnly,
+ charset,
+ valueSideChannel
+ ));
+ }
+ return values;
+}
+function normalize_stringify_options(opts = defaults) {
+ if (opts.allowEmptyArrays !== void 0 && typeof opts.allowEmptyArrays !== "boolean") {
+ throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
+ }
+ if (opts.encodeDotInKeys !== void 0 && typeof opts.encodeDotInKeys !== "boolean") {
+ throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
+ }
+ if (opts.encoder !== null && opts.encoder !== void 0 && typeof opts.encoder !== "function") {
+ throw new TypeError("Encoder has to be a function.");
+ }
+ const charset = opts.charset || defaults.charset;
+ if (opts.charset !== void 0 && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
+ throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
+ }
+ let format = default_format;
+ if (opts.format !== void 0) {
+ if (!has(formatters, opts.format)) {
+ throw new TypeError("Unknown format option provided.");
+ }
+ format = opts.format;
+ }
+ const formatter = formatters[format];
+ let filter = defaults.filter;
+ if (typeof opts.filter === "function" || isArray(opts.filter)) {
+ filter = opts.filter;
+ }
+ let arrayFormat;
+ if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {
+ arrayFormat = opts.arrayFormat;
+ } else if ("indices" in opts) {
+ arrayFormat = opts.indices ? "indices" : "repeat";
+ } else {
+ arrayFormat = defaults.arrayFormat;
+ }
+ if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
+ throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
+ }
+ let allowDots;
+ if (opts.allowDots === void 0) {
+ allowDots = !!opts.encodeDotInKeys === true ? true : defaults.allowDots;
+ } else {
+ allowDots = !!opts.allowDots;
+ }
+ return {
+ addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix,
+ // @ts-ignore
+ allowDots,
+ allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
+ arrayFormat,
+ charset,
+ charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
+ commaRoundTrip: !!opts.commaRoundTrip,
+ delimiter: opts.delimiter === void 0 ? defaults.delimiter : opts.delimiter,
+ encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode,
+ encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
+ encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder,
+ encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
+ filter,
+ format,
+ formatter,
+ serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate,
+ skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls,
+ // @ts-ignore
+ sort: typeof opts.sort === "function" ? opts.sort : null,
+ strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
+ };
+}
+function stringify(object, opts = {}) {
+ let obj = object;
+ const options = normalize_stringify_options(opts);
+ let obj_keys;
+ let filter;
+ if (typeof options.filter === "function") {
+ filter = options.filter;
+ obj = filter("", obj);
+ } else if (isArray(options.filter)) {
+ filter = options.filter;
+ obj_keys = filter;
+ }
+ const keys = [];
+ if (typeof obj !== "object" || obj === null) {
+ return "";
+ }
+ const generateArrayPrefix = array_prefix_generators[options.arrayFormat];
+ const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
+ if (!obj_keys) {
+ obj_keys = Object.keys(obj);
+ }
+ if (options.sort) {
+ obj_keys.sort(options.sort);
+ }
+ const sideChannel = /* @__PURE__ */ new WeakMap();
+ for (const key of obj_keys) {
+ if (options.skipNulls && obj[key] === null) {
+ continue;
+ }
+ push_to_array(keys, inner_stringify(
+ obj[key],
+ key,
+ // @ts-expect-error
+ generateArrayPrefix,
+ commaRoundTrip,
+ options.allowEmptyArrays,
+ options.strictNullHandling,
+ options.skipNulls,
+ options.encodeDotInKeys,
+ options.encode ? options.encoder : null,
+ options.filter,
+ options.sort,
+ options.allowDots,
+ options.serializeDate,
+ options.format,
+ options.formatter,
+ options.encodeValuesOnly,
+ options.charset,
+ sideChannel
+ ));
+ }
+ const joined = keys.join(options.delimiter);
+ let prefix = options.addQueryPrefix === true ? "?" : "";
+ if (options.charsetSentinel) {
+ prefix += options.charset === "iso-8859-1" ? (
+ // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark
+ "utf8=%26%2310003%3B&"
+ ) : (
+ // encodeURIComponent('✓')
+ "utf8=%E2%9C%93&"
+ );
+ }
+ return joined.length > 0 ? prefix + joined : "";
+}
+var array_prefix_generators, push_to_array, toISOString, defaults, sentinel;
+var init_stringify = __esm({
+ "node_modules/openai/internal/qs/stringify.mjs"() {
+ init_utils();
+ init_formats();
+ init_values();
+ array_prefix_generators = {
+ brackets(prefix) {
+ return String(prefix) + "[]";
+ },
+ comma: "comma",
+ indices(prefix, key) {
+ return String(prefix) + "[" + key + "]";
+ },
+ repeat(prefix) {
+ return String(prefix);
+ }
+ };
+ push_to_array = function push_to_array2(arr, value_or_array) {
+ Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]);
+ };
+ defaults = {
+ addQueryPrefix: false,
+ allowDots: false,
+ allowEmptyArrays: false,
+ arrayFormat: "indices",
+ charset: "utf-8",
+ charsetSentinel: false,
+ delimiter: "&",
+ encode: true,
+ encodeDotInKeys: false,
+ encoder: encode,
+ encodeValuesOnly: false,
+ format: default_format,
+ formatter: default_formatter,
+ /** @deprecated */
+ indices: false,
+ serializeDate(date) {
+ return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date);
+ },
+ skipNulls: false,
+ strictNullHandling: false
+ };
+ sentinel = {};
+ }
+});
+
+// node_modules/openai/internal/utils/query.mjs
+function stringifyQuery(query) {
+ return stringify(query, { arrayFormat: "brackets" });
+}
+var init_query = __esm({
+ "node_modules/openai/internal/utils/query.mjs"() {
+ init_stringify();
+ }
+});
+
+// node_modules/openai/internal/data-residency.mjs
+function resolveDataResidency(options) {
+ if (options.dataResidency === null || options.dataResidency === void 0) {
+ return void 0;
+ }
+ if (hasOwn(options, "baseURL")) {
+ throw new OpenAIError("The `dataResidency` and `baseURL` options are mutually exclusive.");
+ }
+ const endpoint = endpoints.get(options.dataResidency);
+ if (endpoint === void 0) {
+ throw new OpenAIError("Invalid `dataResidency`; expected one of: global, us, eu, ae.");
+ }
+ return endpoint;
+}
+var endpoints;
+var init_data_residency = __esm({
+ "node_modules/openai/internal/data-residency.mjs"() {
+ init_error();
+ init_values();
+ endpoints = /* @__PURE__ */ new Map([
+ ["global", "https://api.openai.com/v1"],
+ ["us", "https://us.api.openai.com/v1"],
+ ["eu", "https://eu.api.openai.com/v1"],
+ ["ae", "https://ae.api.openai.com/v1"]
+ ]);
+ }
+});
+
+// node_modules/openai/core/api-promise.mjs
+var _APIPromise_client, APIPromise;
+var init_api_promise = __esm({
+ "node_modules/openai/core/api-promise.mjs"() {
+ init_tslib();
+ init_parse();
+ APIPromise = class _APIPromise extends Promise {
+ constructor(client, responsePromise, parseResponse2 = defaultParseResponse) {
+ super((resolve3) => {
+ resolve3(null);
+ });
+ this.responsePromise = responsePromise;
+ this.parseResponse = parseResponse2;
+ _APIPromise_client.set(this, void 0);
+ __classPrivateFieldSet(this, _APIPromise_client, client, "f");
+ }
+ _thenUnwrap(transform) {
+ return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
+ }
+ /**
+ * Gets the raw `Response` instance instead of parsing the response
+ * data.
+ *
+ * If you want to parse the response body but still get the `Response`
+ * instance, you can use {@link withResponse()}.
+ *
+ * 👋 Getting the wrong TypeScript type for `Response`?
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
+ * to your `tsconfig.json`.
+ */
+ asResponse() {
+ return this.responsePromise.then((p) => p.response);
+ }
+ /**
+ * Gets the parsed response data, the raw `Response` instance and the ID of the request,
+ * returned via the X-Request-ID header which is useful for debugging requests and reporting
+ * issues to OpenAI.
+ *
+ * If you just want to get the raw `Response` instance without parsing it,
+ * you can use {@link asResponse()}.
+ *
+ * 👋 Getting the wrong TypeScript type for `Response`?
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
+ * to your `tsconfig.json`.
+ */
+ async withResponse() {
+ const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
+ return { data, response, request_id: response.headers.get("x-request-id") };
+ }
+ parse() {
+ if (!this.parsedPromise) {
+ this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
+ }
+ return this.parsedPromise;
+ }
+ then(onfulfilled, onrejected) {
+ return this.parse().then(onfulfilled, onrejected);
+ }
+ catch(onrejected) {
+ return this.parse().catch(onrejected);
+ }
+ finally(onfinally) {
+ return this.parse().finally(onfinally);
+ }
+ };
+ _APIPromise_client = /* @__PURE__ */ new WeakMap();
+ }
+});
+
+// node_modules/openai/core/pagination.mjs
+var _AbstractPage_client, AbstractPage, PagePromise, Page, CursorPage, ConversationCursorPage, NextCursorPage, TokenPage;
+var init_pagination = __esm({
+ "node_modules/openai/core/pagination.mjs"() {
+ init_tslib();
+ init_error();
+ init_parse();
+ init_api_promise();
+ init_values();
+ AbstractPage = class {
+ constructor(client, response, body, options) {
+ _AbstractPage_client.set(this, void 0);
+ __classPrivateFieldSet(this, _AbstractPage_client, client, "f");
+ this.options = options;
+ this.response = response;
+ this.body = body;
+ }
+ hasNextPage() {
+ const items = this.getPaginatedItems();
+ if (!items.length)
+ return false;
+ return this.nextPageRequestOptions() != null;
+ }
+ async getNextPage() {
+ const nextOptions = this.nextPageRequestOptions();
+ if (!nextOptions) {
+ throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
+ }
+ return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
+ }
+ async *iterPages() {
+ let page2 = this;
+ yield page2;
+ while (page2.hasNextPage()) {
+ page2 = await page2.getNextPage();
+ yield page2;
+ }
+ }
+ async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
+ for await (const page2 of this.iterPages()) {
+ for (const item of page2.getPaginatedItems()) {
+ yield item;
+ }
+ }
+ }
+ };
+ PagePromise = class extends APIPromise {
+ constructor(client, request, Page2) {
+ super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options));
+ }
+ /**
+ * Allow auto-paginating iteration on an unawaited list call, eg:
+ *
+ * for await (const item of client.items.list()) {
+ * console.log(item)
+ * }
+ */
+ async *[Symbol.asyncIterator]() {
+ const page2 = await this;
+ for await (const item of page2) {
+ yield item;
+ }
+ }
+ };
+ Page = class extends AbstractPage {
+ constructor(client, response, body, options) {
+ super(client, response, body, options);
+ this.data = body.data || [];
+ this.object = body.object;
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ nextPageRequestOptions() {
+ return null;
+ }
+ };
+ CursorPage = class extends AbstractPage {
+ constructor(client, response, body, options) {
+ super(client, response, body, options);
+ this.data = body.data || [];
+ this.has_more = body.has_more || false;
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ hasNextPage() {
+ if (this.has_more === false) {
+ return false;
+ }
+ return super.hasNextPage();
+ }
+ nextPageRequestOptions() {
+ const data = this.getPaginatedItems();
+ const id = data[data.length - 1]?.id;
+ if (!id) {
+ return null;
+ }
+ return {
+ ...this.options,
+ query: {
+ ...maybeObj(this.options.query),
+ after: id
+ }
+ };
+ }
+ };
+ ConversationCursorPage = class extends AbstractPage {
+ constructor(client, response, body, options) {
+ super(client, response, body, options);
+ this.data = body.data || [];
+ this.has_more = body.has_more || false;
+ this.last_id = body.last_id || "";
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ hasNextPage() {
+ if (this.has_more === false) {
+ return false;
+ }
+ return super.hasNextPage();
+ }
+ nextPageRequestOptions() {
+ const cursor = this.last_id;
+ if (!cursor) {
+ return null;
+ }
+ return {
+ ...this.options,
+ query: {
+ ...maybeObj(this.options.query),
+ after: cursor
+ }
+ };
+ }
+ };
+ NextCursorPage = class extends AbstractPage {
+ constructor(client, response, body, options) {
+ super(client, response, body, options);
+ this.data = body.data || [];
+ this.has_more = body.has_more || false;
+ this.next = body.next || null;
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ hasNextPage() {
+ if (this.has_more === false) {
+ return false;
+ }
+ return this.nextPageRequestOptions() != null;
+ }
+ nextPageRequestOptions() {
+ const cursor = this.next;
+ if (!cursor) {
+ return null;
+ }
+ return {
+ ...this.options,
+ query: {
+ ...maybeObj(this.options.query),
+ after: cursor
+ }
+ };
+ }
+ };
+ TokenPage = class extends AbstractPage {
+ constructor(client, response, body, options) {
+ super(client, response, body, options);
+ this.data = body.data || [];
+ this.has_more = body.has_more || false;
+ this.next = body.next || null;
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ hasNextPage() {
+ if (this.has_more === false) {
+ return false;
+ }
+ return this.nextPageRequestOptions() != null;
+ }
+ nextPageRequestOptions() {
+ const cursor = this.next;
+ if (!cursor) {
+ return null;
+ }
+ return {
+ ...this.options,
+ query: {
+ ...maybeObj(this.options.query),
+ page: cursor
+ }
+ };
+ }
+ };
+ }
+});
+
+// node_modules/openai/auth/workload-identity-auth.mjs
+function calculateExpiresAt(expiresIn, exchangeStartedAt) {
+ if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) {
+ throw new OpenAIError("Token exchange response has invalid 'expires_in' field");
+ }
+ const now = Date.now();
+ const fullLifetimeDeadline = now + expiresIn * 1e3;
+ if (!Number.isSafeInteger(fullLifetimeDeadline) || fullLifetimeDeadline <= now) {
+ throw new OpenAIError("Token exchange response has invalid 'expires_in' field");
+ }
+ const expiresAt = fullLifetimeDeadline - (performance.now() - exchangeStartedAt);
+ if (expiresAt <= now) {
+ throw new OpenAIError("Workload identity token expired before its exchange completed.");
+ }
+ return expiresAt;
+}
+function calculateRefreshAt(expiresAt, lifetimeSeconds, refreshBufferSeconds) {
+ const configuredBufferMs = (refreshBufferSeconds ?? 1200) * 1e3;
+ const effectiveBufferMs = Math.min(configuredBufferMs, lifetimeSeconds * 1e3 * MAX_REFRESH_BUFFER_FRACTION);
+ return expiresAt - effectiveBufferMs;
+}
+function isResponsePrototype(response, prototype) {
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
+ if (prototype === response || typeof constructor !== "function" || Object.getOwnPropertyDescriptor(constructor, "name")?.value !== "Response" || Object.getOwnPropertyDescriptor(constructor, "prototype")?.value !== prototype) {
+ return false;
+ }
+ const tag = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);
+ return (tag?.value === "Response" || typeof tag?.get === "function") && typeof Object.getOwnPropertyDescriptor(prototype, "headers")?.get === "function" && typeof Object.getOwnPropertyDescriptor(prototype, "ok")?.get === "function" && typeof Object.getOwnPropertyDescriptor(prototype, "status")?.get === "function";
+}
+function isResponseBodyPrototype(prototype, responsePrototype) {
+ if (prototype === responsePrototype) {
+ return true;
+ }
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
+ return responsePrototype !== null && Object.getPrototypeOf(responsePrototype) === prototype && typeof constructor === "function" && Object.getOwnPropertyDescriptor(constructor, "name")?.value === "Body" && Object.getOwnPropertyDescriptor(constructor, "prototype")?.value === prototype;
+}
+function decodeNativeResponseBody(body) {
+ const scope = globalThis;
+ return new TextDecoder("utf-8", { ignoreBOM: typeof scope.Bun?.version === "string" }).decode(body);
+}
+async function parseOAuthTokenResponse(response) {
+ let readText2;
+ let responsePrototype = null;
+ for (let depth = 0, prototype = response; prototype !== null && depth < 16; prototype = Object.getPrototypeOf(prototype), depth += 1) {
+ if (prototype === NATIVE_RESPONSE_PROTOTYPE) {
+ break;
+ }
+ if (isResponsePrototype(response, prototype)) {
+ responsePrototype = prototype;
+ }
+ const parser = Object.getOwnPropertyDescriptor(prototype, "json");
+ if (!parser) {
+ continue;
+ }
+ if (typeof parser.value !== "function") {
+ break;
+ }
+ const bodyReader = Object.getOwnPropertyDescriptor(prototype, "text")?.value;
+ if (typeof bodyReader === "function" && isResponseBodyPrototype(prototype, responsePrototype)) {
+ readText2 = bodyReader;
+ break;
+ }
+ return parser.value.call(response);
+ }
+ const body = readText2 === void 0 ? decodeNativeResponseBody(await READ_NATIVE_RESPONSE_BODY.call(response)) : await readText2.call(response);
+ try {
+ return JSON.parse(body);
+ } catch {
+ throw new SyntaxError("Token exchange response contains invalid JSON");
+ }
+}
+function isUnsafeAccessToken(accessToken) {
+ const scope = globalThis;
+ if (typeof scope.Bun?.version === "string") {
+ return /[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(accessToken);
+ }
+ return /[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(accessToken);
+}
+var SUBJECT_TOKEN_TYPES, TOKEN_EXCHANGE_GRANT_TYPE, MAX_REFRESH_BUFFER_FRACTION, NATIVE_RESPONSE_PROTOTYPE, READ_NATIVE_RESPONSE_BODY, WorkloadIdentityAuth;
+var init_workload_identity_auth = __esm({
+ "node_modules/openai/auth/workload-identity-auth.mjs"() {
+ init_shims();
+ init_error();
+ SUBJECT_TOKEN_TYPES = {
+ jwt: "urn:ietf:params:oauth:token-type:jwt",
+ id: "urn:ietf:params:oauth:token-type:id_token"
+ };
+ TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
+ MAX_REFRESH_BUFFER_FRACTION = 0.5;
+ NATIVE_RESPONSE_PROTOTYPE = Response.prototype;
+ READ_NATIVE_RESPONSE_BODY = NATIVE_RESPONSE_PROTOTYPE.arrayBuffer;
+ WorkloadIdentityAuth = class _WorkloadIdentityAuth {
+ /**
+ * Creates a workload-identity token cache and OAuth token-exchange client.
+ *
+ * @param config External identity provider, OpenAI service account, and refresh settings.
+ * @param fetch Optional fetch implementation for calls to the OpenAI token endpoint.
+ */
+ constructor(config, fetch2) {
+ this.cachedToken = null;
+ this.refreshPromise = null;
+ this.tokenGeneration = 0;
+ this.tokenExchangeUrl = "https://auth.openai.com/oauth/token";
+ const { identityProviderId, serviceAccountId, clientId, refreshBufferSeconds, provider } = config;
+ this.config = {
+ identityProviderId,
+ serviceAccountId,
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...clientId === void 0 ? {} : { clientId },
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...refreshBufferSeconds === void 0 ? {} : { refreshBufferSeconds },
+ provider: {
+ tokenType: provider.tokenType,
+ getToken: provider.getToken.bind(provider)
+ }
+ };
+ this.fetch = fetch2 ?? getDefaultFetch();
+ }
+ /**
+ * Returns a valid OpenAI access token, exchanging or refreshing credentials as needed.
+ *
+ * Cached tokens nearing expiration are returned immediately while a background
+ * refresh runs. Concurrent callers share the same in-flight token exchange.
+ *
+ * @throws {OAuthError} When the token endpoint rejects the subject token or identity.
+ * @throws {APIError} When another unsuccessful HTTP response prevents token exchange.
+ * @throws {OpenAIError} When a successful exchange has an invalid access token or expiration.
+ */
+ async getToken() {
+ if (!this.cachedToken || _WorkloadIdentityAuth.isTokenExpired(this.cachedToken)) {
+ if (this.refreshPromise) {
+ return await this.refreshPromise;
+ }
+ const refreshPromise = this.refreshToken(this.tokenGeneration);
+ this.refreshPromise = refreshPromise;
+ try {
+ return await refreshPromise;
+ } finally {
+ if (this.refreshPromise === refreshPromise) {
+ this.refreshPromise = null;
+ }
+ }
+ }
+ if (_WorkloadIdentityAuth.needsRefresh(this.cachedToken) && !this.refreshPromise) {
+ const refreshPromise = this.refreshToken(this.tokenGeneration).finally(() => {
+ if (this.refreshPromise === refreshPromise) {
+ this.refreshPromise = null;
+ }
+ });
+ this.refreshPromise = refreshPromise;
+ void refreshPromise.catch(() => null);
+ }
+ return this.cachedToken.token;
+ }
+ async refreshToken(generation) {
+ const subjectToken = await this.config.provider.getToken();
+ const body = {
+ grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
+ subject_token: subjectToken,
+ subject_token_type: SUBJECT_TOKEN_TYPES[this.config.provider.tokenType],
+ identity_provider_id: this.config.identityProviderId,
+ service_account_id: this.config.serviceAccountId
+ };
+ if (this.config.clientId) {
+ body["client_id"] = this.config.clientId;
+ }
+ const exchangeStartedAt = performance.now();
+ const response = await this.fetch(this.tokenExchangeUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify(body),
+ redirect: "manual"
+ });
+ if (!response.ok) {
+ const errorText2 = await response.text();
+ let body2 = void 0;
+ try {
+ body2 = JSON.parse(errorText2);
+ } catch {
+ }
+ if (response.status === 400 || response.status === 401 || response.status === 403) {
+ throw new OAuthError(response.status, body2, response.headers);
+ }
+ throw APIError.generate(response.status, body2, `Token exchange failed with status ${response.status}`, response.headers);
+ }
+ const tokenResponse = await parseOAuthTokenResponse(response);
+ const accessToken = typeof tokenResponse === "object" && tokenResponse !== null && "access_token" in tokenResponse ? tokenResponse.access_token : void 0;
+ if (typeof accessToken !== "string" || accessToken.trim().length === 0 || isUnsafeAccessToken(accessToken)) {
+ throw new OpenAIError("Token exchange response missing 'access_token' field");
+ }
+ const expiresIn = tokenResponse.expires_in ?? 3600;
+ const expiresAt = calculateExpiresAt(expiresIn, exchangeStartedAt);
+ if (this.tokenGeneration === generation) {
+ this.cachedToken = {
+ token: accessToken,
+ expiresAt,
+ refreshAt: calculateRefreshAt(expiresAt, expiresIn, this.config.refreshBufferSeconds)
+ };
+ }
+ return accessToken;
+ }
+ static isTokenExpired(cachedToken) {
+ return Date.now() >= cachedToken.expiresAt;
+ }
+ static needsRefresh(cachedToken) {
+ return Date.now() >= cachedToken.refreshAt;
+ }
+ /** Discards the cached access token so the next request performs a fresh exchange. */
+ invalidateToken() {
+ this.tokenGeneration += 1;
+ this.cachedToken = null;
+ this.refreshPromise = null;
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/auth/x509-api-origin.mjs
+function assertX509APIOrigin(value) {
+ let target;
+ try {
+ target = new URL(value);
+ } catch {
+ throw new OpenAIError("X.509 workload identity requires the approved global mTLS API origin.");
+ }
+ if (target.origin !== "https://mtls.api.openai.com" || target.username || target.password) {
+ throw new OpenAIError("X.509 workload identity requires the approved global mTLS API origin.");
+ }
+ for (const name of target.searchParams.keys()) {
+ if (isSensitiveQueryParameter(name)) {
+ throw new OpenAIError("X.509 workload identity cannot send conflicting query authentication credentials.");
+ }
+ }
+ return target;
+}
+var X509_API_BASE_URL;
+var init_x509_api_origin = __esm({
+ "node_modules/openai/internal/auth/x509-api-origin.mjs"() {
+ init_error();
+ init_log();
+ X509_API_BASE_URL = "https://mtls.api.openai.com/v1";
+ }
+});
+
+// node_modules/openai/internal/headers.mjs
+function* iterateHeaders(headers) {
+ if (!headers)
+ return;
+ if (brand_privateNullableHeaders in headers) {
+ const { values, nulls } = headers;
+ yield* values.entries();
+ for (const name of nulls) {
+ yield [name, null];
+ }
+ return;
+ }
+ let shouldClear = false;
+ let iter;
+ const iterator = Symbol.iterator in headers ? headers[Symbol.iterator] : void 0;
+ if (typeof iterator === "function") {
+ iter = { [Symbol.iterator]: () => iterator.call(headers) };
+ } else {
+ shouldClear = true;
+ iter = Object.entries(headers ?? {});
+ }
+ for (let row of iter) {
+ const name = row[0];
+ if (typeof name !== "string")
+ throw new TypeError("expected header name to be a string");
+ const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
+ let didClear = false;
+ for (const value of values) {
+ if (value === void 0)
+ continue;
+ if (shouldClear && !didClear) {
+ didClear = true;
+ yield [name, null];
+ }
+ yield [name, value];
+ }
+ }
+}
+var brand_privateNullableHeaders, httpTokenHeaderName, buildHeaders;
+var init_headers = __esm({
+ "node_modules/openai/internal/headers.mjs"() {
+ init_values();
+ brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
+ httpTokenHeaderName = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
+ buildHeaders = (newHeaders) => {
+ const targetHeaders = new Headers();
+ const nullHeaders = /* @__PURE__ */ new Set();
+ for (const headers of newHeaders) {
+ const seenHeaders = /* @__PURE__ */ new Set();
+ for (const [name, value] of iterateHeaders(headers)) {
+ if (!httpTokenHeaderName.test(name)) {
+ throw new TypeError(`Header name must be a valid HTTP token ["${name}"]`);
+ }
+ const lowerName = name.toLowerCase();
+ if (!seenHeaders.has(lowerName)) {
+ targetHeaders.delete(lowerName);
+ seenHeaders.add(lowerName);
+ }
+ if (value === null) {
+ targetHeaders.delete(lowerName);
+ nullHeaders.add(lowerName);
+ } else {
+ targetHeaders.append(lowerName, value);
+ nullHeaders.delete(lowerName);
+ }
+ }
+ }
+ return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
+ };
+ }
+});
+
+// node_modules/openai/internal/auth/x509-transport-state-browser.mjs
+var x509_transport_state_browser_exports = {};
+__export(x509_transport_state_browser_exports, {
+ findRegisteredX509Transport: () => findRegisteredX509Transport,
+ findX509Credential: () => findX509Credential,
+ findX509OAuthError: () => findX509OAuthError,
+ isApprovedX509Client: () => isApprovedX509Client,
+ isRetryableX509IssuerError: () => isRetryableX509IssuerError,
+ isTransientX509ConnectionError: () => isTransientX509ConnectionError,
+ markApprovedX509Client: () => markApprovedX509Client,
+ markRetryableX509IssuerError: () => markRetryableX509IssuerError,
+ markTransientX509ConnectionError: () => markTransientX509ConnectionError,
+ rememberRegisteredX509Transport: () => rememberRegisteredX509Transport,
+ rememberX509Credential: () => rememberX509Credential,
+ rememberX509OAuthError: () => rememberX509OAuthError
+});
+var registeredX509Transports, transientX509ConnectionErrors, retryableX509IssuerErrors, approvedX509Clients, approvedX509OAuthErrors, approvedX509Credentials, findRegisteredX509Transport, rememberRegisteredX509Transport, markTransientX509ConnectionError, isTransientX509ConnectionError, markRetryableX509IssuerError, isRetryableX509IssuerError, markApprovedX509Client, isApprovedX509Client, rememberX509OAuthError, findX509OAuthError, rememberX509Credential, findX509Credential;
+var init_x509_transport_state_browser = __esm({
+ "node_modules/openai/internal/auth/x509-transport-state-browser.mjs"() {
+ registeredX509Transports = /* @__PURE__ */ new WeakMap();
+ transientX509ConnectionErrors = /* @__PURE__ */ new WeakSet();
+ retryableX509IssuerErrors = /* @__PURE__ */ new WeakSet();
+ approvedX509Clients = /* @__PURE__ */ new WeakSet();
+ approvedX509OAuthErrors = /* @__PURE__ */ new WeakMap();
+ approvedX509Credentials = /* @__PURE__ */ new WeakMap();
+ findRegisteredX509Transport = WeakMap.prototype.get.bind(registeredX509Transports);
+ rememberRegisteredX509Transport = WeakMap.prototype.set.bind(registeredX509Transports);
+ markTransientX509ConnectionError = WeakSet.prototype.add.bind(transientX509ConnectionErrors);
+ isTransientX509ConnectionError = WeakSet.prototype.has.bind(transientX509ConnectionErrors);
+ markRetryableX509IssuerError = WeakSet.prototype.add.bind(retryableX509IssuerErrors);
+ isRetryableX509IssuerError = WeakSet.prototype.has.bind(retryableX509IssuerErrors);
+ markApprovedX509Client = WeakSet.prototype.add.bind(approvedX509Clients);
+ isApprovedX509Client = WeakSet.prototype.has.bind(approvedX509Clients);
+ rememberX509OAuthError = WeakMap.prototype.set.bind(approvedX509OAuthErrors);
+ findX509OAuthError = WeakMap.prototype.get.bind(approvedX509OAuthErrors);
+ rememberX509Credential = WeakMap.prototype.set.bind(approvedX509Credentials);
+ findX509Credential = WeakMap.prototype.get.bind(approvedX509Credentials);
+ }
+});
+
+// node_modules/openai/internal/auth/x509-transport-state.js
+var require_x509_transport_state = __commonJS({
+ "node_modules/openai/internal/auth/x509-transport-state.js"(exports, module) {
+ "use strict";
+ if (typeof module !== "undefined" && module !== globalThis.module && typeof exports !== "undefined" && module.exports === exports) {
+ Object.defineProperty(exports, "__esModule", { value: true });
+ exports.findX509Credential = exports.rememberX509Credential = exports.findX509OAuthError = exports.rememberX509OAuthError = exports.isApprovedX509Client = exports.markApprovedX509Client = exports.isRetryableX509IssuerError = exports.markRetryableX509IssuerError = exports.isTransientX509ConnectionError = exports.markTransientX509ConnectionError = exports.rememberRegisteredX509Transport = exports.findRegisteredX509Transport = void 0;
+ const registeredX509Transports2 = /* @__PURE__ */ new WeakMap();
+ const transientX509ConnectionErrors2 = /* @__PURE__ */ new WeakSet();
+ const retryableX509IssuerErrors2 = /* @__PURE__ */ new WeakSet();
+ const approvedX509Clients2 = /* @__PURE__ */ new WeakSet();
+ const approvedX509OAuthErrors2 = /* @__PURE__ */ new WeakMap();
+ const approvedX509Credentials2 = /* @__PURE__ */ new WeakMap();
+ exports.findRegisteredX509Transport = WeakMap.prototype.get.bind(registeredX509Transports2);
+ exports.rememberRegisteredX509Transport = WeakMap.prototype.set.bind(registeredX509Transports2);
+ exports.markTransientX509ConnectionError = WeakSet.prototype.add.bind(transientX509ConnectionErrors2);
+ exports.isTransientX509ConnectionError = WeakSet.prototype.has.bind(transientX509ConnectionErrors2);
+ exports.markRetryableX509IssuerError = WeakSet.prototype.add.bind(retryableX509IssuerErrors2);
+ exports.isRetryableX509IssuerError = WeakSet.prototype.has.bind(retryableX509IssuerErrors2);
+ exports.markApprovedX509Client = WeakSet.prototype.add.bind(approvedX509Clients2);
+ exports.isApprovedX509Client = WeakSet.prototype.has.bind(approvedX509Clients2);
+ exports.rememberX509OAuthError = WeakMap.prototype.set.bind(approvedX509OAuthErrors2);
+ exports.findX509OAuthError = WeakMap.prototype.get.bind(approvedX509OAuthErrors2);
+ exports.rememberX509Credential = WeakMap.prototype.set.bind(approvedX509Credentials2);
+ exports.findX509Credential = WeakMap.prototype.get.bind(approvedX509Credentials2);
+ }
+ }
+});
+
+// node_modules/openai/internal/auth/x509-transport-state.mjs
+var nodeState, state, findRegisteredX509Transport3, rememberRegisteredX509Transport2, markTransientX509ConnectionError2, isTransientX509ConnectionError2, markRetryableX509IssuerError2, isRetryableX509IssuerError2, markApprovedX509Client2, isApprovedX509Client2, rememberX509OAuthError2, findX509OAuthError2, rememberX509Credential2, findX509Credential2;
+var init_x509_transport_state = __esm({
+ "node_modules/openai/internal/auth/x509-transport-state.mjs"() {
+ init_x509_transport_state_browser();
+ nodeState = __toESM(require_x509_transport_state(), 1);
+ state = typeof nodeState.findRegisteredX509Transport === "function" ? nodeState : x509_transport_state_browser_exports;
+ ({
+ findRegisteredX509Transport: findRegisteredX509Transport3,
+ rememberRegisteredX509Transport: rememberRegisteredX509Transport2,
+ markTransientX509ConnectionError: markTransientX509ConnectionError2,
+ isTransientX509ConnectionError: isTransientX509ConnectionError2,
+ markRetryableX509IssuerError: markRetryableX509IssuerError2,
+ isRetryableX509IssuerError: isRetryableX509IssuerError2,
+ markApprovedX509Client: markApprovedX509Client2,
+ isApprovedX509Client: isApprovedX509Client2,
+ rememberX509OAuthError: rememberX509OAuthError2,
+ findX509OAuthError: findX509OAuthError2,
+ rememberX509Credential: rememberX509Credential2,
+ findX509Credential: findX509Credential2
+ } = state);
+ }
+});
+
+// node_modules/openai/internal/auth/x509-transport-registry.mjs
+function resolveX509Transport(value) {
+ if (!value || typeof value !== "object") {
+ throw new OpenAIError("X.509 workload identity requires an approved X.509 transport capability.");
+ }
+ const registered = findRegisteredX509Transport3(value);
+ if (!registered) {
+ throw new OpenAIError("X.509 workload identity requires an approved X.509 transport capability.");
+ }
+ return registered;
+}
+var x509TransportBrand;
+var init_x509_transport_registry = __esm({
+ "node_modules/openai/internal/auth/x509-transport-registry.mjs"() {
+ init_error();
+ init_x509_transport_state();
+ x509TransportBrand = Symbol("X.509 transport capability");
+ }
+});
+
+// node_modules/openai/internal/auth/x509-workload-identity-auth.mjs
+function assertSafeHeaders(headers) {
+ for (const name of Headers.prototype.keys.call(headers)) {
+ const canonical2 = name.toLowerCase().split("_").join("-");
+ if (canonical2 !== "authorization" && isSensitiveHeader(canonical2) || canonical2 === "host") {
+ throw new OpenAIError("X.509 workload identity cannot send conflicting authentication credentials.");
+ }
+ }
+}
+function exchangeDeadline(timeout, callerSignal) {
+ const deadline = new AbortController();
+ const timer = timeout === void 0 ? void 0 : setTimeout(() => deadline.abort(new APIConnectionTimeoutError()), timeout);
+ const timerHandle = timer;
+ if (typeof timerHandle === "object" && timerHandle !== null && "unref" in timerHandle && typeof timerHandle.unref === "function") {
+ timerHandle.unref();
+ }
+ const cancel = () => deadline.abort(callerSignal?.reason);
+ callerSignal?.addEventListener("abort", cancel, { once: true });
+ if (callerSignal?.aborted) {
+ cancel();
+ }
+ return {
+ signal: deadline.signal,
+ dispose: () => {
+ callerSignal?.removeEventListener("abort", cancel);
+ if (timer) {
+ clearTimeout(timer);
+ }
+ }
+ };
+}
+function waitForRefresh(attempt, signal) {
+ let abort;
+ const canceled = new Promise((_resolve, reject) => {
+ abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ if (signal.aborted) {
+ abort();
+ }
+ });
+ return {
+ result: Promise.race([attempt.promise, canceled]),
+ dispose: () => {
+ if (abort) {
+ signal.removeEventListener("abort", abort);
+ }
+ }
+ };
+}
+function isX509WorkloadIdentity(identity) {
+ if (!identity || typeof identity !== "object") {
+ return false;
+ }
+ let providerOwner = identity;
+ while (providerOwner !== null && providerOwner !== Object.prototype) {
+ const provider = Object.getOwnPropertyDescriptor(providerOwner, "provider");
+ if (provider) {
+ if (!("value" in provider) || provider.value !== void 0) {
+ return false;
+ }
+ break;
+ }
+ providerOwner = Object.getPrototypeOf(providerOwner);
+ }
+ let current = identity;
+ while (current !== null && current !== Object.prototype) {
+ const discriminator = Object.getOwnPropertyDescriptor(current, "type");
+ if (discriminator) {
+ if (!("value" in discriminator)) {
+ throw new OpenAIError("X.509 workload identity type must be a plain data property.");
+ }
+ return discriminator.value === "x509";
+ }
+ current = Object.getPrototypeOf(current);
+ }
+ return false;
+}
+function assertX509FetchOptions(options) {
+ if (!options) {
+ return;
+ }
+ for (const name of FORBIDDEN_TRANSPORT_OPTIONS) {
+ if (hasOwn(options, name)) {
+ throw new OpenAIError("X.509 workload identity cannot override its approved transport capability.");
+ }
+ }
+ const redirect = Object.getOwnPropertyDescriptor(options, "redirect")?.value;
+ if (redirect !== void 0 && redirect !== "manual") {
+ throw new OpenAIError("X.509 workload identity requests require manual redirects.");
+ }
+}
+function assertX509RequestOptions(options) {
+ assertX509FetchOptions(options);
+ if (options && ["body", "headers", "method", "signal"].some((name) => hasOwn(options, name))) {
+ throw new OpenAIError("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.");
+ }
+}
+function snapshotX509RequestOptions(options) {
+ assertX509RequestOptions(options);
+ const snapshot = { ...options };
+ assertX509RequestOptions(snapshot);
+ return snapshot;
+}
+var _X509WorkloadIdentityAuth_instances, _a, _X509WorkloadIdentityAuth_identityProviderId, _X509WorkloadIdentityAuth_serviceAccountId, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, _X509WorkloadIdentityAuth_organization, _X509WorkloadIdentityAuth_project, _X509WorkloadIdentityAuth_transport, _X509WorkloadIdentityAuth_refreshBufferMs, _X509WorkloadIdentityAuth_cachedToken, _X509WorkloadIdentityAuth_refresh, _X509WorkloadIdentityAuth_tokenGeneration, _X509WorkloadIdentityAuth_cancelRequestBody, _X509WorkloadIdentityAuth_assignToken, _X509WorkloadIdentityAuth_recoverRefreshFailure, _X509WorkloadIdentityAuth_fallbackToken, _X509WorkloadIdentityAuth_retireRefresh, _X509WorkloadIdentityAuth_beginRefresh, _X509WorkloadIdentityAuth_refreshToken, _X509WorkloadIdentityAuth_preflight, _X509WorkloadIdentityAuth_scope, _X509WorkloadIdentityAuth_assertTenantHeaders, FORBIDDEN_TRANSPORT_OPTIONS, headerValue, DEFAULT_REFRESH_BUFFER_MS, FAILED_REFRESH_COOLDOWN_MS, userAbortError, X509WorkloadIdentityAuth;
+var init_x509_workload_identity_auth = __esm({
+ "node_modules/openai/internal/auth/x509-workload-identity-auth.mjs"() {
+ init_tslib();
+ init_error();
+ init_headers();
+ init_shims();
+ init_log();
+ init_values();
+ init_x509_api_origin();
+ init_x509_transport_registry();
+ init_x509_transport_state();
+ FORBIDDEN_TRANSPORT_OPTIONS = ["dispatcher", "agent", "client", "tls", "proxy"];
+ headerValue = (headers, name) => Headers.prototype.get.call(headers, name);
+ DEFAULT_REFRESH_BUFFER_MS = 20 * 60 * 1e3;
+ FAILED_REFRESH_COOLDOWN_MS = 1e3;
+ userAbortError = (signal) => {
+ const error = new APIUserAbortError();
+ Object.defineProperty(error, "cause", { value: signal.reason, writable: true, configurable: true });
+ return error;
+ };
+ X509WorkloadIdentityAuth = class {
+ /** Captures one registered, immutable certificate identity and its enrolled selectors. */
+ constructor(identity, transport, organization, project) {
+ _X509WorkloadIdentityAuth_instances.add(this);
+ _X509WorkloadIdentityAuth_identityProviderId.set(this, void 0);
+ _X509WorkloadIdentityAuth_serviceAccountId.set(this, void 0);
+ _X509WorkloadIdentityAuth_configuredRefreshBufferMs.set(this, void 0);
+ _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds.set(this, void 0);
+ _X509WorkloadIdentityAuth_organization.set(this, void 0);
+ _X509WorkloadIdentityAuth_project.set(this, void 0);
+ _X509WorkloadIdentityAuth_transport.set(this, void 0);
+ _X509WorkloadIdentityAuth_refreshBufferMs.set(this, void 0);
+ _X509WorkloadIdentityAuth_cachedToken.set(this, void 0);
+ _X509WorkloadIdentityAuth_refresh.set(this, void 0);
+ _X509WorkloadIdentityAuth_tokenGeneration.set(this, 0);
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_transport, resolveX509Transport(transport), "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_identityProviderId, identity.identityProviderId, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_serviceAccountId, identity.serviceAccountId, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, identity.refreshBufferMs, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, identity.refreshBufferSeconds, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_organization, organization, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_project, project, "f");
+ if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") !== void 0 && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") !== void 0) {
+ throw new OpenAIError("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");
+ }
+ if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") !== void 0 && (!Number.isSafeInteger(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f")) || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") < 0)) {
+ throw new OpenAIError("X.509 workload identity requires a nonnegative integer refreshBufferMs.");
+ }
+ if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") !== void 0 && (!Number.isSafeInteger(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f")) || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") < 0 || !Number.isSafeInteger(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") * 1e3))) {
+ throw new OpenAIError("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");
+ }
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refreshBufferMs, __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") === void 0 ? __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") ?? DEFAULT_REFRESH_BUFFER_MS : __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") * 1e3, "f");
+ }
+ /** Reconstructs the immutable selectors captured before caller-owned identity mutation. */
+ identitySnapshot() {
+ return {
+ type: "x509",
+ identityProviderId: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_identityProviderId, "f"),
+ serviceAccountId: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_serviceAccountId, "f"),
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") === void 0 ? {} : { refreshBufferMs: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") },
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") === void 0 ? {} : { refreshBufferSeconds: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") }
+ };
+ }
+ /** Preserves explicitly headerless requests without presenting a certificate to the issuer. */
+ static shouldAuthenticate(options, defaultHeaders, requestHeaders = options.headers) {
+ return !buildHeaders([defaultHeaders, requestHeaders]).nulls.has("authorization");
+ }
+ /** Snapshots each caller-owned header layer once while preserving nulls and precedence. */
+ snapshotHeaders(defaultHeaders, requestHeaders) {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ scope.defaultHeaders ?? (scope.defaultHeaders = buildHeaders([defaultHeaders]));
+ scope.requestHeaders ?? (scope.requestHeaders = buildHeaders([requestHeaders]));
+ return this.headerSnapshots();
+ }
+ /** Returns the already rendered caller headers without touching mutable inputs again. */
+ headerSnapshots() {
+ const { defaultHeaders, requestHeaders } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ if (!defaultHeaders || !requestHeaders) {
+ throw new OpenAIError("X.509 workload identity requires snapshotted request headers.");
+ }
+ return { defaultHeaders, requestHeaders };
+ }
+ /** Captures enrolled public tenant selectors once before certificate presentation. */
+ snapshotTenant(organization, project) {
+ if (organization !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") || project !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f")) {
+ throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
+ }
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ scope.tenant = { organization, project };
+ return scope.tenant;
+ }
+ /** Returns the tenant selectors already approved for this logical request. */
+ tenantSnapshot() {
+ const { tenant } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ if (!tenant) {
+ throw new OpenAIError("X.509 workload identity requires snapshotted tenant selectors.");
+ }
+ return tenant;
+ }
+ /** Validates and retains the exact destination that authenticated dispatch will use. */
+ snapshotAPIURL(value) {
+ assertX509APIOrigin(value);
+ __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).apiURL = value;
+ }
+ /** Reads the already-approved destination without rerendering caller-owned request options. */
+ requestAPIURL() {
+ const { apiURL } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ if (apiURL === void 0) {
+ throw new OpenAIError("X.509 workload identity requires a snapshotted API destination.");
+ }
+ return apiURL;
+ }
+ /** Captures the exact caller settings approved for authenticated dispatch. */
+ snapshotRequest(signal, timeout, fetchOptions) {
+ var _b;
+ (_b = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this)).request ?? (_b.request = { signal, timeout, fetchOptions });
+ }
+ /** Returns immutable request settings without invoking caller-owned accessors again. */
+ requestSnapshot() {
+ const { request } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ if (!request) {
+ throw new OpenAIError("X.509 workload identity requires snapshotted request settings.");
+ }
+ return request;
+ }
+ /** Suspends an already-running network budget during retry-local asynchronous preparation. */
+ beginRequestPreparation() {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ if (scope.deadlineArmed && scope.preparationStartedAt === void 0) {
+ scope.preparationStartedAt = performance.now();
+ scope.preparationWallStartedAt = Date.now();
+ }
+ }
+ /** Begins local request construction without charging protected hook latency to the network. */
+ beginRequestPlanning() {
+ __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).phase = "planning";
+ }
+ /** Arms one absolute network deadline only after all local request preparation completes. */
+ beginRequestNetwork() {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ if (!scope.deadlineArmed) {
+ scope.wallStartedAt = Date.now();
+ scope.monotonicStartedAt = performance.now();
+ scope.deadlineArmed = true;
+ } else if (scope.preparationStartedAt !== void 0) {
+ scope.monotonicStartedAt += performance.now() - scope.preparationStartedAt;
+ scope.wallStartedAt += Date.now() - (scope.preparationWallStartedAt ?? Date.now());
+ delete scope.preparationStartedAt;
+ delete scope.preparationWallStartedAt;
+ }
+ }
+ /** Keeps certificate authentication outside overridable request construction. */
+ isPlanningRequest() {
+ return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).phase === "planning";
+ }
+ /** Approves the final overridden destination and transport before minting a bearer. */
+ authorizePlannedRequest(url, request, timeout, allowHookSignal = false) {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ const headers = Object.getOwnPropertyDescriptor(request, "headers");
+ const body = Object.getOwnPropertyDescriptor(request, "body");
+ const signal = Object.getOwnPropertyDescriptor(request, "signal");
+ const redirect = Object.getOwnPropertyDescriptor(request, "redirect");
+ if (scope.phase !== "planning" || !headers || !(headers.value instanceof Headers) || !body && "body" in request || [body, signal, redirect].some((descriptor) => descriptor && !("value" in descriptor))) {
+ throw new OpenAIError("X.509 workload identity requires an approved final request.");
+ }
+ this.snapshotAPIURL(url);
+ assertX509FetchOptions(request);
+ try {
+ assertSafeHeaders(headers.value);
+ } catch {
+ throw new OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials.");
+ }
+ if (headerValue(headers.value, "Authorization") !== null) {
+ throw new OpenAIError("X.509 workload identity cannot use caller-supplied authorization credentials.");
+ }
+ __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_assertTenantHeaders).call(this, headers.value);
+ if (!allowHookSignal && (signal?.value ?? void 0) !== (this.requestSnapshot().signal ?? void 0)) {
+ throw new OpenAIError("X.509 workload identity must preserve its approved request signal.");
+ }
+ const approved = this.requestSnapshot();
+ scope.request = { ...approved, timeout: Math.min(approved.timeout, timeout) };
+ scope.phase = "authorizing";
+ }
+ /** Owns only SDK-created iterator adapters until authenticated dispatch takes responsibility. */
+ ownRequestBody(body, source) {
+ if (body instanceof ReadableStream && body !== source) {
+ __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).materializedBody = body;
+ }
+ }
+ /** Recognizes every one-shot upload before issuer authentication or request replay. */
+ static isStreamingRequestBody(body) {
+ return globalThis.ReadableStream !== void 0 && body instanceof globalThis.ReadableStream || typeof body === "object" && body !== null && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function");
+ }
+ /** Retires abandoned upload adapters without masking or blocking their authentication failure. */
+ retireRequestBody() {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ const body = scope.materializedBody;
+ delete scope.materializedBody;
+ if (body) {
+ void __classPrivateFieldGet(_a, _a, "m", _X509WorkloadIdentityAuth_cancelRequestBody).call(_a, body);
+ }
+ }
+ /** Transfers the dispatched upload while retiring any SDK-owned body replaced by a hook. */
+ releaseRequestBody(body) {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ if (scope.materializedBody === body) {
+ delete scope.materializedBody;
+ } else {
+ this.retireRequestBody();
+ }
+ }
+ /** Retains caller-only cancellation separately from SDK-created deadline controllers. */
+ setEffectiveSignal(signal) {
+ if (signal) {
+ __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).effectiveSignal = signal;
+ } else {
+ delete __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).effectiveSignal;
+ }
+ }
+ /** Uses protected-hook cancellation when an authenticated attempt enters retry backoff. */
+ effectiveSignal() {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ return scope.effectiveSignal ?? scope.request?.signal;
+ }
+ /** Establishes an independent scope even when concurrent requests share caller options. */
+ // oxlint-disable-next-line anti-slop/no-object-parameters -- Logical request owners are opaque identity tokens; their properties are never read.
+ runRequest(operation, requestOwner) {
+ return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").run(async () => {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
+ if (!scope) {
+ throw new OpenAIError("X.509 workload identity requires an active certificate request scope.");
+ }
+ scope.owner = this;
+ scope.requestOwner = requestOwner;
+ try {
+ return await operation();
+ } finally {
+ this.retireRequestBody();
+ this.releaseRequestCredentials();
+ delete scope.requestOwner;
+ delete scope.owner;
+ }
+ });
+ }
+ /** Reports whether a public request-building call already belongs to an active logical operation. */
+ // oxlint-disable-next-line anti-slop/no-object-parameters -- Request scope membership compares the opaque caller token by identity only.
+ inRequest(requestOwner) {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
+ return scope?.owner === this && scope.requestOwner === requestOwner && scope.phase !== "authorizing";
+ }
+ /** Shares a cache only when the complete, privately snapshotted credential identity matches. */
+ matches(other) {
+ return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_transport, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_identityProviderId, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_identityProviderId, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_serviceAccountId, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_serviceAccountId, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_organization, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_project, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refreshBufferMs, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_refreshBufferMs, "f");
+ }
+ /** Binds deferred response parsing to the original logical request and its unchanged deadline. */
+ continuation() {
+ const { wallStartedAt, monotonicStartedAt, deadlineArmed, request, requestOwner, effectiveSignal } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ const scope = {
+ wallStartedAt,
+ monotonicStartedAt,
+ owner: this,
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...deadlineArmed ? { deadlineArmed } : {},
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...request ? { request } : {},
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...effectiveSignal ? { effectiveSignal } : {},
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...requestOwner ? { requestOwner } : {}
+ };
+ return (operation) => __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").resume(scope, async () => {
+ try {
+ return await operation();
+ } finally {
+ this.releaseRequestCredentials();
+ delete scope.requestOwner;
+ delete scope.owner;
+ }
+ });
+ }
+ /** Removes dispatched bearer material before settled request promises can retain their scope. */
+ releaseRequestCredentials() {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ delete scope.request;
+ delete scope.phase;
+ delete scope.deadlineArmed;
+ delete scope.preparationStartedAt;
+ delete scope.preparationWallStartedAt;
+ delete scope.effectiveSignal;
+ delete scope.materializedBody;
+ delete scope.apiURL;
+ delete scope.tenant;
+ delete scope.token;
+ delete scope.defaultHeaders;
+ delete scope.requestHeaders;
+ delete scope.tokenGeneration;
+ delete scope.headers;
+ delete scope.authorization;
+ }
+ /** Returns the original authentication start so response consumption shares its request deadline. */
+ requestStartedAt(_options) {
+ return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current()?.wallStartedAt;
+ }
+ /** Distinguishes issued workload credentials from independent admin or headerless requests. */
+ usedWorkloadToken(_options) {
+ return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current()?.token !== void 0;
+ }
+ /** Returns the budget left after certificate authentication without starting another timeout. */
+ remainingTimeout(_options, timeout) {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
+ if (scope === void 0) {
+ return timeout;
+ }
+ const remaining = timeout - (performance.now() - scope.monotonicStartedAt);
+ if (remaining <= 0) {
+ throw new APIConnectionTimeoutError();
+ }
+ return remaining;
+ }
+ /** Cancels active retry timers promptly without changing public caller-abort semantics. */
+ async waitForRetry(duration, signal) {
+ try {
+ await __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").sleep(duration, signal);
+ } catch (error) {
+ if (signal?.aborted) {
+ throw userAbortError(signal);
+ }
+ throw error;
+ }
+ }
+ /** Trusts only issuer or connection failures privately branded by the approved transport. */
+ static isRetryableFailure(error) {
+ return typeof error === "object" && error !== null && (isTransientX509ConnectionError2(error) || isRetryableX509IssuerError2(error));
+ }
+ /** Reads safe retry hints only from a privately branded, sanitized issuer response. */
+ static retryHeaders(error) {
+ if (!error || typeof error !== "object" || !isRetryableX509IssuerError2(error)) {
+ return void 0;
+ }
+ const headers = Object.getOwnPropertyDescriptor(error, "headers")?.value;
+ return headers instanceof Headers ? headers : void 0;
+ }
+ /** Exchanges the exact certificate capability selected for the matching API dispatch. */
+ async getToken(options, context) {
+ const callerSignal = context ? context.signal : options?.signal;
+ if (callerSignal?.aborted) {
+ throw userAbortError(callerSignal);
+ }
+ if (options) {
+ assertX509RequestOptions(context ? context.fetchOptions : options.fetchOptions);
+ }
+ __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_preflight).call(this, context);
+ const scope = options ? __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this) : void 0;
+ const cached = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f");
+ if (cached && performance.now() < cached.refreshAt && Date.now() < cached.wallRefreshAt) {
+ return __classPrivateFieldGet(_a, _a, "m", _X509WorkloadIdentityAuth_assignToken).call(_a, scope, cached);
+ }
+ const remaining = context && options ? this.remainingTimeout(options, context.timeout) : context?.timeout;
+ const { signal, dispose } = exchangeDeadline(remaining, callerSignal);
+ if (callerSignal?.aborted) {
+ dispose();
+ throw userAbortError(callerSignal);
+ }
+ const attempt = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f") ?? __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_beginRefresh).call(this);
+ attempt.waiters += 1;
+ const waiter = waitForRefresh(attempt, signal);
+ try {
+ const exchanged = await waiter.result;
+ const refreshed = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f");
+ if (!refreshed || refreshed.accessToken !== exchanged.accessToken) {
+ throw new APIUserAbortError();
+ }
+ return __classPrivateFieldGet(_a, _a, "m", _X509WorkloadIdentityAuth_assignToken).call(_a, scope, refreshed);
+ } catch (error) {
+ return await __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_recoverRefreshFailure).call(this, error, attempt, cached, scope, options, context);
+ } finally {
+ waiter.dispose();
+ dispose();
+ attempt.waiters -= 1;
+ __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_retireRefresh).call(this, attempt);
+ }
+ }
+ /** Invalidates only the workload-token generation actually rejected by the current request. */
+ invalidateToken() {
+ const rejected = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
+ if (!rejected?.token || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f")?.accessToken !== rejected.token || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f").generation !== rejected.tokenGeneration) {
+ return;
+ }
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_tokenGeneration, __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f") + 1, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_cachedToken, void 0, "f");
+ const refresh = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refresh, void 0, "f");
+ refresh?.controller.abort(new APIUserAbortError());
+ }
+ /** Binds the minted credential to the original headers before protected request hooks run. */
+ bindRequest(options, request, adminAPIKey) {
+ if (!(request.headers instanceof Headers)) {
+ throw new OpenAIError("X.509 workload identity requires the original workload authorization headers.");
+ }
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ const { token } = scope;
+ const security = options.__security ?? { bearerAuth: true };
+ let approvedAuthorization = token ? `Bearer ${token}` : null;
+ if (!token && security.adminAPIKeyAuth && adminAPIKey !== null && headerValue(request.headers, "Authorization") !== null) {
+ approvedAuthorization = new Headers({ Authorization: `Bearer ${adminAPIKey}` }).get("Authorization");
+ }
+ scope.headers = request.headers;
+ scope.authorization = approvedAuthorization;
+ this.assertRequest(request);
+ }
+ /** Rebinds an equivalent protected-hook container without relaxing final dispatch identity checks. */
+ adoptRequestHeaders(request) {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
+ const original = scope.headers;
+ if (!(original instanceof Headers) || !(request.headers instanceof Headers)) {
+ throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");
+ }
+ scope.headers = request.headers;
+ try {
+ this.assertRequest(request);
+ } catch (error) {
+ scope.headers = original;
+ throw error;
+ }
+ }
+ /** Rejects request hooks that replace the selected bearer or its approved header identity. */
+ assertRequest(request) {
+ const { headers } = request;
+ if (!(headers instanceof Headers)) {
+ throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");
+ }
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
+ if (!scope || scope.headers !== headers || scope.authorization === void 0 || headerValue(headers, "Authorization") !== scope.authorization) {
+ throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");
+ }
+ __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_assertTenantHeaders).call(this, headers);
+ assertSafeHeaders(headers);
+ }
+ /** Returns a guarded final dispatcher while preserving all existing request hook object identities. */
+ fetch() {
+ return async (input, init = {}) => {
+ const target = assertX509APIOrigin(typeof input === "string" || input instanceof URL ? input : input.url);
+ assertX509FetchOptions(init);
+ this.assertRequest(init);
+ const approved = init.headers;
+ if (!(approved instanceof Headers)) {
+ throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");
+ }
+ const headers = new Headers([...Headers.prototype.entries.call(approved)]);
+ assertSafeHeaders(headers);
+ init.headers = headers;
+ init.redirect = "manual";
+ return await __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").dispatch(target, init);
+ };
+ }
+ };
+ _a = X509WorkloadIdentityAuth, _X509WorkloadIdentityAuth_identityProviderId = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_serviceAccountId = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_configuredRefreshBufferMs = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_organization = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_project = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_transport = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_refreshBufferMs = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_cachedToken = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_refresh = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_tokenGeneration = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_instances = /* @__PURE__ */ new WeakSet(), _X509WorkloadIdentityAuth_cancelRequestBody = async function _X509WorkloadIdentityAuth_cancelRequestBody2(body) {
+ try {
+ await CancelReadableStream(body);
+ } catch {
+ }
+ }, _X509WorkloadIdentityAuth_assignToken = function _X509WorkloadIdentityAuth_assignToken2(scope, token) {
+ if (scope) {
+ scope.token = token.accessToken;
+ scope.tokenGeneration = token.generation;
+ }
+ return token.accessToken;
+ }, _X509WorkloadIdentityAuth_recoverRefreshFailure = async function _X509WorkloadIdentityAuth_recoverRefreshFailure2(error, attempt, cached, scope, options, context) {
+ const callerSignal = context ? context.signal : options?.signal;
+ if (callerSignal?.aborted) {
+ throw userAbortError(callerSignal);
+ }
+ if (attempt.controller.signal.aborted && attempt.generation !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f")) {
+ return await this.getToken(options, context);
+ }
+ const fallback = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_fallbackToken).call(this, error, cached, scope);
+ if (fallback !== void 0) {
+ return fallback;
+ }
+ if (error && typeof error === "object" && !(error instanceof OAuthError)) {
+ const oauth = findX509OAuthError2(error);
+ if (oauth) {
+ throw new OAuthError(oauth.status, oauth.error, oauth.headers);
+ }
+ }
+ throw error;
+ }, _X509WorkloadIdentityAuth_fallbackToken = function _X509WorkloadIdentityAuth_fallbackToken2(error, cached, scope) {
+ if (!cached || cached !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f") || performance.now() >= cached.expiresAt || Date.now() >= cached.wallExpiresAt || !_a.isRetryableFailure(error)) {
+ return void 0;
+ }
+ const headers = _a.retryHeaders(error);
+ const milliseconds = headers?.get("retry-after-ms");
+ let requested = milliseconds ? Number(milliseconds) : void 0;
+ const retryAfter = headers?.get("retry-after");
+ if (retryAfter && (requested === void 0 || Number.isNaN(requested))) {
+ const seconds = Number(retryAfter);
+ requested = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1e3;
+ }
+ const cooldown = requested !== void 0 && Number.isFinite(requested) && requested >= 0 && requested <= 6e4 ? Math.max(FAILED_REFRESH_COOLDOWN_MS, requested) : FAILED_REFRESH_COOLDOWN_MS;
+ cached.refreshAt = Math.min(cached.expiresAt, performance.now() + cooldown);
+ cached.wallRefreshAt = Math.min(cached.wallExpiresAt, Date.now() + cooldown);
+ return __classPrivateFieldGet(_a, _a, "m", _X509WorkloadIdentityAuth_assignToken).call(_a, scope, cached);
+ }, _X509WorkloadIdentityAuth_retireRefresh = function _X509WorkloadIdentityAuth_retireRefresh2(attempt) {
+ if (attempt.waiters !== 0 || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f") !== attempt) {
+ return;
+ }
+ queueMicrotask(() => {
+ if (attempt.waiters === 0 && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f") === attempt) {
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refresh, void 0, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_tokenGeneration, __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f") + 1, "f");
+ attempt.controller.abort(new APIUserAbortError());
+ }
+ });
+ }, _X509WorkloadIdentityAuth_beginRefresh = function _X509WorkloadIdentityAuth_beginRefresh2() {
+ const controller = new AbortController();
+ const generation = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f");
+ const attempt = {
+ controller,
+ generation,
+ waiters: 0,
+ promise: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_refreshToken).call(this, controller, generation)
+ };
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refresh, attempt, "f");
+ return attempt;
+ }, _X509WorkloadIdentityAuth_refreshToken = async function _X509WorkloadIdentityAuth_refreshToken2(controller, generation) {
+ const startedAt = performance.now();
+ const wallStartedAt = Date.now();
+ try {
+ const token = await __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").exchange(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_identityProviderId, "f"), __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_serviceAccountId, "f"), controller.signal);
+ const lifetime = token.expiresIn * 1e3;
+ const expiresAt = startedAt + lifetime;
+ const wallExpiresAt = wallStartedAt + lifetime;
+ if (performance.now() >= expiresAt || Date.now() >= wallExpiresAt) {
+ throw new OpenAIError("X.509 workload identity token expired before its exchange completed.");
+ }
+ if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f") !== generation || controller.signal.aborted || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f")?.controller !== controller) {
+ throw new APIUserAbortError();
+ }
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_tokenGeneration, __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f") + 1, "f");
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_cachedToken, {
+ accessToken: token.accessToken,
+ generation: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f"),
+ expiresAt,
+ refreshAt: expiresAt - Math.min(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refreshBufferMs, "f"), lifetime / 2),
+ wallExpiresAt,
+ wallRefreshAt: wallExpiresAt - Math.min(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refreshBufferMs, "f"), lifetime / 2)
+ }, "f");
+ return token;
+ } finally {
+ if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f")?.controller === controller) {
+ __classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refresh, void 0, "f");
+ }
+ }
+ }, _X509WorkloadIdentityAuth_preflight = function _X509WorkloadIdentityAuth_preflight2(context) {
+ if (!context) {
+ return;
+ }
+ if (context.organization !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") || context.project !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f")) {
+ throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
+ }
+ assertX509APIOrigin(context.apiURL);
+ const supplied = buildHeaders([context.defaultHeaders, context.requestHeaders]);
+ if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") !== null && supplied.nulls.has("openai-organization") || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f") !== null && supplied.nulls.has("openai-project")) {
+ throw new OpenAIError("X.509 workload identity cannot omit its enrolled organization or project.");
+ }
+ for (const name of supplied.values.keys()) {
+ const canonical2 = name.toLowerCase().split("_").join("-");
+ if ((canonical2 === "openai-organization" || canonical2 === "openai-project") && (name !== canonical2 || headerValue(supplied.values, name) !== (canonical2 === "openai-organization" ? context.organization : context.project))) {
+ throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
+ }
+ if (isSensitiveHeader(canonical2) || canonical2 === "host") {
+ throw new OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials.");
+ }
+ }
+ }, _X509WorkloadIdentityAuth_scope = function _X509WorkloadIdentityAuth_scope2() {
+ const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
+ if (!scope || scope.owner !== this) {
+ throw new OpenAIError("X.509 workload identity requires an active certificate request scope.");
+ }
+ return scope;
+ }, _X509WorkloadIdentityAuth_assertTenantHeaders = function _X509WorkloadIdentityAuth_assertTenantHeaders2(headers) {
+ if (headerValue(headers, "OpenAI-Organization") !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") || headerValue(headers, "OpenAI-Project") !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f")) {
+ throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
+ }
+ for (const name of Headers.prototype.keys.call(headers)) {
+ const canonical2 = name.toLowerCase().split("_").join("-");
+ if ((canonical2 === "openai-organization" || canonical2 === "openai-project") && name !== canonical2) {
+ throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
+ }
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/auth/x509-credential-options.mjs
+function normalizeX509CredentialOptions(options) {
+ const { credential } = options;
+ if (credential === void 0) {
+ return { credential, options };
+ }
+ const registered = findX509Credential2(credential);
+ if (!registered) {
+ throw new OpenAIError("An X.509 credential must be created by the SDK authentication helper.");
+ }
+ const conflicting = ["apiKey", "adminAPIKey", "workloadIdentity", "x509Transport"].filter((name) => {
+ const value = options[name];
+ return value !== null && value !== void 0;
+ });
+ if (conflicting.length > 0) {
+ throw new OpenAIError(`The \`credential\` option cannot be combined with ${conflicting.map((name) => `\`${name}\``).join(", ")}.`);
+ }
+ return {
+ credential,
+ options: {
+ ...options,
+ apiKey: null,
+ adminAPIKey: null,
+ baseURL: options.baseURL ?? null,
+ organization: options.organization ?? null,
+ project: options.project ?? null,
+ workloadIdentity: registered.identity,
+ x509Transport: registered.transport
+ }
+ };
+}
+function overridesOrdinaryAuthentication({ apiKey, adminAPIKey }) {
+ return apiKey !== null && apiKey !== void 0 || adminAPIKey !== null && adminAPIKey !== void 0;
+}
+function prepareProviderClone(inherited, overrides) {
+ const inheritedProvider = inherited.provider;
+ const replacingProvider = overrides.credential ?? overrides.workloadIdentity;
+ const provider = overrides.provider ?? (replacingProvider ? void 0 : inheritedProvider);
+ if (provider !== inheritedProvider) {
+ delete inherited.baseURL;
+ delete inherited.organization;
+ delete inherited.project;
+ delete inherited.defaultHeaders;
+ delete inherited.defaultQuery;
+ delete inherited.fetchOptions;
+ delete inherited.fetch;
+ }
+ if (provider) {
+ delete inherited.apiKey;
+ delete inherited.adminAPIKey;
+ delete inherited.credential;
+ delete inherited.workloadIdentity;
+ delete inherited.x509Transport;
+ delete inherited.baseURL;
+ }
+ return provider;
+}
+function prepareX509ClientClone(inherited, overrides, credential, currentlyX509) {
+ const nextIdentity = hasOwn(overrides, "workloadIdentity") ? overrides.workloadIdentity : inherited.workloadIdentity;
+ const dropping = credential !== void 0 && (overridesOrdinaryAuthentication(overrides) && overrides.workloadIdentity === void 0 || overrides.provider !== void 0);
+ if (credential !== void 0 && hasOwn(overrides, "workloadIdentity")) {
+ delete inherited.x509Transport;
+ }
+ const inheritedCredential = credential !== void 0 && !dropping && overrides.credential === void 0 && !hasOwn(overrides, "workloadIdentity") && !hasOwn(overrides, "x509Transport") ? credential : void 0;
+ const nextCredential = overrides.credential === void 0 ? inheritedCredential : overrides.credential;
+ const nextX509 = nextCredential !== void 0 || !dropping && isX509WorkloadIdentity(nextIdentity);
+ if (currentlyX509 !== nextX509) {
+ delete inherited.fetch;
+ delete inherited.baseURL;
+ delete inherited.organization;
+ delete inherited.project;
+ delete inherited.defaultHeaders;
+ delete inherited.defaultQuery;
+ delete inherited.fetchOptions;
+ if (nextX509) {
+ inherited.apiKey = null;
+ } else {
+ delete inherited.x509Transport;
+ if (dropping) {
+ delete inherited.workloadIdentity;
+ }
+ }
+ }
+ if (nextCredential !== void 0) {
+ delete inherited.apiKey;
+ delete inherited.adminAPIKey;
+ delete inherited.workloadIdentity;
+ delete inherited.x509Transport;
+ inherited.credential = nextCredential;
+ if (overrides.credential !== void 0) {
+ delete inherited.organization;
+ delete inherited.project;
+ delete inherited.defaultHeaders;
+ delete inherited.defaultQuery;
+ delete inherited.fetchOptions;
+ }
+ }
+ return { credential: nextCredential, provider: prepareProviderClone(inherited, overrides) };
+}
+var init_x509_credential_options = __esm({
+ "node_modules/openai/internal/auth/x509-credential-options.mjs"() {
+ init_error();
+ init_values();
+ init_x509_workload_identity_auth();
+ init_x509_transport_state();
+ }
+});
+
+// node_modules/openai/internal/uploads.mjs
+function toStreamingFile(data, name, options) {
+ if (typeof name !== "string" || !name) {
+ throw new TypeError("toStreamingFile requires a non-empty file name");
+ }
+ const type = options?.type;
+ if (type) {
+ validateStreamingFileType(type);
+ }
+ return {
+ [brand_privateStreamingFile]: true,
+ data,
+ name,
+ ...type ? { type } : {}
+ };
+}
+function makeFile(fileBits, fileName, options) {
+ checkFileSupport();
+ return new File(fileBits, fileName ?? "unknown_file", options);
+}
+function getName(value, options) {
+ if (typeof value !== "object" || value === null) {
+ return void 0;
+ }
+ const name = "name" in value ? value.name : void 0;
+ const explicitName = name && String(name) || "filename" in value && value.filename && String(value.filename);
+ if (explicitName) {
+ return options?.stripFilename === false ? normalizeFilenamePath(explicitName) : basename(explicitName);
+ }
+ const url = "url" in value && value.url && String(value.url);
+ if (url) {
+ try {
+ return basename(new URL(url).pathname);
+ } catch {
+ return basename(url);
+ }
+ }
+ const path5 = "path" in value && value.path && String(value.path);
+ return path5 ? basename(path5) : void 0;
+}
+function basename(value) {
+ return value.split(/[\\/]/).pop() || void 0;
+}
+function normalizeFilenamePath(value) {
+ const normalized = value.replace(/\\/g, "/");
+ if (normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || normalized.split("/").includes("..")) {
+ throw new TypeError("Upload file name must be a safe relative path without parent directory segments");
+ }
+ return normalized;
+}
+function isArrayBuffer(value) {
+ try {
+ return arrayBufferByteLengthGetter?.call(value) !== void 0;
+ } catch {
+ return false;
+ }
+}
+function supportsFormData(fetchObject) {
+ const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
+ const cached = supportsFormDataMap.get(fetch2);
+ if (cached) {
+ return cached;
+ }
+ const promise = (async () => {
+ try {
+ let FetchResponse;
+ if ("Response" in fetch2) {
+ FetchResponse = fetch2.Response;
+ } else {
+ const response = await fetch2("data:,");
+ await response.arrayBuffer();
+ FetchResponse = response.constructor;
+ }
+ const data = new FormData();
+ if (data.toString() === await new FetchResponse(data).text()) {
+ return false;
+ }
+ return true;
+ } catch {
+ return true;
+ }
+ })();
+ supportsFormDataMap.set(fetch2, promise);
+ return promise;
+}
+async function* iterateMultipartBody(entries, boundary, options, preservedFilenames) {
+ for await (const { key, value } of entries) {
+ if (isUploadable(value)) {
+ const filename = preservedFilenames?.get(value) ?? getStreamingFileName(value, options);
+ const type = getStreamingFileType(value);
+ yield encodeUTF8(`--${boundary}\r
+`);
+ yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"; filename="${escapeHeaderValue(filename)}"\r
+Content-Type: ${type}\r
+\r
+`);
+ yield* iterateBytes(getStreamingFileData(value));
+ } else {
+ yield encodeUTF8(`--${boundary}\r
+`);
+ yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"\r
+\r
+${String(value)}`);
+ }
+ yield encodeUTF8("\r\n");
+ }
+ yield encodeUTF8(`--${boundary}--\r
+`);
+}
+function* iterateFormEntries(body) {
+ if (!body || typeof body !== "object") {
+ return;
+ }
+ for (const [key, value] of Object.entries(body)) {
+ yield* iterateFormValue(key, value);
+ }
+}
+function* iterateFormValue(key, value) {
+ if (value === void 0) {
+ return;
+ }
+ if (value == null) {
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
+ }
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || isUploadable(value)) {
+ yield { key, value };
+ } else if (Array.isArray(value)) {
+ for (const entry of value) {
+ yield* iterateFormValue(key + "[]", entry);
+ }
+ } else if (typeof value === "object") {
+ for (const [name, prop] of Object.entries(value)) {
+ yield* iterateFormValue(`${key}[${name}]`, prop);
+ }
+ } else {
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
+ }
+}
+function getStreamingFileName(value, options) {
+ if (isStreamingFile(value)) {
+ const { name } = value;
+ if (typeof name !== "string" || !name) {
+ throw new TypeError("Streaming upload file name must be a non-empty string");
+ }
+ return options.stripFilenames === false ? normalizeFilenamePath(name) : basename(name) ?? "unknown_file";
+ }
+ return getName(value, { stripFilename: options.stripFilenames }) ?? "unknown_file";
+}
+function getStreamingFileType(value) {
+ let type;
+ if (isStreamingFile(value) || isBlob(value)) {
+ ({ type } = value);
+ } else if (value instanceof Response) {
+ type = value.headers.get("content-type") ?? void 0;
+ }
+ return validateStreamingFileType(type || "application/octet-stream");
+}
+function validateStreamingFileType(type) {
+ if (typeof type !== "string") {
+ throw new TypeError("Streaming upload content type must be a string");
+ }
+ for (let index3 = 0; index3 < type.length; index3 += 1) {
+ const character = type.codePointAt(index3) ?? 0;
+ if (character <= 31 || character === 127) {
+ throw new TypeError("Streaming upload content type must not contain control characters");
+ }
+ }
+ return type;
+}
+function getStreamingFileData(value) {
+ if (isStreamingFile(value)) {
+ return value.data;
+ }
+ return value;
+}
+async function* iterateBytes(value) {
+ if (typeof value === "string") {
+ yield encodeUTF8(value);
+ } else if (ArrayBuffer.isView(value)) {
+ yield new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
+ } else if (isArrayBuffer(value)) {
+ yield new Uint8Array(value);
+ } else if (value instanceof Response) {
+ yield* iterateBytes(value.body || await value.blob());
+ } else if (value instanceof Blob) {
+ if (typeof value.stream === "function") {
+ yield* iterateBytes(value.stream());
+ } else {
+ yield new Uint8Array(await value.arrayBuffer());
+ }
+ } else if (isReadableStream(value)) {
+ for await (const chunk of ReadableStreamToAsyncIterable(value)) {
+ yield* iterateBytes(chunk);
+ }
+ } else if (isAsyncIterable(value)) {
+ for await (const chunk of value) {
+ yield* iterateBytes(chunk);
+ }
+ } else {
+ throw new TypeError(`Invalid streaming file chunk: ${String(value)}`);
+ }
+}
+function escapeHeaderValue(value) {
+ return Array.from(value, (character) => {
+ const codePoint = character.codePointAt(0) ?? 0;
+ return codePoint <= 31 || codePoint === 127 || character === '"' || character === "\\" ? encodeURIComponent(character) : character;
+ }).join("");
+}
+var brand_privateStreamingFile, checkFileSupport, arrayBufferByteLengthGetter, isAsyncIterable, maybeMultipartFormRequestOptions, multipartFormRequestOptions, supportsFormDataMap, createForm, isBlob, isReadableStream, isStreamingFile, isUploadable, hasStreamingUploadableValue, hasUploadableValue, snapshotPreservedUploadEntries, createStreamingFormRequestOptions, addFormValue;
+var init_uploads = __esm({
+ "node_modules/openai/internal/uploads.mjs"() {
+ init_headers();
+ init_shims();
+ init_bytes();
+ brand_privateStreamingFile = /* @__PURE__ */ Symbol("brand.privateStreamingFile");
+ checkFileSupport = () => {
+ if (typeof File === "undefined") {
+ const { process: process2 } = globalThis;
+ const isOldNode = typeof process2?.versions?.node === "string" && Number.parseInt(process2.versions.node.split("."), 10) < 20;
+ throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`." : ""));
+ }
+ };
+ arrayBufferByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")?.get;
+ isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
+ maybeMultipartFormRequestOptions = async (opts, fetch2, formOptions) => {
+ if (!hasUploadableValue(opts.body)) {
+ return opts;
+ }
+ if (hasStreamingUploadableValue(opts.body)) {
+ return createStreamingFormRequestOptions(opts, formOptions);
+ }
+ return { ...opts, body: await createForm(opts.body, fetch2, formOptions) };
+ };
+ multipartFormRequestOptions = async (opts, fetch2, formOptions) => {
+ if (hasStreamingUploadableValue(opts.body)) {
+ return createStreamingFormRequestOptions(opts, formOptions);
+ }
+ return { ...opts, body: await createForm(opts.body, fetch2, formOptions) };
+ };
+ supportsFormDataMap = /* @__PURE__ */ new WeakMap();
+ createForm = async (body, fetch2, options = {}) => {
+ if (!await supportsFormData(fetch2)) {
+ throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
+ }
+ const form = new FormData();
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, options)));
+ return form;
+ };
+ isBlob = (value) => value instanceof Blob;
+ isReadableStream = (value) => typeof value === "object" && value !== null && "getReader" in value && typeof value.getReader === "function";
+ isStreamingFile = (value) => typeof value === "object" && value !== null && brand_privateStreamingFile in value;
+ isUploadable = (value) => typeof value === "object" && value !== null && (value instanceof Response || isAsyncIterable(value) || isReadableStream(value) || isStreamingFile(value) || isBlob(value));
+ hasStreamingUploadableValue = (value) => {
+ if (isStreamingFile(value) || isAsyncIterable(value) || isReadableStream(value)) {
+ return true;
+ }
+ if (Array.isArray(value)) {
+ return value.some(hasStreamingUploadableValue);
+ }
+ if (value && typeof value === "object" && !isBlob(value) && !(value instanceof Response)) {
+ for (const k of Object.keys(value)) {
+ if (hasStreamingUploadableValue(value[k])) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+ hasUploadableValue = (value) => {
+ if (isUploadable(value)) {
+ return true;
+ }
+ if (Array.isArray(value)) {
+ return value.some(hasUploadableValue);
+ }
+ if (value && typeof value === "object") {
+ for (const k of Object.keys(value)) {
+ if (hasUploadableValue(value[k])) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+ snapshotPreservedUploadEntries = (entries, filenames) => {
+ const snapshot = [];
+ for (const entry of entries) {
+ if (isUploadable(entry.value) && !filenames.has(entry.value)) {
+ filenames.set(entry.value, getStreamingFileName(entry.value, { stripFilenames: false }));
+ }
+ snapshot.push(entry);
+ }
+ return snapshot;
+ };
+ createStreamingFormRequestOptions = (opts, options = {}) => {
+ const entries = iterateFormEntries(opts.body);
+ const preservedFilenames = options.stripFilenames === false ? /* @__PURE__ */ new WeakMap() : void 0;
+ const multipartEntries = preservedFilenames ? snapshotPreservedUploadEntries(entries, preservedFilenames) : entries;
+ const boundary = `openai-${Math.random().toString(36).slice(2)}`;
+ const body = ReadableStreamFrom(iterateMultipartBody(multipartEntries, boundary, options, preservedFilenames));
+ return {
+ ...opts,
+ body,
+ headers: buildHeaders([{ "content-type": `multipart/form-data; boundary=${boundary}` }, opts.headers])
+ };
+ };
+ addFormValue = async (form, key, value, options) => {
+ if (value === void 0) {
+ return;
+ }
+ if (value == null) {
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
+ }
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ form.append(key, String(value));
+ } else if (value instanceof Response) {
+ const blob = await value.blob();
+ form.append(key, makeFile([blob], getName(value, { stripFilename: options.stripFilenames }), { type: blob.type }));
+ } else if (isAsyncIterable(value)) {
+ form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, { stripFilename: options.stripFilenames })));
+ } else if (isBlob(value)) {
+ const filename = getName(value, { stripFilename: options.stripFilenames });
+ if (filename === void 0) {
+ form.append(key, value);
+ } else {
+ form.append(key, value, filename);
+ }
+ } else if (Array.isArray(value)) {
+ const entries = await Promise.all(value.map(async (entry) => {
+ const entryForm = new FormData();
+ await addFormValue(entryForm, key + "[]", entry, options);
+ return entryForm;
+ }));
+ for (const entryForm of entries) {
+ if (!entryForm) {
+ continue;
+ }
+ for (const [entryKey, entryValue] of entryForm.entries()) {
+ form.append(entryKey, entryValue);
+ }
+ }
+ } else if (typeof value === "object") {
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, options)));
+ } else {
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/to-file.mjs
+async function toFile(value, name, options) {
+ checkFileSupport();
+ value = await value;
+ if (isFileLike(value)) {
+ const fileOptions = {
+ ...options,
+ type: options?.type ?? value.type,
+ lastModified: options?.lastModified ?? value.lastModified
+ };
+ if (value instanceof File) {
+ if (canReuseNativeFile(value, name, options)) {
+ return value;
+ }
+ return makeFile([value], name ?? value.name, fileOptions);
+ }
+ return makeFile([await value.arrayBuffer()], name ?? value.name, fileOptions);
+ }
+ if (isResponseLike(value)) {
+ const blob = await value.blob();
+ name ?? (name = getName(value));
+ const responseOptions = options?.type === void 0 && blob.type ? { ...options, type: blob.type } : options;
+ return makeFile(await getBytes(blob), name, responseOptions);
+ }
+ const parts2 = await getBytes(value);
+ name ?? (name = getName(value));
+ if (options?.type === void 0) {
+ const typedPart = parts2.find((part) => typeof part === "object" && "type" in part && !!part.type);
+ if (typedPart) {
+ options = { ...options, type: typedPart.type };
+ }
+ }
+ return makeFile(parts2, name, options);
+}
+async function getBytes(value) {
+ const parts2 = [];
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
+ isArrayBuffer(value)) {
+ parts2.push(value);
+ } else if (isBlobLike(value)) {
+ parts2.push(value instanceof Blob ? value : new Blob([await value.arrayBuffer()], { type: value.type }));
+ } else if (isAsyncIterable(value)) {
+ for await (const chunk of value) {
+ parts2.push(...await getBytes(chunk));
+ }
+ } else {
+ const constructor = value?.constructor?.name;
+ throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`);
+ }
+ return parts2;
+}
+function propsForError(value) {
+ if (typeof value !== "object" || value === null) {
+ return "";
+ }
+ const props = Object.getOwnPropertyNames(value);
+ return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`;
+}
+var isBlobLike, isFileLike, isResponseLike, hasFilePropertyOverrides, canReuseNativeFile;
+var init_to_file = __esm({
+ "node_modules/openai/internal/to-file.mjs"() {
+ init_uploads();
+ isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
+ isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value);
+ isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
+ hasFilePropertyOverrides = (value, options) => options?.type != null && options.type !== value.type || options?.lastModified != null && options.lastModified !== value.lastModified || options?.endings != null;
+ canReuseNativeFile = (value, name, options) => (name == null || name === value.name) && !hasFilePropertyOverrides(value, options);
+ }
+});
+
+// node_modules/openai/core/uploads.mjs
+var init_uploads2 = __esm({
+ "node_modules/openai/core/uploads.mjs"() {
+ init_uploads();
+ init_to_file();
+ }
+});
+
+// node_modules/openai/core/resource.mjs
+var APIResource;
+var init_resource = __esm({
+ "node_modules/openai/core/resource.mjs"() {
+ APIResource = class {
+ constructor(client) {
+ this._client = client;
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/utils/path.mjs
+function encodeURIPath(str) {
+ return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
+}
+var EMPTY, createPathTagFunction, path;
+var init_path = __esm({
+ "node_modules/openai/internal/utils/path.mjs"() {
+ init_error();
+ EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
+ createPathTagFunction = (pathEncoder = encodeURIPath) => function path5(statics, ...params) {
+ if (statics.length === 1) {
+ return statics[0];
+ }
+ let postPath = false;
+ const invalidSegments = [];
+ let path6 = "";
+ for (let index3 = 0; index3 < statics.length; index3 += 1) {
+ if (index3 in statics) {
+ const currentValue = statics[index3];
+ if (/[?#]/.test(currentValue)) {
+ postPath = true;
+ }
+ const value = params[index3];
+ let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
+ if (index3 !== params.length && (value == null || // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Path parameters may arrive from JavaScript callers and require runtime validation before URL encoding.
+ typeof value === "object" && // handle values from other realms
+ value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) {
+ encoded = value + "";
+ invalidSegments.push({
+ start: path6.length + currentValue.length,
+ length: encoded.length,
+ error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
+ });
+ }
+ path6 += currentValue + (index3 === params.length ? "" : encoded);
+ }
+ }
+ const pathOnly = path6.split(/[?#]/, 1)[0];
+ const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
+ let match;
+ while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
+ invalidSegments.push({
+ start: match.index,
+ length: match[0].length,
+ error: `Value "${match[0]}" can't be safely passed as a path parameter`
+ });
+ }
+ invalidSegments.sort((a, b) => a.start - b.start);
+ if (invalidSegments.length > 0) {
+ let lastEnd = 0;
+ let underline = "";
+ for (const segment of invalidSegments) {
+ const spaces = " ".repeat(segment.start - lastEnd);
+ const arrows = "^".repeat(segment.length);
+ lastEnd = segment.start + segment.length;
+ underline += spaces + arrows;
+ }
+ throw new OpenAIError(`Path parameters result in path with invalid segments:
+${invalidSegments.map((e) => e.error).join("\n")}
+${path6}
+${underline}`);
+ }
+ return path6;
+ };
+ path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
+ }
+});
+
+// node_modules/openai/resources/chat/completions/messages.mjs
+var Messages;
+var init_messages = __esm({
+ "node_modules/openai/resources/chat/completions/messages.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Messages = class extends APIResource {
+ /**
+ * Get the messages in a stored chat completion. Only Chat Completions that have
+ * been created with the `store` parameter set to `true` will be returned.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list(
+ * 'completion_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(completionID, query = {}, options) {
+ return this._client.getAPIList(path`/chat/completions/${completionID}/messages`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/error.mjs
+var init_error2 = __esm({
+ "node_modules/openai/error.mjs"() {
+ init_error();
+ }
+});
+
+// node_modules/openai/lib/parser.mjs
+function isChatCompletionFunctionTool(tool) {
+ return tool !== void 0 && "function" in tool && tool.function !== void 0;
+}
+function isAutoParsableResponseFormat(response_format) {
+ return response_format?.["$brand"] === "auto-parseable-response-format";
+}
+function isParseableResponseFormat(format) {
+ return isAutoParsableResponseFormat(format) || format?.type === "json_schema";
+}
+function parseResponseFormatContent(format, content) {
+ if (!isParseableResponseFormat(format)) {
+ return null;
+ }
+ if (typeof format === "object" && format !== null && "$parseRaw" in format && typeof format.$parseRaw === "function") {
+ return format.$parseRaw(content);
+ }
+ try {
+ return JSON.parse(content);
+ } catch (error) {
+ if (error instanceof SyntaxError) {
+ throw new SyntaxError("Error reading response: invalid structured output JSON.");
+ }
+ throw error;
+ }
+}
+function isAutoParsableTool(tool) {
+ return tool?.["$brand"] === "auto-parseable-tool";
+}
+function maybeParseChatCompletion(completion, params) {
+ if (!params || !hasAutoParseableInput(params)) {
+ return {
+ ...completion,
+ choices: completion.choices.map((choice) => ({
+ ...choice,
+ message: {
+ ...choice.message,
+ parsed: null,
+ ...choice.message.tool_calls ? {
+ tool_calls: choice.message.tool_calls
+ } : void 0
+ }
+ }))
+ };
+ }
+ return parseChatCompletion(completion, params);
+}
+function parseChatCompletion(completion, params) {
+ const choices = completion.choices.map((choice) => {
+ if (choice.finish_reason === "length") {
+ throw new LengthFinishReasonError();
+ }
+ if (choice.finish_reason === "content_filter") {
+ throw new ContentFilterFinishReasonError();
+ }
+ return {
+ ...choice,
+ message: {
+ ...choice.message,
+ ...choice.message.tool_calls ? {
+ tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? void 0
+ } : void 0,
+ parsed: choice.message.content !== null && choice.message.content !== void 0 && !choice.message.refusal && (choice.message.content !== "" || !choice.message.tool_calls?.length && !choice.message.function_call) ? parseResponseFormat(params, choice.message.content) : null
+ }
+ };
+ });
+ return { ...completion, choices };
+}
+function parseResponseFormat(params, content) {
+ return parseResponseFormatContent(params.response_format, content);
+}
+function parseToolCall(params, toolCall) {
+ if (toolCall.type === "custom") {
+ return toolCall;
+ }
+ if (toolCall.type !== "function") {
+ const unsupportedType = toolCall.type;
+ throw new OpenAIError(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${unsupportedType}\``);
+ }
+ const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function.name);
+ let parsedArguments = null;
+ if (isAutoParsableTool(inputTool)) {
+ parsedArguments = inputTool.$parseRaw(toolCall.function.arguments);
+ } else if (inputTool?.function.strict) {
+ parsedArguments = parseResponseFormatContent({ type: "json_schema", $parseRaw: void 0 }, toolCall.function.arguments);
+ }
+ return {
+ ...toolCall,
+ function: {
+ ...toolCall.function,
+ parsed_arguments: parsedArguments
+ }
+ };
+}
+function shouldParseToolCall(params, toolCall) {
+ if (!params || !("tools" in params) || !params.tools || toolCall.type !== "function") {
+ return false;
+ }
+ const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function?.name);
+ return isChatCompletionFunctionTool(inputTool) && (isAutoParsableTool(inputTool) || inputTool?.function.strict || false);
+}
+function hasAutoParseableInput(params) {
+ if (isParseableResponseFormat(params.response_format)) {
+ return true;
+ }
+ return params.tools?.some((t) => isAutoParsableTool(t) || t.type === "function" && t.function.strict === true) ?? false;
+}
+function validateInputTools(tools) {
+ for (const tool of tools ?? []) {
+ if (tool.type === "custom") {
+ continue;
+ }
+ if (tool.type !== "function") {
+ const unsupportedType = tool.type;
+ throw new OpenAIError(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${unsupportedType}\``);
+ }
+ if (tool.function.strict !== true) {
+ throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`);
+ }
+ }
+}
+var init_parser = __esm({
+ "node_modules/openai/lib/parser.mjs"() {
+ init_error2();
+ }
+});
+
+// node_modules/openai/lib/chatCompletionUtils.mjs
+var isAssistantMessage, isToolMessage;
+var init_chatCompletionUtils = __esm({
+ "node_modules/openai/lib/chatCompletionUtils.mjs"() {
+ isAssistantMessage = (message) => message?.role === "assistant";
+ isToolMessage = (message) => message?.role === "tool";
+ }
+});
+
+// node_modules/openai/lib/EventStream.mjs
+function captureNativeProxyDetector() {
+ if (typeof process === "undefined") {
+ return void 0;
+ }
+ try {
+ const loader = Object.getOwnPropertyDescriptor(process, "getBuiltinModule");
+ if (!loader || !("value" in loader) || typeof loader.value !== "function") {
+ return void 0;
+ }
+ const util = Reflect.apply(loader.value, process, ["node:util"]);
+ if (typeof util !== "object" || util === null) {
+ return void 0;
+ }
+ const types = Object.getOwnPropertyDescriptor(util, "types");
+ if (!types || !("value" in types) || typeof types.value !== "object" || types.value === null) {
+ return void 0;
+ }
+ const detector = Object.getOwnPropertyDescriptor(types.value, "isProxy");
+ if (!detector || !("value" in detector) || typeof detector.value !== "function") {
+ return void 0;
+ }
+ return detector.value;
+ } catch {
+ return void 0;
+ }
+}
+function rememberTrustedIntrinsic(constructor) {
+ if (typeof constructor !== "function") {
+ return;
+ }
+ const prototypeDescriptor = Object.getOwnPropertyDescriptor(constructor, "prototype");
+ if (!prototypeDescriptor || !("value" in prototypeDescriptor) || typeof prototypeDescriptor.value !== "object" && typeof prototypeDescriptor.value !== "function") {
+ return;
+ }
+ trustedIntrinsicPrototypes.add(prototypeDescriptor.value);
+ const source = functionToString.call(constructor);
+ if (/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(source) && prototypeDescriptor.configurable === false && prototypeDescriptor.writable === false) {
+ trustedNativeConstructorSources.add(source);
+ const descriptors = /* @__PURE__ */ new Map();
+ for (const key of Reflect.ownKeys(prototypeDescriptor.value)) {
+ const descriptor = Object.getOwnPropertyDescriptor(prototypeDescriptor.value, key);
+ if (descriptor) {
+ descriptors.set(key, descriptor);
+ }
+ }
+ canonicalIntrinsicDescriptors.set(source, descriptors);
+ }
+}
+function getTrustedForeignIntrinsic(prototype) {
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "constructor");
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "function") {
+ return void 0;
+ }
+ const constructor = descriptor.value;
+ const source = functionToString.call(constructor);
+ const descriptors = canonicalIntrinsicDescriptors.get(source);
+ if (!trustedNativeConstructorSources.has(source) || !descriptors) {
+ return void 0;
+ }
+ const constructorPrototype = Object.getOwnPropertyDescriptor(constructor, "prototype");
+ if (!constructorPrototype || !("value" in constructorPrototype) || constructorPrototype.value !== prototype || constructorPrototype.configurable !== false || constructorPrototype.writable !== false) {
+ return void 0;
+ }
+ return { constructor, descriptors, functionPrototype: Object.getPrototypeOf(constructor) };
+}
+function isTrustedIntrinsicPrototype(prototype) {
+ return trustedIntrinsicPrototypes.has(prototype) || getTrustedForeignIntrinsic(prototype) !== void 0;
+}
+function isCanonicalIntrinsicFunction(value, canonical2, functionPrototype) {
+ if (canonical2 === void 0) {
+ return value === void 0;
+ }
+ if (typeof value !== "function" || typeof canonical2 !== "function") {
+ return false;
+ }
+ const source = functionToString.call(canonical2);
+ if (functionToString.call(value) !== source) {
+ return false;
+ }
+ const actualFunctionPrototype = Object.getPrototypeOf(value);
+ if (actualFunctionPrototype === functionPrototype) {
+ return true;
+ }
+ if (!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(source)) {
+ return false;
+ }
+ const intrinsic = getTrustedForeignIntrinsic(actualFunctionPrototype);
+ return intrinsic !== void 0 && functionToString.call(intrinsic.constructor) === nativeFunctionConstructorSource;
+}
+function isCanonicalIntrinsicDescriptor(descriptor, canonical2, functionPrototype) {
+ if (!canonical2 || descriptor.configurable !== canonical2.configurable || descriptor.enumerable !== canonical2.enumerable || "value" in descriptor !== "value" in canonical2) {
+ return false;
+ }
+ if ("value" in descriptor && "value" in canonical2) {
+ if (descriptor.writable !== canonical2.writable) {
+ return false;
+ }
+ if (typeof canonical2.value === "function") {
+ return isCanonicalIntrinsicFunction(descriptor.value, canonical2.value, functionPrototype);
+ }
+ if (canonical2.value !== null && typeof canonical2.value === "object") {
+ return false;
+ }
+ return Object.is(descriptor.value, canonical2.value);
+ }
+ return isCanonicalIntrinsicFunction(descriptor.get, canonical2.get, functionPrototype) && isCanonicalIntrinsicFunction(descriptor.set, canonical2.set, functionPrototype);
+}
+function hasNativeErrorBrand(current) {
+ if (nativeErrorBrand) {
+ return nativeErrorBrand.call(Error, current);
+ }
+ let prototype = current;
+ for (let depth = 0; prototype !== null && depth < MAX_BUFFERED_EVENT_DEPTH; depth += 1) {
+ if (Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag)) {
+ return false;
+ }
+ prototype = Object.getPrototypeOf(prototype);
+ }
+ return prototype === null && objectToString.call(current) === "[object Error]";
+}
+function getVerifiedForeignErrorConstructor(current, stackDescriptor) {
+ if (typeof stackDescriptor.get !== "function" || typeof stackDescriptor.set !== "function") {
+ return void 0;
+ }
+ let prototype = Object.getPrototypeOf(current);
+ for (let depth = 0; prototype !== null && depth < MAX_BUFFERED_EVENT_DEPTH; depth += 1) {
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, "constructor");
+ if (descriptor && "value" in descriptor && typeof descriptor.value === "function") {
+ const constructor = descriptor.value;
+ if (functionToString.call(constructor) === nativeErrorConstructorSource && isTrustedIntrinsicPrototype(prototype)) {
+ const functionPrototype = Object.getPrototypeOf(constructor);
+ if (Object.getPrototypeOf(stackDescriptor.get) === functionPrototype && Object.getPrototypeOf(stackDescriptor.set) === functionPrototype) {
+ return { constructor, prototype };
+ }
+ return void 0;
+ }
+ }
+ prototype = Object.getPrototypeOf(prototype);
+ }
+ return void 0;
+}
+function isTrustedNativeErrorStack(current, descriptor) {
+ if (!hasNativeErrorBrand(current)) {
+ return false;
+ }
+ if (errorStackDescriptor && !("value" in errorStackDescriptor) && typeof errorStackDescriptor.get === "function" && Object.prototype.isPrototypeOf.call(Error.prototype, current) && descriptor.get === errorStackDescriptor.get && descriptor.set === errorStackDescriptor.set) {
+ return true;
+ }
+ const verified = getVerifiedForeignErrorConstructor(current, descriptor);
+ if (!verified) {
+ return false;
+ }
+ let canonicalDescriptor = foreignErrorStackDescriptors.get(verified.prototype);
+ if (!canonicalDescriptor) {
+ const canonical2 = Reflect.construct(verified.constructor, []);
+ if (typeof canonical2 !== "object" || canonical2 === null || !hasNativeErrorBrand(canonical2) || Object.getPrototypeOf(canonical2) !== verified.prototype) {
+ return false;
+ }
+ canonicalDescriptor = Object.getOwnPropertyDescriptor(canonical2, "stack");
+ if (!canonicalDescriptor || "value" in canonicalDescriptor || typeof canonicalDescriptor.get !== "function" || typeof canonicalDescriptor.set !== "function") {
+ return false;
+ }
+ foreignErrorStackDescriptors.set(verified.prototype, canonicalDescriptor);
+ }
+ return descriptor.get === canonicalDescriptor.get && descriptor.set === canonicalDescriptor.set;
+}
+function createEventQueue() {
+ let entries = [];
+ let head = 0;
+ return {
+ get length() {
+ return entries.length - head;
+ },
+ enqueue(value) {
+ entries.push(value);
+ },
+ dequeue() {
+ if (head === entries.length) {
+ return void 0;
+ }
+ const value = entries[head];
+ entries[head] = void 0;
+ head += 1;
+ if (head === entries.length) {
+ entries = [];
+ head = 0;
+ } else if (head >= 1024 && head * 2 >= entries.length) {
+ entries = entries.slice(head);
+ head = 0;
+ }
+ return value;
+ },
+ clear() {
+ entries = [];
+ head = 0;
+ }
+ };
+}
+function getRetainedStorageBrand(current) {
+ let prototype = Object.getPrototypeOf(current);
+ for (let depth = 0; prototype !== null && depth < MAX_BUFFERED_EVENT_DEPTH; depth += 1) {
+ if (prototype === Date.prototype) {
+ return "Date";
+ }
+ if (!trustedIntrinsicPrototypes.has(prototype)) {
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor");
+ if (constructor && "value" in constructor && typeof constructor.value === "function" && functionToString.call(constructor.value) === nativeDateConstructorSource && getTrustedForeignIntrinsic(prototype)) {
+ return "Date";
+ }
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);
+ if (descriptor && "value" in descriptor && typeof descriptor.value === "string" && retainedStorageBrands.has(descriptor.value)) {
+ return descriptor.value;
+ }
+ prototype = Object.getPrototypeOf(prototype);
+ }
+ return void 0;
+}
+function estimateRetainedBufferBytes(current, visit, depth) {
+ if (ArrayBuffer.isView(current)) {
+ let buffer;
+ let kind2 = "typed-array";
+ try {
+ buffer = typedArrayBufferGetter?.call(current);
+ } catch {
+ kind2 = "data-view";
+ buffer = dataViewBufferGetter?.call(current);
+ }
+ if (typeof buffer !== "object" || buffer === null) {
+ return { bytes: Number.POSITIVE_INFINITY, kind: kind2 };
+ }
+ visit(buffer, depth + 1);
+ return { bytes: 0, kind: kind2 };
+ }
+ const brand = getRetainedStorageBrand(current);
+ if (!brand) {
+ return void 0;
+ }
+ let getter;
+ const kind = "buffer";
+ switch (brand) {
+ case "ArrayBuffer": {
+ getter = arrayBufferByteLengthGetter2;
+ break;
+ }
+ case "SharedArrayBuffer": {
+ getter = sharedArrayBufferByteLengthGetter;
+ break;
+ }
+ case "Blob":
+ case "File": {
+ return { bytes: Number.POSITIVE_INFINITY, kind: "blob" };
+ }
+ case "Map": {
+ return { bytes: 0, kind: "map" };
+ }
+ case "Date": {
+ Reflect.apply(dateTimestampGetter, current, []);
+ return { bytes: 8, kind: "date" };
+ }
+ case "Set": {
+ return { bytes: 0, kind: "set" };
+ }
+ case "Headers": {
+ return { bytes: 0, kind: "headers" };
+ }
+ default: {
+ return void 0;
+ }
+ }
+ const bytes = getter?.call(current);
+ return {
+ bytes: typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 ? bytes : Number.POSITIVE_INFINITY,
+ kind
+ };
+}
+function visitHiddenEventValues(current, kind, visit) {
+ if (kind === "map") {
+ for (const [key, entry] of mapEntries.call(current)) {
+ if (!visit(key, 8) || !visit(entry, 8)) {
+ return false;
+ }
+ }
+ }
+ if (kind === "set") {
+ for (const entry of setValues.call(current)) {
+ if (!visit(entry, 8)) {
+ return false;
+ }
+ }
+ }
+ if (kind === "headers") {
+ if (!headersEntries) {
+ return false;
+ }
+ for (const [name, value] of headersEntries.call(current)) {
+ if (!visit(name, 8) || !visit(value, 8)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+function getInspectableEventKeys(current, kind, availableBytes) {
+ if (Array.isArray(current)) {
+ const descriptor = Object.getOwnPropertyDescriptor(current, "length");
+ const length2 = descriptor && "value" in descriptor ? descriptor.value : void 0;
+ if (typeof length2 !== "number" || !Number.isSafeInteger(length2) || length2 < 0 || length2 > Math.floor(availableBytes / 16)) {
+ return void 0;
+ }
+ }
+ if (kind !== "typed-array") {
+ return Reflect.ownKeys(current);
+ }
+ const length = typedArrayLengthGetter?.call(current);
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > MAX_INSPECTABLE_TYPED_ARRAY_ELEMENTS) {
+ return void 0;
+ }
+ return Reflect.ownKeys(current).filter((key) => {
+ if (typeof key !== "string") {
+ return true;
+ }
+ const index3 = Number(key);
+ return !Number.isInteger(index3) || index3 < 0 || index3 >= length || String(index3) !== key;
+ });
+}
+function visitInspectableEventProperties(current, kind, depth, availableBytes, charge, visit) {
+ const keys = getInspectableEventKeys(current, kind, availableBytes());
+ if (keys === void 0) {
+ return false;
+ }
+ for (const key of keys) {
+ if (!charge(typeof key === "string" ? key.length * 2 + 8 : 8)) {
+ return false;
+ }
+ if (typeof key === "symbol") {
+ visit(key, depth + 1);
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
+ if (!descriptor) {
+ return false;
+ }
+ if (!("value" in descriptor)) {
+ if (key === "stack" && isTrustedNativeErrorStack(current, descriptor)) {
+ continue;
+ }
+ return false;
+ }
+ visit(descriptor.value, depth + 1, kind === "blob");
+ }
+ return true;
+}
+function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited2, availableBytes, charge, visit, retainPrototype) {
+ let prototype = Object.getPrototypeOf(current);
+ for (let prototypeDepth = depth + 1; prototype !== null; prototypeDepth += 1) {
+ if (prototypeDepth >= MAX_BUFFERED_EVENT_DEPTH) {
+ return false;
+ }
+ if (trustedIntrinsicPrototypes.has(prototype) || isBlobInternalHandle && prototype === blobInternalHandlePrototype) {
+ return true;
+ }
+ if (visited2.has(prototype)) {
+ visit(prototype, prototypeDepth);
+ return availableBytes() >= 0;
+ }
+ visited2.add(prototype);
+ const retainedPrototype = prototype;
+ const retained = retainPrototype(retainedPrototype, () => {
+ if (!charge(16)) {
+ return false;
+ }
+ const intrinsic = getTrustedForeignIntrinsic(retainedPrototype);
+ if (!intrinsic) {
+ return visitInspectableEventProperties(retainedPrototype, void 0, prototypeDepth, availableBytes, charge, visit);
+ }
+ for (const key of Reflect.ownKeys(retainedPrototype)) {
+ const descriptor = Object.getOwnPropertyDescriptor(retainedPrototype, key);
+ if (!descriptor) {
+ return false;
+ }
+ if (isCanonicalIntrinsicDescriptor(descriptor, intrinsic.descriptors.get(key), intrinsic.functionPrototype)) {
+ continue;
+ }
+ if (!charge(typeof key === "string" ? key.length * 2 + 8 : 8) || !("value" in descriptor)) {
+ return false;
+ }
+ if (typeof key === "symbol") {
+ visit(key, prototypeDepth + 1);
+ }
+ visit(descriptor.value, prototypeDepth + 1);
+ }
+ return availableBytes() >= 0;
+ });
+ if (!retained) {
+ return false;
+ }
+ prototype = Object.getPrototypeOf(retainedPrototype);
+ }
+ return true;
+}
+function inspectBufferedEventGraph(value, remainingBytes) {
+ let bytes = 0;
+ let scalarBytes = 0;
+ const visited2 = /* @__PURE__ */ new WeakSet();
+ const visitedSymbols = /* @__PURE__ */ new Set();
+ const roots = /* @__PURE__ */ new Set();
+ const nodes = /* @__PURE__ */ new Map();
+ let activeNode;
+ const availableBytes = () => remainingBytes - bytes;
+ const charge = (amount) => {
+ if (!Number.isSafeInteger(amount) || amount < 0) {
+ bytes = remainingBytes + 1;
+ return false;
+ }
+ bytes += amount;
+ if (activeNode) {
+ activeNode.bytes += amount;
+ } else {
+ scalarBytes += amount;
+ }
+ return bytes <= remainingBytes;
+ };
+ const addIdentity = (identity) => {
+ if (activeNode) {
+ activeNode.edges.add(identity);
+ } else {
+ roots.add(identity);
+ }
+ };
+ const retainIdentity = (identity, inspect) => {
+ addIdentity(identity);
+ const node = { bytes: 0, edges: /* @__PURE__ */ new Set() };
+ nodes.set(identity, node);
+ const previous = activeNode;
+ activeNode = node;
+ try {
+ return inspect();
+ } finally {
+ activeNode = previous;
+ }
+ };
+ const visitSymbol = (current) => {
+ if (visitedSymbols.has(current)) {
+ addIdentity(current);
+ charge(8);
+ return;
+ }
+ visitedSymbols.add(current);
+ if (!retainIdentity(current, () => {
+ if (!symbolDescriptionGetter) {
+ return false;
+ }
+ const description = Reflect.apply(symbolDescriptionGetter, current, []);
+ return charge(8 + (description?.length ?? 0) * 2);
+ })) {
+ bytes = remainingBytes + 1;
+ }
+ };
+ const visit = (current, depth, isBlobInternalHandle = false) => {
+ if (bytes > remainingBytes) {
+ return;
+ }
+ if (typeof current === "string") {
+ charge(current.length * 2);
+ return;
+ }
+ if (typeof current === "symbol") {
+ visitSymbol(current);
+ return;
+ }
+ if (typeof current === "function") {
+ bytes = remainingBytes + 1;
+ return;
+ }
+ if (current === null || typeof current !== "object") {
+ charge(8);
+ return;
+ }
+ if (nativeProxyDetector?.(current)) {
+ bytes = remainingBytes + 1;
+ return;
+ }
+ if (depth >= MAX_BUFFERED_EVENT_DEPTH) {
+ bytes = remainingBytes + 1;
+ return;
+ }
+ if (visited2.has(current)) {
+ addIdentity(current);
+ charge(8);
+ return;
+ }
+ visited2.add(current);
+ if (!retainIdentity(current, () => {
+ if (!charge(16)) {
+ return false;
+ }
+ const retainedStorage = estimateRetainedBufferBytes(current, visit, depth);
+ if (!visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited2, availableBytes, charge, visit, retainIdentity)) {
+ return false;
+ }
+ if (retainedStorage !== void 0 && !charge(retainedStorage.bytes)) {
+ return false;
+ }
+ if (!visitHiddenEventValues(current, retainedStorage?.kind, (hiddenValue, overhead) => {
+ if (!charge(overhead)) {
+ return false;
+ }
+ visit(hiddenValue, depth + 1);
+ return bytes <= remainingBytes;
+ })) {
+ return false;
+ }
+ return visitInspectableEventProperties(current, retainedStorage?.kind, depth, availableBytes, charge, visit);
+ })) {
+ bytes = remainingBytes + 1;
+ }
+ };
+ try {
+ visit(value, 0);
+ } catch {
+ return void 0;
+ }
+ return bytes <= remainingBytes ? { scalarBytes, roots, nodes } : void 0;
+}
+function areBufferedRetainedEdgesEqual(first, second) {
+ if (first.size !== second.size) {
+ return false;
+ }
+ for (const identity of first) {
+ if (!second.has(identity)) {
+ return false;
+ }
+ }
+ return true;
+}
+function getBufferedLedgerNodeBytes(node, owners) {
+ return node.bytes + BUFFERED_LEDGER_NODE_BYTES + node.edges.size * BUFFERED_LEDGER_EDGE_BYTES + owners * BUFFERED_LEDGER_OWNER_BYTES;
+}
+function getBufferedLedgerEntryBytes(entry) {
+ return BUFFERED_LEDGER_ENTRY_BYTES + entry.scalarBytes + entry.roots.size * BUFFERED_LEDGER_EDGE_BYTES;
+}
+function collectBufferedLedgerIdentities(roots, candidate, records, work) {
+ const identities = /* @__PURE__ */ new Set();
+ const pending = [...roots];
+ while (pending.length) {
+ work.remaining -= 1;
+ if (work.remaining < 0) {
+ return void 0;
+ }
+ const identity = pending.pop();
+ if (identities.has(identity)) {
+ continue;
+ }
+ const node = candidate.get(identity) ?? records.get(identity);
+ if (!node) {
+ return void 0;
+ }
+ identities.add(identity);
+ for (const edge of node.edges) {
+ pending.push(edge);
+ }
+ }
+ return identities;
+}
+function getBufferedLedgerChange(identity, graph, records, changes, node) {
+ const existing = changes.get(identity);
+ if (existing) {
+ if (node) {
+ existing.node = node;
+ }
+ return existing;
+ }
+ const current = node ?? graph.nodes.get(identity) ?? records.get(identity);
+ if (!current) {
+ return void 0;
+ }
+ const update = { node: current, ownerDelta: 0 };
+ changes.set(identity, update);
+ return update;
+}
+function findBufferedLedgerAffectedOwners(entry, graph, records, changes, work) {
+ const affected = /* @__PURE__ */ new Set([entry]);
+ for (const [identity, node] of graph.nodes) {
+ work.remaining -= 1;
+ if (work.remaining < 0) {
+ return void 0;
+ }
+ const previous = records.get(identity);
+ if (!previous) {
+ continue;
+ }
+ const changedEdges = !areBufferedRetainedEdgesEqual(previous.edges, node.edges);
+ if (previous.bytes !== node.bytes || changedEdges) {
+ getBufferedLedgerChange(identity, graph, records, changes, node);
+ }
+ if (!changedEdges) {
+ continue;
+ }
+ for (const owner of previous.owners) {
+ work.remaining -= 1;
+ if (work.remaining < 0) {
+ return void 0;
+ }
+ affected.add(owner);
+ }
+ }
+ return affected;
+}
+function updateBufferedLedgerMembershipChanges(owner, next, graph, records, changes, work) {
+ for (const identity of owner.identities) {
+ work.remaining -= 1;
+ if (work.remaining < 0) {
+ return false;
+ }
+ if (!next.has(identity)) {
+ const update = getBufferedLedgerChange(identity, graph, records, changes);
+ if (!update) {
+ return false;
+ }
+ update.ownerDelta -= 1;
+ }
+ }
+ for (const identity of next) {
+ work.remaining -= 1;
+ if (work.remaining < 0) {
+ return false;
+ }
+ if (!owner.identities.has(identity)) {
+ const update = getBufferedLedgerChange(identity, graph, records, changes);
+ if (!update) {
+ return false;
+ }
+ update.ownerDelta += 1;
+ }
+ }
+ return true;
+}
+function collectBufferedLedgerMemberships(entry, graph, affected, records, changes, work) {
+ const memberships = /* @__PURE__ */ new Map();
+ for (const owner of affected) {
+ const roots = owner === entry ? graph.roots : owner.roots;
+ const next = collectBufferedLedgerIdentities(roots, graph.nodes, records, work);
+ if (!next || !updateBufferedLedgerMembershipChanges(owner, next, graph, records, changes, work)) {
+ return void 0;
+ }
+ memberships.set(owner, next);
+ }
+ return memberships;
+}
+function projectBufferedLedgerBytes(currentBytes, entry, graph, isNew, changes, records) {
+ let projected = currentBytes - (isNew ? 0 : getBufferedLedgerEntryBytes(entry)) + getBufferedLedgerEntryBytes(graph);
+ for (const [identity, update] of changes) {
+ const previous = records.get(identity);
+ const owners = (previous?.owners.size ?? 0) + update.ownerDelta;
+ if (owners < 0) {
+ return void 0;
+ }
+ if (previous) {
+ projected -= getBufferedLedgerNodeBytes(previous, previous.owners.size);
+ }
+ if (owners) {
+ projected += getBufferedLedgerNodeBytes(update.node, owners);
+ }
+ }
+ return Number.isSafeInteger(projected) && projected >= 0 && projected <= MAX_BUFFERED_ITERATOR_BYTES ? projected : void 0;
+}
+function applyBufferedLedgerChanges(records, changes, memberships) {
+ for (const [identity, update] of changes) {
+ const previous = records.get(identity);
+ const owners = (previous?.owners.size ?? 0) + update.ownerDelta;
+ if (!owners) {
+ continue;
+ }
+ if (previous) {
+ previous.bytes = update.node.bytes;
+ previous.edges = update.node.edges;
+ } else {
+ records.set(identity, {
+ bytes: update.node.bytes,
+ edges: update.node.edges,
+ owners: /* @__PURE__ */ new Set()
+ });
+ }
+ }
+ for (const [owner, next] of memberships) {
+ for (const identity of owner.identities) {
+ if (!next.has(identity)) {
+ records.get(identity)?.owners.delete(owner);
+ }
+ }
+ for (const identity of next) {
+ if (!owner.identities.has(identity)) {
+ records.get(identity).owners.add(owner);
+ }
+ }
+ owner.identities = next;
+ }
+ for (const identity of changes.keys()) {
+ if (records.get(identity)?.owners.size === 0) {
+ records.delete(identity);
+ }
+ }
+}
+function createBufferedEventLedger() {
+ const records = /* @__PURE__ */ new Map();
+ let bytes = 0;
+ const reconcile = (entry, graph, isNew) => {
+ const work = { remaining: MAX_BUFFERED_LEDGER_RECONCILIATION_WORK };
+ const changes = /* @__PURE__ */ new Map();
+ const affected = findBufferedLedgerAffectedOwners(entry, graph, records, changes, work);
+ if (!affected) {
+ return false;
+ }
+ const memberships = collectBufferedLedgerMemberships(entry, graph, affected, records, changes, work);
+ if (!memberships) {
+ return false;
+ }
+ const projectedBytes = projectBufferedLedgerBytes(bytes, entry, graph, isNew, changes, records);
+ if (projectedBytes === void 0) {
+ return false;
+ }
+ applyBufferedLedgerChanges(records, changes, memberships);
+ entry.scalarBytes = graph.scalarBytes;
+ entry.roots = graph.roots;
+ bytes = projectedBytes;
+ return true;
+ };
+ const release = (entry) => {
+ bytes -= getBufferedLedgerEntryBytes(entry);
+ for (const identity of entry.identities) {
+ const record = records.get(identity);
+ if (!record?.owners.delete(entry)) {
+ continue;
+ }
+ bytes -= BUFFERED_LEDGER_OWNER_BYTES;
+ if (record.owners.size === 0) {
+ bytes -= getBufferedLedgerNodeBytes(record, 0);
+ records.delete(identity);
+ }
+ }
+ entry.identities.clear();
+ };
+ return {
+ retain(graph) {
+ const entry = { scalarBytes: 0, roots: /* @__PURE__ */ new Set(), identities: /* @__PURE__ */ new Set() };
+ return reconcile(entry, graph, true) ? entry : void 0;
+ },
+ refresh(entry, graph) {
+ return reconcile(entry, graph, false);
+ },
+ release,
+ clear() {
+ records.clear();
+ bytes = 0;
+ }
+ };
+}
+var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_abortListeners, _EventStream_emittedListenerRegistrations, _EventStream_pendingListenerCleanup, _EventStream_pendingBufferedEventChecks, _EventStream_listenerDispatchDepth, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_terminalFailure, _EventStream_abortFromSignal, _EventStream_removeAbortListeners, _EventStream_onceForEmitted, _EventStream_removeEmittedListener, _EventStream_cleanupEmittedListeners, _EventStream_handleError, _EventStream_settleTerminalEvent, MAX_BUFFERED_ITERATOR_EVENTS, MAX_BUFFERED_ITERATOR_BYTES, MAX_INSPECTABLE_TYPED_ARRAY_ELEMENTS, MAX_BUFFERED_EVENT_DEPTH, bufferedJSONStringify, bufferedJSONParse, sdkOwnedBufferedEventArguments, typedArrayBufferGetter, typedArrayLengthGetter, dataViewBufferGetter, symbolDescriptionGetter, dateTimestampGetter, arrayBufferByteLengthGetter2, sharedArrayBufferByteLengthGetter, errorStackDescriptor, functionToString, objectToString, errorBrandDescriptor, nativeErrorBrand, nativeErrorConstructorSource, nativeDateConstructorSource, nativeFunctionConstructorSource, trustedIntrinsicPrototypes, trustedNativeConstructorSources, canonicalIntrinsicDescriptors, foreignErrorStackDescriptors, nativeProxyDetector, typedArrayConstructorDescriptor, blobInternalHandlePrototype, mapEntries, setValues, headersEntriesDescriptor, headersEntries, retainedStorageBrands, BUFFERED_LEDGER_ENTRY_BYTES, BUFFERED_LEDGER_NODE_BYTES, BUFFERED_LEDGER_EDGE_BYTES, BUFFERED_LEDGER_OWNER_BYTES, MAX_BUFFERED_LEDGER_RECONCILIATION_WORK, EventStream2;
+var init_EventStream = __esm({
+ "node_modules/openai/lib/EventStream.mjs"() {
+ init_tslib();
+ init_error2();
+ MAX_BUFFERED_ITERATOR_EVENTS = 4096;
+ MAX_BUFFERED_ITERATOR_BYTES = 8 * 1024 * 1024;
+ MAX_INSPECTABLE_TYPED_ARRAY_ELEMENTS = 4096;
+ MAX_BUFFERED_EVENT_DEPTH = 256;
+ bufferedJSONStringify = JSON.stringify;
+ bufferedJSONParse = JSON.parse;
+ sdkOwnedBufferedEventArguments = /* @__PURE__ */ new WeakSet();
+ typedArrayBufferGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "buffer")?.get;
+ typedArrayLengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length")?.get;
+ dataViewBufferGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "buffer")?.get;
+ symbolDescriptionGetter = Object.getOwnPropertyDescriptor(Symbol.prototype, "description")?.get;
+ dateTimestampGetter = Date.prototype.getTime;
+ arrayBufferByteLengthGetter2 = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")?.get;
+ sharedArrayBufferByteLengthGetter = typeof SharedArrayBuffer === "function" ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength")?.get : void 0;
+ errorStackDescriptor = Object.getOwnPropertyDescriptor(new Error("native stack descriptor"), "stack");
+ functionToString = Function.prototype.toString;
+ objectToString = Object.prototype.toString;
+ errorBrandDescriptor = Object.getOwnPropertyDescriptor(Error, "isError");
+ nativeErrorBrand = errorBrandDescriptor && "value" in errorBrandDescriptor && typeof errorBrandDescriptor.value === "function" ? errorBrandDescriptor.value : void 0;
+ nativeErrorConstructorSource = functionToString.call(Error);
+ nativeDateConstructorSource = functionToString.call(Date);
+ nativeFunctionConstructorSource = functionToString.call(Function);
+ trustedIntrinsicPrototypes = /* @__PURE__ */ new Set([
+ APIConnectionError.prototype,
+ APIConnectionTimeoutError.prototype,
+ APIError.prototype,
+ OpenAIError.prototype,
+ APIUserAbortError.prototype,
+ AuthenticationError.prototype,
+ BadRequestError.prototype,
+ ConflictError.prototype,
+ ContentFilterFinishReasonError.prototype,
+ InternalServerError.prototype,
+ InvalidWebhookSignatureError.prototype,
+ LengthFinishReasonError.prototype,
+ NotFoundError.prototype,
+ OAuthError.prototype,
+ PermissionDeniedError.prototype,
+ RateLimitError.prototype,
+ SubjectTokenProviderError.prototype,
+ UnprocessableEntityError.prototype
+ ]);
+ trustedNativeConstructorSources = /* @__PURE__ */ new Set();
+ canonicalIntrinsicDescriptors = /* @__PURE__ */ new Map();
+ foreignErrorStackDescriptors = /* @__PURE__ */ new WeakMap();
+ nativeProxyDetector = captureNativeProxyDetector();
+ for (const constructor of [
+ Object,
+ Function,
+ Array,
+ Date,
+ Map,
+ Set,
+ ArrayBuffer,
+ DataView,
+ Error,
+ EvalError,
+ RangeError,
+ ReferenceError,
+ SyntaxError,
+ TypeError,
+ URIError,
+ Uint8Array,
+ Uint8ClampedArray,
+ Uint16Array,
+ Uint32Array,
+ Int8Array,
+ Int16Array,
+ Int32Array,
+ Float32Array,
+ Float64Array
+ ]) {
+ rememberTrustedIntrinsic(constructor);
+ }
+ for (const name of [
+ "SharedArrayBuffer",
+ "AggregateError",
+ "Float16Array",
+ "BigInt64Array",
+ "BigUint64Array",
+ "Blob",
+ "File",
+ "Headers"
+ ]) {
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, name);
+ if (descriptor && "value" in descriptor) {
+ rememberTrustedIntrinsic(descriptor.value);
+ }
+ }
+ typedArrayConstructorDescriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "constructor");
+ if (typedArrayConstructorDescriptor && "value" in typedArrayConstructorDescriptor) {
+ rememberTrustedIntrinsic(typedArrayConstructorDescriptor.value);
+ }
+ if (typeof Buffer === "function") {
+ rememberTrustedIntrinsic(Buffer);
+ }
+ blobInternalHandlePrototype = (() => {
+ if (typeof Blob !== "function") {
+ return void 0;
+ }
+ try {
+ const blob = new Blob([]);
+ for (const key of Object.getOwnPropertySymbols(blob)) {
+ const descriptor = Object.getOwnPropertyDescriptor(blob, key);
+ if (descriptor && "value" in descriptor && typeof descriptor.value === "object" && descriptor.value) {
+ return Object.getPrototypeOf(descriptor.value);
+ }
+ }
+ } catch {
+ return void 0;
+ }
+ return void 0;
+ })();
+ mapEntries = Map.prototype.entries;
+ setValues = Set.prototype.values;
+ headersEntriesDescriptor = typeof Headers === "function" ? Object.getOwnPropertyDescriptor(Headers.prototype, "entries") : void 0;
+ headersEntries = headersEntriesDescriptor && "value" in headersEntriesDescriptor && typeof headersEntriesDescriptor.value === "function" ? headersEntriesDescriptor.value : void 0;
+ retainedStorageBrands = /* @__PURE__ */ new Set([
+ "ArrayBuffer",
+ "SharedArrayBuffer",
+ "Blob",
+ "File",
+ "Map",
+ "Date",
+ "Set",
+ "Headers"
+ ]);
+ BUFFERED_LEDGER_ENTRY_BYTES = 32;
+ BUFFERED_LEDGER_NODE_BYTES = 32;
+ BUFFERED_LEDGER_EDGE_BYTES = 8;
+ BUFFERED_LEDGER_OWNER_BYTES = 16;
+ MAX_BUFFERED_LEDGER_RECONCILIATION_WORK = 128 * 1024;
+ EventStream2 = class {
+ /** Creates an unstarted stream with independent connection and completion lifecycle promises. */
+ constructor() {
+ _EventStream_instances.add(this);
+ this.controller = new AbortController();
+ _EventStream_connectedPromise.set(this, void 0);
+ _EventStream_resolveConnectedPromise.set(this, () => void 0);
+ _EventStream_rejectConnectedPromise.set(this, () => void 0);
+ _EventStream_endPromise.set(this, void 0);
+ _EventStream_resolveEndPromise.set(this, () => void 0);
+ _EventStream_rejectEndPromise.set(this, () => void 0);
+ _EventStream_listeners.set(this, /* @__PURE__ */ Object.create(null));
+ _EventStream_abortListeners.set(this, []);
+ _EventStream_emittedListenerRegistrations.set(this, /* @__PURE__ */ new WeakMap());
+ _EventStream_pendingListenerCleanup.set(this, /* @__PURE__ */ new Set());
+ _EventStream_pendingBufferedEventChecks.set(this, /* @__PURE__ */ new Set());
+ _EventStream_listenerDispatchDepth.set(this, 0);
+ _EventStream_ended.set(this, false);
+ _EventStream_errored.set(this, false);
+ _EventStream_aborted.set(this, false);
+ _EventStream_catchingPromiseCreated.set(this, false);
+ _EventStream_terminalFailure.set(this, void 0);
+ __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve3, reject) => {
+ __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve3, "f");
+ __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f");
+ }), "f");
+ __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve3, reject) => {
+ __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve3, "f");
+ __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f");
+ }), "f");
+ __classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => void 0);
+ __classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => void 0);
+ }
+ _run(executor) {
+ setTimeout(() => {
+ let failed = false;
+ Promise.resolve().then(executor).catch((error) => {
+ failed = true;
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error);
+ }).then(() => {
+ if (failed) {
+ return;
+ }
+ try {
+ this._emitFinal();
+ } catch (error) {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error);
+ return;
+ }
+ this._emit("end");
+ });
+ }, 0);
+ }
+ _connected() {
+ if (this.ended) {
+ return;
+ }
+ __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this);
+ this._emit("connect");
+ }
+ /** Whether the stream has finished successfully, failed, or been aborted. */
+ get ended() {
+ return __classPrivateFieldGet(this, _EventStream_ended, "f");
+ }
+ /** Whether an error or user cancellation has been observed. */
+ get errored() {
+ return __classPrivateFieldGet(this, _EventStream_errored, "f");
+ }
+ /** Whether the stream ended because its request was cancelled. */
+ get aborted() {
+ return __classPrivateFieldGet(this, _EventStream_aborted, "f");
+ }
+ /**
+ * Cancels the underlying request; {@link done} and {@link events} observe cancellation.
+ * Promises returned by {@link emitted} for other events may remain pending.
+ */
+ abort() {
+ this.controller.abort();
+ }
+ /** Creates a user-abort error retaining this runner's cancellation reason. */
+ _userAbortError() {
+ const error = new APIUserAbortError();
+ Object.defineProperty(error, "cause", {
+ value: this.controller.signal.reason,
+ writable: true,
+ configurable: true
+ });
+ return error;
+ }
+ _listenForAbort(signal) {
+ if (!signal || this.ended) {
+ return;
+ }
+ if (signal.aborted) {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_abortFromSignal).call(this, signal);
+ return;
+ }
+ if (__classPrivateFieldGet(this, _EventStream_abortListeners, "f").some((registration) => registration.signal === signal)) {
+ return;
+ }
+ const listener = () => __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_abortFromSignal).call(this, signal);
+ signal.addEventListener("abort", listener, { once: true });
+ __classPrivateFieldGet(this, _EventStream_abortListeners, "f").push({ signal, listener });
+ }
+ /**
+ * Adds the listener function to the end of the listeners array for the event.
+ * No checks are made to see if the listener has already been added. Multiple calls passing
+ * the same combination of event and listener will result in the listener being added, and
+ * called, multiple times.
+ * @returns This stream, so that listener registration calls can be chained.
+ */
+ on(event, listener) {
+ var _a5;
+ const listeners = (_a5 = __classPrivateFieldGet(this, _EventStream_listeners, "f"))[event] || (_a5[event] = []);
+ listeners.push({ listener });
+ return this;
+ }
+ /**
+ * Removes the specified listener from the listener array for the event.
+ * off() will remove, at most, one instance of a listener from the listener array. If any single
+ * listener has been added multiple times to the listener array for the specified event, then
+ * off() must be called multiple times to remove each instance.
+ * @returns This stream, so that listener registration calls can be chained.
+ */
+ off(event, listener) {
+ const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
+ if (!listeners) {
+ return this;
+ }
+ const emittedRegistration = __classPrivateFieldGet(this, _EventStream_emittedListenerRegistrations, "f").get(listener);
+ if (emittedRegistration?.event === event && !emittedRegistration.registration.removed && !emittedRegistration.registration.detached) {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_removeEmittedListener).call(this, event, emittedRegistration.registration);
+ return this;
+ }
+ const index3 = listeners.findIndex((l) => !l.removed && l.listener === listener);
+ if (index3 !== -1) {
+ listeners.splice(index3, 1);
+ }
+ return this;
+ }
+ /**
+ * Adds a one-time listener function for the event. The next time the event is triggered,
+ * this listener is removed and then invoked.
+ * @returns This stream, so that listener registration calls can be chained.
+ */
+ once(event, listener) {
+ var _a5;
+ const listeners = (_a5 = __classPrivateFieldGet(this, _EventStream_listeners, "f"))[event] || (_a5[event] = []);
+ listeners.push({ listener, once: true });
+ return this;
+ }
+ /**
+ * This is similar to `.once()`, but returns a Promise that resolves the next time
+ * the event is triggered, instead of calling a listener callback.
+ * Events without arguments resolve to `undefined`, single-argument events resolve
+ * to that argument, and events with multiple arguments resolve to an argument tuple.
+ *
+ * @returns A promise for the next event, or a rejection if an error occurs first.
+ * Requesting the `error` event resolves with the emitted error instead.
+ *
+ * Example:
+ *
+ * const message = await stream.emitted('message') // rejects if the stream errors
+ */
+ emitted(event) {
+ return new Promise((resolve3, reject) => {
+ __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
+ const onError = (error) => {
+ this.off(event, onEvent);
+ reject(error);
+ };
+ const onEvent = (...values) => {
+ if (event !== "error") {
+ this.off("error", onError);
+ }
+ resolve3(values.length > 1 ? values : values[0]);
+ };
+ if (event !== "error") {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_onceForEmitted).call(this, "error", onError);
+ }
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_onceForEmitted).call(this, event, onEvent);
+ });
+ }
+ /**
+ * Returns an async iterator that yields every time the event is triggered.
+ * The iterator ends when the stream ends and rejects if the stream errors
+ * or is aborted. If you request the 'error' or 'abort' event, the iterator
+ * yields that event instead of rejecting.
+ *
+ * Example:
+ *
+ * for await (const [message] of stream.events('message')) {
+ * await processMessage(message);
+ * }
+ */
+ events(event) {
+ return this._createIterator((push) => {
+ const onEvent = (...args) => {
+ sdkOwnedBufferedEventArguments.add(args);
+ try {
+ push(args);
+ } finally {
+ sdkOwnedBufferedEventArguments.delete(args);
+ }
+ };
+ this.on(event, onEvent);
+ return () => this.off(event, onEvent);
+ }, {
+ // When iterating the 'error' or 'abort' event itself, yield it as a
+ // value instead of rejecting the iterator.
+ rejectOnError: event !== "error",
+ rejectOnAbort: event !== "abort"
+ });
+ }
+ /**
+ * Shared buffered async-iterator adapter over this stream's events.
+ *
+ * `attach` registers the producer listener(s) with the given `push` and
+ * returns a cleanup function that removes them. Termination is handled
+ * here: the iterator ends when the stream ends, listeners are removed on
+ * end/return, and a terminal error is retained until buffered values have
+ * drained so it is surfaced even when no reader was waiting when it fired.
+ * Detached consumers have bounded event and byte queues; exceeding either
+ * limit fails the stream and aborts its underlying request. Detached queues
+ * also reject accessor-backed payloads because getter closures cannot be
+ * safely sized without executing untrusted code.
+ */
+ _createIterator(attach, { rejectOnError = true, rejectOnAbort = true, onReturn } = {}) {
+ const pushQueue = createEventQueue();
+ const bufferedEventSizes = createEventQueue();
+ const readQueue = createEventQueue();
+ const bufferedLedger = createBufferedEventLedger();
+ let ended = this.ended;
+ let failure;
+ let failureDelivered = false;
+ let detach = () => void 0;
+ const doneResult = () => ({ value: void 0, done: true });
+ const finishReaders = () => {
+ while (readQueue.length) {
+ readQueue.dequeue().resolve(doneResult());
+ }
+ };
+ const rejectReader = () => {
+ if (!failure || failureDelivered || !readQueue.length) {
+ return;
+ }
+ failureDelivered = true;
+ readQueue.dequeue().reject(failure);
+ };
+ const cleanup = () => {
+ detach();
+ this.off("end", onEnd);
+ if (rejectOnError) {
+ this.off("error", onFailure);
+ }
+ if (rejectOnAbort) {
+ this.off("abort", onFailure);
+ }
+ };
+ const deactivateBufferedEvent = (entry) => {
+ entry.active = false;
+ if (entry.check) {
+ __classPrivateFieldGet(this, _EventStream_pendingBufferedEventChecks, "f").delete(entry.check);
+ entry.check = void 0;
+ }
+ };
+ const failBufferedEvents = (discardRetained = false) => {
+ if (discardRetained) {
+ while (bufferedEventSizes.length) {
+ deactivateBufferedEvent(bufferedEventSizes.dequeue());
+ }
+ pushQueue.clear();
+ bufferedLedger.clear();
+ }
+ const error = new OpenAIError(`Event stream iterator buffer limit exceeded (${MAX_BUFFERED_ITERATOR_EVENTS} events or ${MAX_BUFFERED_ITERATOR_BYTES} bytes); consume events as they arrive.`);
+ try {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error);
+ } finally {
+ this.controller.abort();
+ }
+ return error;
+ };
+ const revalidateBufferedEvent = (value, entry) => {
+ if (!entry.active || __classPrivateFieldGet(this, _EventStream_ended, "f")) {
+ return;
+ }
+ const graph = inspectBufferedEventGraph(value, MAX_BUFFERED_ITERATOR_BYTES);
+ if (!graph || !bufferedLedger.refresh(entry.retention, graph)) {
+ failBufferedEvents(true);
+ }
+ };
+ const push = (value) => {
+ if (ended) {
+ return;
+ }
+ const reader = readQueue.dequeue();
+ if (reader) {
+ reader.resolve({ value, done: false });
+ } else {
+ if (pushQueue.length >= MAX_BUFFERED_ITERATOR_EVENTS) {
+ failBufferedEvents();
+ return;
+ }
+ const graph = inspectBufferedEventGraph(value, MAX_BUFFERED_ITERATOR_BYTES);
+ const retention = graph && bufferedLedger.retain(graph);
+ if (!retention) {
+ failBufferedEvents();
+ return;
+ }
+ if (typeof value === "object" && value !== null && sdkOwnedBufferedEventArguments.has(value)) {
+ const argumentsTuple = value;
+ for (let index3 = 0; index3 < argumentsTuple.length; index3 += 1) {
+ const argument = argumentsTuple[index3];
+ if (typeof argument === "string") {
+ argumentsTuple[index3] = bufferedJSONParse(bufferedJSONStringify(argument));
+ }
+ }
+ }
+ const entry = { retention, active: true, check: void 0 };
+ pushQueue.enqueue(value);
+ bufferedEventSizes.enqueue(entry);
+ const check = () => {
+ entry.check = void 0;
+ revalidateBufferedEvent(value, entry);
+ };
+ entry.check = check;
+ __classPrivateFieldGet(this, _EventStream_pendingBufferedEventChecks, "f").add(check);
+ }
+ };
+ const onFailure = (error) => {
+ failure = error;
+ if (!pushQueue.length) {
+ rejectReader();
+ }
+ };
+ const adoptTerminalFailure = () => {
+ if (failure) {
+ return;
+ }
+ const terminal = __classPrivateFieldGet(this, _EventStream_terminalFailure, "f");
+ if (!terminal) {
+ return;
+ }
+ if (terminal.kind === "error" ? rejectOnError : rejectOnAbort) {
+ failure = terminal.error;
+ }
+ };
+ const onEnd = () => {
+ ended = true;
+ adoptTerminalFailure();
+ cleanup();
+ if (!pushQueue.length) {
+ rejectReader();
+ finishReaders();
+ }
+ };
+ if (!ended) {
+ detach = attach(push);
+ this.on("end", onEnd);
+ if (rejectOnError) {
+ this.on("error", onFailure);
+ }
+ if (rejectOnAbort) {
+ this.on("abort", onFailure);
+ }
+ }
+ return {
+ next: () => {
+ if (pushQueue.length) {
+ const value = pushQueue.dequeue();
+ const entry = bufferedEventSizes.dequeue();
+ deactivateBufferedEvent(entry);
+ const graph = inspectBufferedEventGraph(value, MAX_BUFFERED_ITERATOR_BYTES);
+ if (!graph || !bufferedLedger.refresh(entry.retention, graph)) {
+ const error = failBufferedEvents(true);
+ failureDelivered = true;
+ return Promise.reject(error);
+ }
+ bufferedLedger.release(entry.retention);
+ return Promise.resolve({ value, done: false });
+ }
+ if (ended || this.ended) {
+ adoptTerminalFailure();
+ }
+ if (failure && !failureDelivered) {
+ failureDelivered = true;
+ return Promise.reject(failure);
+ }
+ if (ended) {
+ return Promise.resolve(doneResult());
+ }
+ return new Promise((resolve3, reject) => {
+ readQueue.enqueue({ resolve: resolve3, reject });
+ });
+ },
+ return: () => {
+ ended = true;
+ failureDelivered = true;
+ while (bufferedEventSizes.length) {
+ deactivateBufferedEvent(bufferedEventSizes.dequeue());
+ }
+ pushQueue.clear();
+ bufferedLedger.clear();
+ cleanup();
+ finishReaders();
+ if (onReturn) {
+ void this.done().catch(() => void 0);
+ onReturn();
+ }
+ return Promise.resolve(doneResult());
+ },
+ [Symbol.asyncIterator]() {
+ return this;
+ }
+ };
+ }
+ /** Resolves when the stream ends successfully or rejects when it fails or is aborted. */
+ async done() {
+ __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
+ await __classPrivateFieldGet(this, _EventStream_endPromise, "f");
+ }
+ /** Returns whether an event currently has one or more registered listeners. */
+ _hasListeners(event) {
+ return Boolean(__classPrivateFieldGet(this, _EventStream_listeners, "f")[event]?.some((listener) => !listener.removed));
+ }
+ /** Dispatches a stream event and performs the associated lifecycle transitions. */
+ _emit(event, ...args) {
+ if (__classPrivateFieldGet(this, _EventStream_ended, "f")) {
+ return;
+ }
+ if (event === "end") {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_removeAbortListeners).call(this);
+ __classPrivateFieldSet(this, _EventStream_ended, true, "f");
+ __classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this);
+ }
+ const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
+ let dispatchError;
+ let dispatchThrew = false;
+ try {
+ if (listeners) {
+ __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((listener) => {
+ if (listener.once) {
+ listener.detached = true;
+ }
+ return !listener.once && !listener.removed;
+ });
+ __classPrivateFieldSet(this, _EventStream_listenerDispatchDepth, __classPrivateFieldGet(this, _EventStream_listenerDispatchDepth, "f") + 1, "f");
+ try {
+ for (const registration of listeners) {
+ if (!registration.removed) {
+ const { listener } = registration;
+ listener(...args);
+ }
+ }
+ } finally {
+ __classPrivateFieldSet(this, _EventStream_listenerDispatchDepth, __classPrivateFieldGet(this, _EventStream_listenerDispatchDepth, "f") - 1, "f");
+ if (__classPrivateFieldGet(this, _EventStream_listenerDispatchDepth, "f") === 0) {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_cleanupEmittedListeners).call(this);
+ for (const check of __classPrivateFieldGet(this, _EventStream_pendingBufferedEventChecks, "f")) {
+ __classPrivateFieldGet(this, _EventStream_pendingBufferedEventChecks, "f").delete(check);
+ if (!__classPrivateFieldGet(this, _EventStream_ended, "f")) {
+ check();
+ }
+ }
+ }
+ }
+ }
+ } catch (error) {
+ dispatchError = error;
+ dispatchThrew = true;
+ }
+ try {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_settleTerminalEvent).call(this, event, args, Boolean(listeners?.length));
+ } catch (error) {
+ if (!dispatchThrew) {
+ dispatchError = error;
+ dispatchThrew = true;
+ }
+ }
+ if (dispatchThrew) {
+ throw dispatchError;
+ }
+ }
+ // oxlint-disable-next-line class-methods-use-this -- Subclasses override this instance hook.
+ _emitFinal() {
+ }
+ };
+ _EventStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_endPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_listeners = /* @__PURE__ */ new WeakMap(), _EventStream_abortListeners = /* @__PURE__ */ new WeakMap(), _EventStream_emittedListenerRegistrations = /* @__PURE__ */ new WeakMap(), _EventStream_pendingListenerCleanup = /* @__PURE__ */ new WeakMap(), _EventStream_pendingBufferedEventChecks = /* @__PURE__ */ new WeakMap(), _EventStream_listenerDispatchDepth = /* @__PURE__ */ new WeakMap(), _EventStream_ended = /* @__PURE__ */ new WeakMap(), _EventStream_errored = /* @__PURE__ */ new WeakMap(), _EventStream_aborted = /* @__PURE__ */ new WeakMap(), _EventStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _EventStream_terminalFailure = /* @__PURE__ */ new WeakMap(), _EventStream_instances = /* @__PURE__ */ new WeakSet(), _EventStream_abortFromSignal = function _EventStream_abortFromSignal2(signal) {
+ try {
+ this.controller.abort(signal.reason);
+ } catch {
+ this.controller.abort();
+ }
+ }, _EventStream_removeAbortListeners = function _EventStream_removeAbortListeners2() {
+ for (const { signal, listener } of __classPrivateFieldGet(this, _EventStream_abortListeners, "f").splice(0)) {
+ signal.removeEventListener("abort", listener);
+ }
+ }, _EventStream_onceForEmitted = function _EventStream_onceForEmitted2(event, listener) {
+ const previousListeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
+ const previousLength = previousListeners?.length ?? 0;
+ this.once(event, listener);
+ const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
+ const [registration] = listeners?.slice(-1) ?? [];
+ if ((previousListeners === void 0 || listeners === previousListeners) && listeners?.length === previousLength + 1 && registration?.listener === listener && registration.once) {
+ __classPrivateFieldGet(this, _EventStream_emittedListenerRegistrations, "f").set(listener, { event, registration });
+ }
+ }, _EventStream_removeEmittedListener = function _EventStream_removeEmittedListener2(event, registration) {
+ if (registration.removed) {
+ return;
+ }
+ registration.removed = true;
+ __classPrivateFieldGet(this, _EventStream_emittedListenerRegistrations, "f").delete(registration.listener);
+ __classPrivateFieldGet(this, _EventStream_pendingListenerCleanup, "f").add(event);
+ if (__classPrivateFieldGet(this, _EventStream_listenerDispatchDepth, "f") === 0) {
+ __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_cleanupEmittedListeners).call(this);
+ }
+ }, _EventStream_cleanupEmittedListeners = function _EventStream_cleanupEmittedListeners2() {
+ for (const event of __classPrivateFieldGet(this, _EventStream_pendingListenerCleanup, "f")) {
+ const eventType = event;
+ const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[eventType];
+ if (listeners) {
+ __classPrivateFieldGet(this, _EventStream_listeners, "f")[eventType] = listeners.filter((listener) => !listener.removed);
+ }
+ }
+ __classPrivateFieldGet(this, _EventStream_pendingListenerCleanup, "f").clear();
+ }, _EventStream_handleError = function _EventStream_handleError2(error) {
+ __classPrivateFieldSet(this, _EventStream_errored, true, "f");
+ if (error instanceof Error && error.name === "AbortError") {
+ error = this._userAbortError();
+ }
+ if (error instanceof APIUserAbortError) {
+ __classPrivateFieldSet(this, _EventStream_aborted, true, "f");
+ return this._emit("abort", error);
+ }
+ if (error instanceof OpenAIError) {
+ return this._emit("error", error);
+ }
+ if (error instanceof Error) {
+ const openAIError = new OpenAIError(error.message);
+ openAIError.cause = error;
+ return this._emit("error", openAIError);
+ }
+ return this._emit("error", new OpenAIError(String(error)));
+ }, _EventStream_settleTerminalEvent = function _EventStream_settleTerminalEvent2(event, args, hasListeners) {
+ if (event === "abort") {
+ const error = args[0];
+ __classPrivateFieldSet(this, _EventStream_terminalFailure, __classPrivateFieldGet(this, _EventStream_terminalFailure, "f") ?? { kind: "abort", error }, "f");
+ if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !hasListeners) {
+ Promise.reject(error);
+ }
+ __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
+ __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error);
+ this._emit("end");
+ return;
+ }
+ if (event === "error") {
+ const error = args[0];
+ __classPrivateFieldSet(this, _EventStream_terminalFailure, __classPrivateFieldGet(this, _EventStream_terminalFailure, "f") ?? { kind: "error", error }, "f");
+ if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !hasListeners) {
+ Promise.reject(error);
+ }
+ __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
+ __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error);
+ this._emit("end");
+ }
+ };
+ }
+});
+
+// node_modules/openai/lib/RunnableFunction.mjs
+function isRunnableFunctionWithParse(fn) {
+ return typeof fn.parse === "function";
+}
+var init_RunnableFunction = __esm({
+ "node_modules/openai/lib/RunnableFunction.mjs"() {
+ }
+});
+
+// node_modules/openai/lib/AbstractChatCompletionRunner.mjs
+function normalizeToolCallIds(chatCompletion) {
+ for (const choice of chatCompletion.choices) {
+ for (const toolCall of choice.message.tool_calls ?? []) {
+ if (!toolCall.id) {
+ toolCall.id = `call_${uuid4()}`;
+ }
+ }
+ }
+}
+function toRequestMessage(message) {
+ if (!isAssistantMessage(message)) {
+ return message;
+ }
+ const requestMessage = { role: "assistant" };
+ if (message.audio != null) {
+ requestMessage.audio = { id: message.audio.id };
+ }
+ if (message.content !== void 0) {
+ requestMessage.content = message.content;
+ }
+ if (message.function_call != null) {
+ requestMessage.function_call = message.function_call;
+ }
+ if (message.name !== void 0) {
+ requestMessage.name = message.name;
+ }
+ if (message.refusal != null) {
+ requestMessage.refusal = message.refusal;
+ }
+ if (message.tool_calls !== void 0) {
+ requestMessage.tool_calls = message.tool_calls.map((toolCall) => {
+ if (toolCall.type === "custom") {
+ return {
+ id: toolCall.id,
+ type: toolCall.type,
+ custom: {
+ input: toolCall.custom.input,
+ name: toolCall.custom.name
+ }
+ };
+ }
+ return {
+ id: toolCall.id,
+ type: toolCall.type,
+ function: {
+ arguments: toolCall.function.arguments,
+ name: toolCall.function.name
+ }
+ };
+ });
+ }
+ return requestMessage;
+}
+var _AbstractChatCompletionRunner_instances, _a2, _AbstractChatCompletionRunner_completionArrivedBeforeAbort, _AbstractChatCompletionRunner_afterCompletionInvoked, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_throwIfAborted, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult, DEFAULT_MAX_CHAT_COMPLETIONS, AbstractChatCompletionRunner;
+var init_AbstractChatCompletionRunner = __esm({
+ "node_modules/openai/lib/AbstractChatCompletionRunner.mjs"() {
+ init_tslib();
+ init_error2();
+ init_uuid();
+ init_parser();
+ init_chatCompletionUtils();
+ init_EventStream();
+ init_RunnableFunction();
+ DEFAULT_MAX_CHAT_COMPLETIONS = 10;
+ AbstractChatCompletionRunner = class extends EventStream2 {
+ constructor() {
+ super(...arguments);
+ _AbstractChatCompletionRunner_instances.add(this);
+ this._chatCompletions = [];
+ _AbstractChatCompletionRunner_completionArrivedBeforeAbort.set(this, false);
+ _AbstractChatCompletionRunner_afterCompletionInvoked.set(this, false);
+ this.messages = [];
+ }
+ _addChatCompletion(chatCompletion) {
+ __classPrivateFieldSet(this, _AbstractChatCompletionRunner_completionArrivedBeforeAbort, !this.controller.signal.aborted, "f");
+ normalizeToolCallIds(chatCompletion);
+ this._chatCompletions.push(chatCompletion);
+ this._emit("chatCompletion", chatCompletion);
+ const message = chatCompletion.choices[0]?.message;
+ if (message) {
+ this._addMessage(message);
+ }
+ return chatCompletion;
+ }
+ _addMessage(message, emit = true, normalizeContent = true) {
+ if (normalizeContent && !("content" in message)) {
+ message.content = null;
+ }
+ this.messages.push(message);
+ if (emit) {
+ this._emit("message", message);
+ if (isToolMessage(message) && message.content) {
+ this._emit("functionToolCallResult", message.content);
+ } else if (isAssistantMessage(message) && message.tool_calls) {
+ for (const tool_call of message.tool_calls) {
+ if (tool_call.type === "function") {
+ this._emit("functionToolCall", tool_call.function);
+ }
+ }
+ }
+ }
+ }
+ /**
+ * @returns a promise that resolves with the final ChatCompletion, or rejects
+ * if an error occurred or the stream ended prematurely without producing a ChatCompletion.
+ */
+ async finalChatCompletion() {
+ await this.done();
+ const completion = this._chatCompletions[this._chatCompletions.length - 1];
+ if (!completion) {
+ throw new OpenAIError("stream ended without producing a ChatCompletion");
+ }
+ return completion;
+ }
+ /**
+ * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects
+ * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
+ */
+ async finalContent() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
+ }
+ /**
+ * @returns a promise that resolves with the final assistant ChatCompletionMessage response,
+ * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
+ */
+ async finalMessage() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
+ }
+ /**
+ * Waits for completion and returns the last function-tool call, or `undefined`
+ * when no assistant message contains a function-tool call.
+ */
+ async finalFunctionToolCall() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
+ }
+ /** Waits for completion and returns the last matching function-tool result, if any. */
+ async finalFunctionToolCallResult() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
+ }
+ /** Waits for completion and sums token usage across every chat completion in the run. */
+ async totalUsage() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
+ }
+ /** Returns a copy of the chat completions received so far, in request order. */
+ allChatCompletions() {
+ return [...this._chatCompletions];
+ }
+ _emitFinal() {
+ if (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_afterCompletionInvoked, "f")) {
+ __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_throwIfAborted).call(this);
+ }
+ const completion = this._chatCompletions[this._chatCompletions.length - 1];
+ if (completion) {
+ this._emit("finalChatCompletion", completion);
+ }
+ const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
+ if (finalMessage) {
+ this._emit("finalMessage", finalMessage);
+ }
+ const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
+ if (finalContent) {
+ this._emit("finalContent", finalContent);
+ }
+ const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
+ if (finalFunctionCall) {
+ this._emit("finalFunctionToolCall", finalFunctionCall);
+ }
+ const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
+ if (finalFunctionCallResult != null) {
+ this._emit("finalFunctionToolCallResult", finalFunctionCallResult);
+ }
+ if (this._chatCompletions.some((c) => c.usage)) {
+ this._emit("totalUsage", __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
+ }
+ }
+ async _createChatCompletion(client, params, options) {
+ this._listenForAbort(options?.signal);
+ __classPrivateFieldGet(_a2, _a2, "m", _AbstractChatCompletionRunner_validateParams).call(_a2, params);
+ const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
+ this._connected();
+ return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
+ }
+ async _runChatCompletion(client, params, options) {
+ for (const message of params.messages) {
+ this._addMessage(message, false, false);
+ }
+ return await this._createChatCompletion(client, params, options);
+ }
+ async _runTools(client, params, runner, options) {
+ const role = "tool";
+ const { tool_choice = "auto", stream: stream3, toolContext: inputToolContext, ...restParams } = params;
+ const toolContext = inputToolContext;
+ const singleFunctionToCall = (
+ // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Chat history and tool-choice inputs can contain runtime variants that select different runner behavior.
+ typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name
+ );
+ const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS, afterCompletion } = options || {};
+ const runAfterCompletion = async (completion) => {
+ if (afterCompletion == null) {
+ return;
+ }
+ __classPrivateFieldSet(this, _AbstractChatCompletionRunner_afterCompletionInvoked, true, "f");
+ await afterCompletion(completion, runner);
+ __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_throwIfAborted).call(this);
+ };
+ const inputTools = params.tools.map((tool) => {
+ if (isAutoParsableTool(tool)) {
+ if (!tool.$callback) {
+ throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");
+ }
+ return {
+ type: "function",
+ function: {
+ function: tool.$callback,
+ name: tool.function.name,
+ description: tool.function.description || "",
+ parameters: tool.function.parameters,
+ parse: tool.$parseRaw,
+ strict: true
+ }
+ };
+ }
+ return tool;
+ });
+ const functionsByName = /* @__PURE__ */ Object.create(null);
+ for (const f of inputTools) {
+ if (f.type === "function") {
+ functionsByName[f.function.name || f.function.function.name] = f.function;
+ }
+ }
+ const tools = "tools" in params ? inputTools.map((t) => t.type === "function" ? {
+ type: "function",
+ function: {
+ name: t.function.name || t.function.function.name,
+ // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Tool parameter schemas use the published open JSON Schema dictionary contract, including arbitrary extensions.
+ parameters: t.function.parameters,
+ description: t.function.description,
+ strict: t.function.strict
+ }
+ } : (
+ // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Preserve the existing non-function tool pass-through; runnable and wire schema interfaces have incompatible index signatures.
+ t
+ )) : void 0;
+ for (const message of params.messages) {
+ this._addMessage(message, false, false);
+ }
+ let allowBufferedToolCall = false;
+ const runToolCall = async (toolCall) => {
+ const bufferedToolCall = allowBufferedToolCall;
+ allowBufferedToolCall = false;
+ if (toolCall.type !== "function") {
+ return { message: void 0, functionCalled: false };
+ }
+ const tool_call_id = toolCall.id;
+ const { name, arguments: args } = toolCall.function;
+ const fn = functionsByName[name];
+ if (!fn) {
+ const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2) => JSON.stringify(name2)).join(", ")}. Please try again`;
+ return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
+ }
+ if (singleFunctionToCall && singleFunctionToCall !== name) {
+ const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
+ return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
+ }
+ let rawContent;
+ if (isRunnableFunctionWithParse(fn)) {
+ let parsed;
+ try {
+ parsed = await fn.parse(args);
+ } catch (error) {
+ if (this.controller.signal.aborted) {
+ throw this._userAbortError();
+ }
+ const content2 = error instanceof Error ? error.message : String(error);
+ return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
+ }
+ if (this.controller.signal.aborted) {
+ throw this._userAbortError();
+ }
+ try {
+ rawContent = await fn.function(parsed, runner, toolContext);
+ } catch (error) {
+ if (this.controller.signal.aborted && Object.is(error, this.controller.signal.reason)) {
+ throw this._userAbortError();
+ }
+ throw error;
+ }
+ } else {
+ if (this.controller.signal.aborted && !bufferedToolCall) {
+ throw this._userAbortError();
+ }
+ try {
+ rawContent = await fn.function(args, runner, toolContext);
+ } catch (error) {
+ if (this.controller.signal.aborted && Object.is(error, this.controller.signal.reason)) {
+ throw this._userAbortError();
+ }
+ throw error;
+ }
+ }
+ const content = __classPrivateFieldGet(_a2, _a2, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(_a2, rawContent);
+ return { message: { role, tool_call_id, content }, functionCalled: true };
+ };
+ for (let i = 0; i < maxChatCompletions; ++i) {
+ const chatCompletion = await this._createChatCompletion(client, {
+ ...restParams,
+ tool_choice,
+ tools,
+ messages: this.messages.map(toRequestMessage)
+ }, options);
+ allowBufferedToolCall = this.controller.signal.aborted && __classPrivateFieldGet(this, _AbstractChatCompletionRunner_completionArrivedBeforeAbort, "f");
+ const message = chatCompletion.choices[0]?.message;
+ if (!message) {
+ throw new OpenAIError(`missing message in ChatCompletion response`);
+ }
+ if (!message.tool_calls?.length) {
+ await runAfterCompletion(chatCompletion);
+ return;
+ }
+ if (singleFunctionToCall || params.parallel_tool_calls === false) {
+ for (const toolCall of message.tool_calls) {
+ const result = await runToolCall(toolCall);
+ if (result.message) {
+ this._addMessage(result.message);
+ }
+ if (this.controller.signal.aborted) {
+ throw this._userAbortError();
+ }
+ if (singleFunctionToCall && result.functionCalled) {
+ await runAfterCompletion(chatCompletion);
+ return;
+ }
+ }
+ } else {
+ const results = await Promise.allSettled(message.tool_calls.map(runToolCall));
+ if (!this.controller.signal.aborted) {
+ for (const result of results) {
+ if (result.status === "rejected") {
+ throw result.reason;
+ }
+ }
+ }
+ for (const result of results) {
+ if (result.status === "fulfilled" && result.value.message) {
+ this._addMessage(result.value.message);
+ }
+ }
+ if (this.controller.signal.aborted) {
+ throw this._userAbortError();
+ }
+ }
+ await runAfterCompletion(chatCompletion);
+ }
+ }
+ };
+ _a2 = AbstractChatCompletionRunner, _AbstractChatCompletionRunner_completionArrivedBeforeAbort = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_afterCompletionInvoked = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent2() {
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
+ }, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() {
+ let i = this.messages.length;
+ while (i-- > 0) {
+ const message = this.messages[i];
+ if (isAssistantMessage(message)) {
+ const ret = {
+ ...message,
+ content: message.content ?? null,
+ refusal: message.refusal ?? null
+ };
+ return ret;
+ }
+ }
+ throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant");
+ }, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall2() {
+ for (let i = this.messages.length - 1; i >= 0; i--) {
+ const message = this.messages[i];
+ if (isAssistantMessage(message) && message?.tool_calls?.length) {
+ for (let j = message.tool_calls.length - 1; j >= 0; j--) {
+ const toolCall = message.tool_calls[j];
+ if (toolCall?.type === "function") {
+ return toolCall.function;
+ }
+ }
+ }
+ }
+ return void 0;
+ }, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult2() {
+ for (let i = this.messages.length - 1; i >= 0; i--) {
+ const message = this.messages[i];
+ if (isToolMessage(message) && message.content != null && // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Chat history and tool-choice inputs can contain runtime variants that select different runner behavior.
+ typeof message.content === "string" && this.messages.some((x) => x.role === "assistant" && x.tool_calls?.some((y) => y.type === "function" && y.id === message.tool_call_id))) {
+ return message.content;
+ }
+ }
+ return void 0;
+ }, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage2() {
+ const total = {
+ completion_tokens: 0,
+ prompt_tokens: 0,
+ total_tokens: 0
+ };
+ for (const { usage } of this._chatCompletions) {
+ if (usage) {
+ total.completion_tokens += usage.completion_tokens;
+ total.prompt_tokens += usage.prompt_tokens;
+ total.total_tokens += usage.total_tokens;
+ }
+ }
+ return total;
+ }, _AbstractChatCompletionRunner_throwIfAborted = function _AbstractChatCompletionRunner_throwIfAborted2() {
+ if (this.controller.signal.aborted) {
+ throw this._userAbortError();
+ }
+ }, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams2(params) {
+ if (params.n != null && params.n > 1) {
+ throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.");
+ }
+ }, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) {
+ if (typeof rawContent === "string") {
+ return rawContent;
+ }
+ if (rawContent === void 0) {
+ return "undefined";
+ }
+ return JSON.stringify(rawContent);
+ };
+ }
+});
+
+// node_modules/openai/lib/ChatCompletionRunner.mjs
+var ChatCompletionRunner;
+var init_ChatCompletionRunner = __esm({
+ "node_modules/openai/lib/ChatCompletionRunner.mjs"() {
+ init_AbstractChatCompletionRunner();
+ init_chatCompletionUtils();
+ ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompletionRunner {
+ /** Starts a non-streaming tool loop and returns its event-driven conversation runner. */
+ static runTools(client, params, options) {
+ const runner = new _ChatCompletionRunner();
+ const opts = {
+ ...options,
+ __metadata: { ...options?.__metadata, helperMethod: "runTools" }
+ };
+ runner._run(() => runner._runTools(client, params, runner, opts));
+ return runner;
+ }
+ /**
+ * Appends a conversation message and emits text content for assistant replies.
+ * @param normalizeContent Defaults to true; initial history passes false to preserve caller-owned messages.
+ */
+ _addMessage(message, emit = true, normalizeContent = true) {
+ super._addMessage(message, emit, normalizeContent);
+ if (emit && isAssistantMessage(message) && message.content) {
+ this._emit("content", message.content);
+ }
+ }
+ };
+ }
+});
+
+// node_modules/openai/_vendor/partial-json-parser/parser.mjs
+function parseJSON(jsonString, allowPartial = Allow.ALL) {
+ if (typeof jsonString !== "string") {
+ throw new TypeError(`expecting str, got ${typeof jsonString}`);
+ }
+ if (!jsonString.trim()) {
+ throw new Error(`${jsonString} is empty`);
+ }
+ return _parseJSON(jsonString.trim(), allowPartial);
+}
+var STR, NUM, ARR, OBJ, NULL, BOOL, NAN, INFINITY, MINUS_INFINITY, INF, SPECIAL, ATOM, COLLECTION, ALL, Allow, PartialJSON, MalformedJSON, _parseJSON, partialParse;
+var init_parser2 = __esm({
+ "node_modules/openai/_vendor/partial-json-parser/parser.mjs"() {
+ STR = 1;
+ NUM = 2;
+ ARR = 4;
+ OBJ = 8;
+ NULL = 16;
+ BOOL = 32;
+ NAN = 64;
+ INFINITY = 128;
+ MINUS_INFINITY = 256;
+ INF = INFINITY | MINUS_INFINITY;
+ SPECIAL = NULL | BOOL | INF | NAN;
+ ATOM = STR | NUM | SPECIAL;
+ COLLECTION = ARR | OBJ;
+ ALL = ATOM | COLLECTION;
+ Allow = {
+ STR,
+ NUM,
+ ARR,
+ OBJ,
+ NULL,
+ BOOL,
+ NAN,
+ INFINITY,
+ MINUS_INFINITY,
+ INF,
+ SPECIAL,
+ ATOM,
+ COLLECTION,
+ ALL
+ };
+ PartialJSON = class extends Error {
+ };
+ MalformedJSON = class extends Error {
+ };
+ _parseJSON = (jsonString, allow) => {
+ const length = jsonString.length;
+ let index3 = 0;
+ const markPartialJSON = (msg) => {
+ throw new PartialJSON(`${msg} at position ${index3}`);
+ };
+ const throwMalformedError = (msg) => {
+ throw new MalformedJSON(`${msg} at position ${index3}`);
+ };
+ const parseAny = () => {
+ skipBlank();
+ if (index3 >= length) {
+ markPartialJSON("Unexpected end of input");
+ }
+ if (jsonString[index3] === '"') {
+ return parseStr();
+ }
+ if (jsonString[index3] === "{") {
+ return parseObj();
+ }
+ if (jsonString[index3] === "[") {
+ return parseArr();
+ }
+ if (jsonString.substring(index3, index3 + 4) === "null" || Allow.NULL & allow && length - index3 < 4 && "null".startsWith(jsonString.substring(index3))) {
+ index3 += 4;
+ return null;
+ }
+ if (jsonString.substring(index3, index3 + 4) === "true" || Allow.BOOL & allow && length - index3 < 4 && "true".startsWith(jsonString.substring(index3))) {
+ index3 += 4;
+ return true;
+ }
+ if (jsonString.substring(index3, index3 + 5) === "false" || Allow.BOOL & allow && length - index3 < 5 && "false".startsWith(jsonString.substring(index3))) {
+ index3 += 5;
+ return false;
+ }
+ if (jsonString.substring(index3, index3 + 8) === "Infinity" || Allow.INFINITY & allow && length - index3 < 8 && "Infinity".startsWith(jsonString.substring(index3))) {
+ index3 += 8;
+ return Infinity;
+ }
+ if (jsonString.substring(index3, index3 + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && length - index3 > 1 && length - index3 < 9 && "-Infinity".startsWith(jsonString.substring(index3))) {
+ index3 += 9;
+ return -Infinity;
+ }
+ if (jsonString.substring(index3, index3 + 3) === "NaN" || Allow.NAN & allow && length - index3 < 3 && "NaN".startsWith(jsonString.substring(index3))) {
+ index3 += 3;
+ return Number.NaN;
+ }
+ return parseNum();
+ };
+ const parseStr = () => {
+ const start = index3;
+ let escape2 = false;
+ index3++;
+ while (index3 < length && (jsonString[index3] !== '"' || escape2 && jsonString[index3 - 1] === "\\")) {
+ escape2 = jsonString[index3] === "\\" ? !escape2 : false;
+ index3++;
+ }
+ if (jsonString.charAt(index3) === '"') {
+ try {
+ return JSON.parse(jsonString.substring(start, ++index3 - Number(escape2)));
+ } catch (e) {
+ throwMalformedError(String(e));
+ }
+ } else if (Allow.STR & allow) {
+ try {
+ return JSON.parse(jsonString.substring(start, index3 - Number(escape2)) + '"');
+ } catch {
+ return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
+ }
+ }
+ markPartialJSON("Unterminated string literal");
+ };
+ const parseObj = () => {
+ index3++;
+ skipBlank();
+ const obj = {};
+ try {
+ while (jsonString[index3] !== "}") {
+ skipBlank();
+ if (index3 >= length && Allow.OBJ & allow) {
+ return obj;
+ }
+ const key = parseStr();
+ skipBlank();
+ index3++;
+ try {
+ const value = parseAny();
+ Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
+ } catch (e) {
+ if (Allow.OBJ & allow) {
+ return obj;
+ }
+ throw e;
+ }
+ skipBlank();
+ if (jsonString[index3] === ",") {
+ index3++;
+ }
+ }
+ } catch {
+ if (Allow.OBJ & allow) {
+ return obj;
+ }
+ markPartialJSON("Expected '}' at end of object");
+ }
+ index3++;
+ return obj;
+ };
+ const parseArr = () => {
+ index3++;
+ const arr = [];
+ try {
+ while (jsonString[index3] !== "]") {
+ arr.push(parseAny());
+ skipBlank();
+ if (jsonString[index3] === ",") {
+ index3++;
+ }
+ }
+ } catch {
+ if (Allow.ARR & allow) {
+ return arr;
+ }
+ markPartialJSON("Expected ']' at end of array");
+ }
+ index3++;
+ return arr;
+ };
+ const parseNum = () => {
+ if (index3 === 0) {
+ if (jsonString === "-" && Allow.NUM & allow) {
+ markPartialJSON("Not sure what '-' is");
+ }
+ try {
+ return JSON.parse(jsonString);
+ } catch (e) {
+ if (Allow.NUM & allow) {
+ try {
+ if (jsonString[jsonString.length - 1] === ".") {
+ return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf(".")));
+ }
+ return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
+ } catch {
+ }
+ }
+ throwMalformedError(String(e));
+ }
+ }
+ const start = index3;
+ if (jsonString[index3] === "-") {
+ index3++;
+ }
+ while (jsonString[index3] && !",]}".includes(jsonString[index3])) {
+ index3++;
+ }
+ if (index3 === length && !(Allow.NUM & allow)) {
+ markPartialJSON("Unterminated number literal");
+ }
+ const number = jsonString.substring(start, index3);
+ try {
+ return JSON.parse(number);
+ } catch {
+ if (number === "-" && Allow.NUM & allow) {
+ markPartialJSON("Not sure what '-' is");
+ }
+ try {
+ return JSON.parse(number.substring(0, number.lastIndexOf("e")));
+ } catch (e) {
+ throwMalformedError(String(e));
+ }
+ }
+ };
+ const skipBlank = () => {
+ while (index3 < length && " \n\r ".includes(jsonString[index3])) {
+ index3++;
+ }
+ };
+ return parseAny();
+ };
+ partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);
+ }
+});
+
+// node_modules/openai/streaming.mjs
+var init_streaming2 = __esm({
+ "node_modules/openai/streaming.mjs"() {
+ init_streaming();
+ }
+});
+
+// node_modules/openai/lib/ChatCompletionStream.mjs
+function parseStructuredStreamingJSON(content) {
+ try {
+ return partialParse(content);
+ } catch (error) {
+ if (error instanceof MalformedJSON || error instanceof SyntaxError) {
+ return parseResponseFormatContent({ type: "json_schema", $parseRaw: void 0 }, content);
+ }
+ throw error;
+ }
+}
+function makeChatCompletionReadableStreamMessageChunk(chunk, message, toolCallIds) {
+ const payload = {
+ type: "message",
+ message,
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...toolCallIds ? { tool_call_ids: toolCallIds } : {}
+ };
+ return {
+ id: chunk.id,
+ choices: [],
+ created: chunk.created,
+ model: chunk.model,
+ object: `${CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX}${JSON.stringify(payload)}`
+ };
+}
+function isChatCompletionReadableStreamMessage(item) {
+ return "type" in item && item.type === "message" && "message" in item || "object" in item && typeof item.object === "string" && item.object.startsWith(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX);
+}
+function getChatCompletionReadableStreamMessage(item) {
+ if ("type" in item) {
+ return item;
+ }
+ return JSON.parse(item.object.slice(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX.length));
+}
+function createPartialJSONParseState() {
+ return {
+ bytes: 0,
+ depth: 0,
+ fragments: 0,
+ work: 0,
+ escaped: false,
+ has_non_whitespace: false,
+ in_string: false,
+ last_parsed_bytes: 0,
+ pending_high_surrogate: false
+ };
+}
+function recordPartialJSONFragment(state3, budget, fragment, validationWorkBudget) {
+ if (budget.fragments >= MAX_PARTIAL_JSON_FRAGMENTS) {
+ throw new OpenAIError("Chat completion stream exceeded its structured JSON fragment limit");
+ }
+ let bytes = 0;
+ let { depth, escaped, has_non_whitespace: hasNonWhitespace, in_string: inString } = state3;
+ let completed = false;
+ let firstCharacter = true;
+ for (const character of fragment) {
+ const previousBytes = bytes;
+ const codePoint = character.codePointAt(0);
+ if (firstCharacter && state3.pending_high_surrogate && codePoint >= 56320 && codePoint <= 57343) {
+ bytes += 1;
+ } else if (codePoint <= 127) {
+ bytes += 1;
+ } else if (codePoint <= 2047) {
+ bytes += 2;
+ } else if (codePoint <= 65535) {
+ bytes += 3;
+ } else {
+ bytes += 4;
+ }
+ firstCharacter = false;
+ if (budget.bytes + bytes > MAX_PARTIAL_JSON_BYTES) {
+ throw new OpenAIError("Chat completion stream exceeded its structured JSON byte limit");
+ }
+ if (validationWorkBudget && validationWorkBudget.work + bytes > MAX_PARTIAL_JSON_PARSE_WORK) {
+ validationWorkBudget.work += previousBytes;
+ throw new OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit");
+ }
+ if (character !== " " && character !== "\n" && character !== "\r" && character !== " ") {
+ hasNonWhitespace = true;
+ }
+ if (inString) {
+ if (escaped) {
+ escaped = false;
+ } else if (character === "\\") {
+ escaped = true;
+ } else if (character === '"') {
+ inString = false;
+ completed || (completed = depth === 0);
+ }
+ continue;
+ }
+ if (character === '"') {
+ inString = true;
+ } else if (character === "{" || character === "[") {
+ depth += 1;
+ if (depth > MAX_PARTIAL_JSON_DEPTH) {
+ throw new OpenAIError("Chat completion stream exceeded its structured JSON nesting depth limit");
+ }
+ } else if ((character === "}" || character === "]") && depth > 0) {
+ depth -= 1;
+ completed || (completed = depth === 0);
+ }
+ }
+ state3.bytes += bytes;
+ state3.fragments += 1;
+ state3.depth = depth;
+ state3.escaped = escaped;
+ state3.has_non_whitespace = hasNonWhitespace;
+ state3.in_string = inString;
+ if (fragment.length > 0) {
+ const finalCodeUnit = fragment.codePointAt(fragment.length - 1) ?? 0;
+ state3.pending_high_surrogate = finalCodeUnit >= 55296 && finalCodeUnit <= 56319;
+ }
+ budget.bytes += bytes;
+ budget.fragments += 1;
+ if (validationWorkBudget) {
+ validationWorkBudget.work += bytes;
+ }
+ if (!hasNonWhitespace || bytes === 0) {
+ return false;
+ }
+ const minimumGrowth = Math.max(EAGER_PARTIAL_JSON_BYTES, Math.floor(state3.last_parsed_bytes / 2));
+ if (state3.bytes > EAGER_PARTIAL_JSON_BYTES && !completed && state3.bytes - state3.last_parsed_bytes < minimumGrowth) {
+ return false;
+ }
+ return true;
+}
+function reservePartialJSONParse(state3, budget) {
+ if (budget.work + state3.bytes > MAX_PARTIAL_JSON_PARSE_WORK) {
+ return false;
+ }
+ budget.work += state3.bytes;
+ state3.work += state3.bytes;
+ state3.last_parsed_bytes = state3.bytes;
+ return true;
+}
+function captureStructuredJSONSnapshot(snapshot, property) {
+ const descriptor = Object.getOwnPropertyDescriptor(snapshot, property);
+ if (!descriptor) {
+ let prototype = Object.getPrototypeOf(snapshot);
+ for (let depth = 0; prototype !== null; depth += 1) {
+ if (depth >= MAX_PARTIAL_JSON_DEPTH || Object.getOwnPropertyDescriptor(prototype, property)) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ prototype = Object.getPrototypeOf(prototype);
+ }
+ return void 0;
+ }
+ if (!("value" in descriptor) || typeof descriptor.value !== "string" && descriptor.value !== null && descriptor.value !== void 0) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ return descriptor.value;
+}
+function captureStructuredMessageSnapshot(choice) {
+ const descriptor = Object.getOwnPropertyDescriptor(choice, "message");
+ if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "object" || descriptor.value === null) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ return descriptor.value;
+}
+function captureSnapshotArray(snapshot, property, maximum, kind) {
+ const descriptor = Object.getOwnPropertyDescriptor(snapshot, property);
+ if (!descriptor) {
+ let prototype = Object.getPrototypeOf(snapshot);
+ for (let depth = 0; prototype !== null; depth += 1) {
+ if (depth >= MAX_PARTIAL_JSON_DEPTH || Object.getOwnPropertyDescriptor(prototype, property)) {
+ throw new OpenAIError(`Chat completion stream contains an unsafe snapshot ${kind} collection`);
+ }
+ prototype = Object.getPrototypeOf(prototype);
+ }
+ return void 0;
+ }
+ if (!("value" in descriptor) || !Array.isArray(descriptor.value)) {
+ throw new OpenAIError(`Chat completion stream contains an unsafe snapshot ${kind} collection`);
+ }
+ const length = Object.getOwnPropertyDescriptor(descriptor.value, "length");
+ if (!length || !("value" in length) || !Number.isSafeInteger(length.value) || length.value > maximum) {
+ throw new OpenAIError(`Chat completion stream exceeded its snapshot ${kind} limit`);
+ }
+ return descriptor.value;
+}
+function captureSnapshotArrayItem(array, index3) {
+ const descriptor = Object.getOwnPropertyDescriptor(array, index3);
+ if (!descriptor) {
+ return void 0;
+ }
+ if (!("value" in descriptor)) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ return descriptor.value;
+}
+function mapCapturedSnapshotArray(array, maximum, kind, map) {
+ const descriptor = Object.getOwnPropertyDescriptor(array, "length");
+ const length = descriptor && "value" in descriptor ? descriptor.value : void 0;
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > maximum) {
+ throw new OpenAIError(`Chat completion stream exceeded its snapshot ${kind} limit`);
+ }
+ const mapped = [];
+ mapped.length = length;
+ for (let index3 = 0; index3 < length; index3 += 1) {
+ const item = Object.getOwnPropertyDescriptor(array, index3);
+ if (!item) {
+ continue;
+ }
+ if (!("value" in item)) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ mapped[index3] = map(item.value, index3);
+ }
+ return mapped;
+}
+function validateStructuredJSONSnapshot(value, budget, validationWorkBudget) {
+ const state3 = createPartialJSONParseState();
+ const parseBudget = budget ?? { bytes: 0, fragments: 0, work: 0 };
+ recordPartialJSONFragment(state3, parseBudget, value, validationWorkBudget);
+ if (!reservePartialJSONParse(state3, parseBudget)) {
+ throw new OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit");
+ }
+ return value;
+}
+function ownFunctionToolIdentity(toolCall) {
+ const type = Object.getOwnPropertyDescriptor(toolCall, "type");
+ const fn = Object.getOwnPropertyDescriptor(toolCall, "function");
+ if (!type || !("value" in type) || type.value !== "function" || !fn || !("value" in fn)) {
+ return void 0;
+ }
+ if (typeof fn.value !== "object" || fn.value === null) {
+ return void 0;
+ }
+ const name = Object.getOwnPropertyDescriptor(fn.value, "name");
+ if (!name || !("value" in name) || typeof name.value !== "string" || name.value.length === 0) {
+ return void 0;
+ }
+ return { type: "function", name: name.value };
+}
+function assertBoundToolCallIdentity(toolCall, identity) {
+ const current = ownFunctionToolIdentity(toolCall);
+ if (!current || current.name !== identity.name || current.type !== identity.type) {
+ throw new OpenAIError("Chat completion stream contains a changed tool call identity");
+ }
+}
+function assignOwnProperties(target, source) {
+ if (Object.prototype.propertyIsEnumerable.call(source, "__proto__") && !hasOwn(target, "__proto__")) {
+ Object.defineProperty(target, "__proto__", {
+ value: void 0,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ }
+ return Object.assign(target, source);
+}
+function cloneParserConfigObject(value, stableFields = []) {
+ const descriptors = Object.getOwnPropertyDescriptors(value);
+ for (const field of stableFields) {
+ const descriptor = descriptors[field];
+ if (!descriptor && !(field in value)) {
+ continue;
+ }
+ descriptors[field] = {
+ // oxlint-disable-next-line anti-slop/no-reflect-get -- Generic config cloning must resolve inherited/accessor keys outside the declared config shape.
+ value: descriptor && "value" in descriptor ? descriptor.value : Reflect.get(value, field, value),
+ enumerable: descriptor?.enumerable ?? false,
+ configurable: descriptor?.configurable ?? true,
+ writable: descriptor && "writable" in descriptor ? descriptor.writable : false
+ };
+ }
+ return Object.create(Object.getPrototypeOf(value), descriptors);
+}
+function snapshotChatCompletionParserParams(params) {
+ const snapshot = cloneParserConfigObject(params);
+ if (params.tools) {
+ const stableTools = [];
+ const lengthDescriptor = Object.getOwnPropertyDescriptor(params.tools, "length");
+ const length = lengthDescriptor && "value" in lengthDescriptor ? lengthDescriptor.value : void 0;
+ const toolCount = typeof length === "number" && Number.isSafeInteger(length) && length >= 0 ? Math.min(length, MAX_STREAM_TOOL_CALLS) : 0;
+ for (let index3 = 0; index3 < toolCount; index3 += 1) {
+ const item = Object.getOwnPropertyDescriptor(params.tools, String(index3));
+ if (!item || !("value" in item)) {
+ stableTools.length = index3 + 1;
+ continue;
+ }
+ const tool = item.value;
+ const stableTool = cloneParserConfigObject(tool, [
+ "type",
+ "$brand",
+ "$parseRaw",
+ "$callback",
+ "function"
+ ]);
+ const descriptors = Object.getOwnPropertyDescriptors(stableTool);
+ if (isChatCompletionFunctionTool(stableTool)) {
+ const descriptor = descriptors.function;
+ descriptors.function = {
+ ...descriptor && "value" in descriptor ? descriptor : { configurable: true, enumerable: true, writable: true },
+ value: cloneParserConfigObject(stableTool.function, ["name", "strict"])
+ };
+ }
+ stableTools[index3] = Object.create(Object.getPrototypeOf(tool), descriptors);
+ }
+ snapshot.tools = stableTools;
+ }
+ if (params.response_format) {
+ snapshot.response_format = cloneParserConfigObject(params.response_format, [
+ "type",
+ "$brand",
+ "$parseRaw"
+ ]);
+ }
+ return snapshot;
+}
+function canonicalSerializedParserSchema(value, budget) {
+ const ancestors = /* @__PURE__ */ new WeakSet();
+ const charge = (bytes) => {
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || budget.bytes + bytes > MAX_SERIALIZED_PARSER_SCHEMA_BYTES) {
+ return false;
+ }
+ budget.bytes += bytes;
+ return true;
+ };
+ const visit = (current, depth) => {
+ if (depth > MAX_SERIALIZED_PARSER_SCHEMA_DEPTH || budget.nodes >= MAX_SERIALIZED_PARSER_SCHEMA_NODES) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ budget.nodes += 1;
+ if (current === void 0 || typeof current === "function" || typeof current === "symbol") {
+ return OMITTED_SERIALIZED_PARSER_VALUE;
+ }
+ if (typeof current === "bigint") {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ if (current === null || typeof current === "boolean" || typeof current === "number") {
+ const serialized = stringifyParserSchemaValue(current);
+ return typeof serialized === "string" && charge(serialized.length) ? serialized : UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ if (typeof current === "string") {
+ if (!charge(current.length * 6 + 2)) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ return stringifyParserSchemaValue(current);
+ }
+ if (typeof current !== "object" || ancestors.has(current)) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ const array = Array.isArray(current);
+ const prototype = Object.getPrototypeOf(current);
+ if (array && prototype !== Array.prototype || !array && prototype !== null && prototype !== Object.prototype) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ for (let owner = current; owner !== null; owner = Object.getPrototypeOf(owner)) {
+ const serializer = Object.getOwnPropertyDescriptor(owner, "toJSON");
+ if (!serializer) {
+ continue;
+ }
+ if (!("value" in serializer) || typeof serializer.value === "function") {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ break;
+ }
+ ancestors.add(current);
+ try {
+ if (!charge(2)) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ if (array) {
+ const lengthDescriptor = Object.getOwnPropertyDescriptor(current, "length");
+ const length = lengthDescriptor && "value" in lengthDescriptor ? lengthDescriptor.value : void 0;
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > MAX_SERIALIZED_PARSER_SCHEMA_NODES - budget.nodes) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ const items = [];
+ for (let index3 = 0; index3 < length; index3 += 1) {
+ const key = String(index3);
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
+ if (!descriptor) {
+ if (Object.getOwnPropertyDescriptor(Array.prototype, key) || Object.getOwnPropertyDescriptor(Object.prototype, key)) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ budget.nodes += 1;
+ if (!charge(4)) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ items.push("null");
+ continue;
+ }
+ if (!("value" in descriptor)) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ const item = visit(descriptor.value, depth + 1);
+ if (item === UNSAFE_SERIALIZED_PARSER_VALUE) {
+ return item;
+ }
+ items.push(item === OMITTED_SERIALIZED_PARSER_VALUE ? "null" : item);
+ }
+ return `[${items.join(",")}]`;
+ }
+ const keys = Reflect.ownKeys(current);
+ if (keys.length > MAX_SERIALIZED_PARSER_SCHEMA_NODES - budget.nodes) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ const entries = [];
+ for (const key of keys) {
+ if (typeof key !== "string") {
+ continue;
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
+ if (!descriptor) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ if (!descriptor.enumerable) {
+ continue;
+ }
+ if (!("value" in descriptor)) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ entries.push([key, descriptor.value]);
+ }
+ entries.sort(([left], [right]) => {
+ if (left === right) {
+ return 0;
+ }
+ return left < right ? -1 : 1;
+ });
+ const fields = [];
+ for (const [key, entry] of entries) {
+ const normalized = visit(entry, depth + 1);
+ if (normalized === UNSAFE_SERIALIZED_PARSER_VALUE) {
+ return normalized;
+ }
+ if (normalized === OMITTED_SERIALIZED_PARSER_VALUE) {
+ continue;
+ }
+ if (!charge(key.length * 6 + 3)) {
+ return UNSAFE_SERIALIZED_PARSER_VALUE;
+ }
+ fields.push(`${stringifyParserSchemaValue(key)}:${normalized}`);
+ }
+ return `{${fields.join(",")}}`;
+ } finally {
+ ancestors.delete(current);
+ }
+ };
+ try {
+ const normalized = visit(value, 0);
+ return typeof normalized === "string" ? normalized : void 0;
+ } catch {
+ return void 0;
+ }
+}
+function rememberSerializedParserSchema(signatures, source, holder, key) {
+ const parser = Object.getOwnPropertyDescriptor(source, "$parseRaw");
+ const schema = Object.getOwnPropertyDescriptor(holder, key);
+ if (!parser || !("value" in parser) || typeof parser.value !== "function" || !schema || !("value" in schema)) {
+ return;
+ }
+ const normalized = canonicalSerializedParserSchema(schema.value, { nodes: 0, bytes: 0 });
+ if (normalized !== void 0) {
+ signatures.set(source, normalized);
+ }
+}
+function hasMatchingSerializedParserSchema(signatures, source, holder, key, value) {
+ const expected = source && signatures.get(source);
+ const descriptor = Object.getOwnPropertyDescriptor(holder, key);
+ return expected !== void 0 && descriptor !== void 0 && "value" in descriptor && canonicalSerializedParserSchema(value, { nodes: 0, bytes: 0 }) === expected;
+}
+function serializedParserDescriptor(descriptor, value) {
+ return descriptor && "value" in descriptor ? { ...descriptor, value } : { configurable: true, enumerable: true, writable: true, value };
+}
+function shadowSerializedParserMetadata(descriptors, source, fields) {
+ for (const field of fields) {
+ const descriptor = descriptors[field];
+ if (!descriptor && !(field in source)) {
+ continue;
+ }
+ descriptors[field] = descriptor && "value" in descriptor ? { ...descriptor, value: void 0 } : {
+ configurable: descriptor?.configurable ?? true,
+ enumerable: descriptor?.enumerable ?? false,
+ writable: false,
+ value: void 0
+ };
+ }
+}
+function snapshotSerializedParserTool(serialized) {
+ const source = serialized.source ?? {
+ type: serialized.type,
+ ...serialized.type === "function" ? { function: {} } : {}
+ };
+ const descriptors = Object.getOwnPropertyDescriptors(source);
+ descriptors.type = serializedParserDescriptor(descriptors.type, serialized.type);
+ if (serialized.type !== "function" || !serialized.function) {
+ if (descriptors.function) {
+ descriptors.function = serializedParserDescriptor(descriptors.function, void 0);
+ }
+ shadowSerializedParserMetadata(descriptors, source, ["$brand", "$parseRaw", "$callback"]);
+ return Object.create(Object.getPrototypeOf(source), descriptors);
+ }
+ const descriptor = descriptors.function;
+ const original = descriptor && "value" in descriptor && typeof descriptor.value === "object" && descriptor.value !== null ? descriptor.value : {};
+ const functionDescriptors = Object.getOwnPropertyDescriptors(original);
+ functionDescriptors["name"] = serializedParserDescriptor(functionDescriptors["name"], serialized.function.name);
+ functionDescriptors["strict"] = serializedParserDescriptor(functionDescriptors["strict"], serialized.function.strict);
+ descriptors.function = serializedParserDescriptor(descriptor, Object.create(Object.getPrototypeOf(original), functionDescriptors));
+ if (!serialized.function.schemaMatches) {
+ shadowSerializedParserMetadata(descriptors, source, ["$brand", "$parseRaw", "$callback"]);
+ }
+ return Object.create(Object.getPrototypeOf(source), descriptors);
+}
+function snapshotSerializedResponseFormat(serialized) {
+ const source = serialized.source ?? { type: serialized.type };
+ const descriptors = Object.getOwnPropertyDescriptors(source);
+ descriptors.type = serializedParserDescriptor(descriptors.type, serialized.type);
+ if (serialized.type !== "json_schema" || !serialized.source || !serialized.schemaMatches) {
+ shadowSerializedParserMetadata(descriptors, source, ["$brand", "$parseRaw"]);
+ }
+ return Object.create(Object.getPrototypeOf(source), descriptors);
+}
+function ownSerializedParserObject(holder, key) {
+ const descriptor = Object.getOwnPropertyDescriptor(holder, key);
+ if (!descriptor || !("value" in descriptor)) {
+ return void 0;
+ }
+ const { value } = descriptor;
+ return typeof value === "object" && value !== null ? value : void 0;
+}
+function observeSerializedChatCompletionParserParams(body, initial, update) {
+ const originalToolOwners = /* @__PURE__ */ new WeakMap();
+ const originalSchemaSignatures = /* @__PURE__ */ new WeakMap();
+ if (body.tools) {
+ for (let index3 = 0; index3 < body.tools.length && index3 < MAX_STREAM_TOOL_CALLS; index3 += 1) {
+ const owner = ownSerializedParserObject(body.tools, String(index3));
+ const source = initial.tools?.[index3];
+ if (owner && source) {
+ originalToolOwners.set(owner, source);
+ const originalFunction = ownSerializedParserObject(source, "function");
+ if (originalFunction) {
+ rememberSerializedParserSchema(originalSchemaSignatures, source, originalFunction, "parameters");
+ }
+ }
+ }
+ }
+ if (initial.response_format) {
+ rememberSerializedParserSchema(originalSchemaSignatures, initial.response_format, initial.response_format, "json_schema");
+ }
+ let root;
+ let tools;
+ let responseFormat;
+ let responseFrame;
+ let frames = [];
+ let toolFrames = /* @__PURE__ */ new WeakMap();
+ let actualToolOwners = /* @__PURE__ */ new Map();
+ let functionFrames = /* @__PURE__ */ new WeakMap();
+ return observeJSONRequestBody(body, {
+ value(holder, key, value) {
+ if (!root && key === "" && typeof value === "object" && value !== null) {
+ root = value;
+ tools = void 0;
+ responseFormat = void 0;
+ responseFrame = void 0;
+ frames = [];
+ toolFrames = /* @__PURE__ */ new WeakMap();
+ actualToolOwners = /* @__PURE__ */ new Map();
+ functionFrames = /* @__PURE__ */ new WeakMap();
+ return;
+ }
+ if (holder === root && key === "response_format") {
+ if (typeof value === "object" && value !== null) {
+ responseFormat = value;
+ const owner = ownSerializedParserObject(holder, key);
+ responseFrame = {
+ source: owner === body.response_format ? initial.response_format : void 0,
+ schemaMatches: false
+ };
+ }
+ return;
+ }
+ if (holder === root && key === "tools") {
+ if (Array.isArray(value)) {
+ tools = new Proxy(value, {
+ get(target, property) {
+ const actual = Reflect.get(target, property, target);
+ if (typeof property === "string") {
+ const index3 = Number(property);
+ if (Number.isSafeInteger(index3) && index3 >= 0 && index3 < MAX_STREAM_TOOL_CALLS && String(index3) === property) {
+ actualToolOwners.set(index3, typeof actual === "object" && actual !== null ? actual : void 0);
+ }
+ }
+ return actual;
+ }
+ });
+ return tools;
+ }
+ return;
+ }
+ if (holder === tools) {
+ const index3 = Number(key);
+ if (!Number.isSafeInteger(index3) || index3 < 0 || index3 >= MAX_STREAM_TOOL_CALLS || typeof value !== "object" || value === null) {
+ return;
+ }
+ const owner = actualToolOwners.get(index3);
+ const source = owner ? originalToolOwners.get(owner) : void 0;
+ const frame = { source };
+ frames[index3] = frame;
+ toolFrames.set(value, frame);
+ return;
+ }
+ const tool = toolFrames.get(holder);
+ if (tool) {
+ if (key === "type" && typeof value === "string") {
+ tool.type = value;
+ } else if (key === "function" && typeof value === "object" && value !== null) {
+ const fn2 = { source: tool.source, schemaMatches: false };
+ tool.function = fn2;
+ functionFrames.set(value, fn2);
+ }
+ return;
+ }
+ if (holder === responseFormat && responseFrame) {
+ if (key === "type" && typeof value === "string") {
+ responseFrame.type = value;
+ } else if (key === "json_schema") {
+ responseFrame.schemaMatches = hasMatchingSerializedParserSchema(originalSchemaSignatures, responseFrame.source, holder, key, value);
+ }
+ return;
+ }
+ const fn = functionFrames.get(holder);
+ if (fn) {
+ if (key === "name" && typeof value === "string") {
+ fn.name = value;
+ } else if (key === "strict" && typeof value === "boolean") {
+ fn.strict = value;
+ } else if (key === "parameters") {
+ fn.schemaMatches = hasMatchingSerializedParserSchema(originalSchemaSignatures, fn.source, holder, key, value);
+ }
+ }
+ return void 0;
+ },
+ complete() {
+ if (!root) {
+ return;
+ }
+ const snapshot = cloneParserConfigObject(initial);
+ if (tools) {
+ const serializedTools = [];
+ for (let index3 = 0; index3 < frames.length; index3 += 1) {
+ const frame = frames[index3];
+ if (frame) {
+ serializedTools[index3] = snapshotSerializedParserTool(frame);
+ }
+ }
+ snapshot.tools = serializedTools;
+ } else {
+ delete snapshot.tools;
+ }
+ if (responseFrame) {
+ snapshot.response_format = snapshotSerializedResponseFormat(responseFrame);
+ } else {
+ delete snapshot.response_format;
+ }
+ update(snapshot);
+ root = void 0;
+ tools = void 0;
+ responseFormat = void 0;
+ responseFrame = void 0;
+ frames = [];
+ toolFrames = /* @__PURE__ */ new WeakMap();
+ actualToolOwners = /* @__PURE__ */ new Map();
+ functionFrames = /* @__PURE__ */ new WeakMap();
+ }
+ });
+}
+function finalizeChatCompletion(snapshot, params, audioDoneChoiceIndexes, validatedMessages) {
+ const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
+ const completion = {
+ ...rest,
+ id,
+ choices: mapCapturedSnapshotArray(choices, MAX_STREAM_CHOICES, "choice", (choice) => {
+ const validated = validatedMessages.get(choice);
+ if (!validated) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ const stableChoice = new Proxy(choice, {
+ get(target, property, receiver) {
+ return property === "message" ? validated.message : Reflect.get(target, property, receiver);
+ }
+ });
+ const { message: sourceMessage, finish_reason, index: index3, logprobs, ...choiceRest } = stableChoice;
+ const message = new Proxy(sourceMessage, {
+ get(target, property, receiver) {
+ if (property === "content") {
+ return validated.content;
+ }
+ if (property === "refusal") {
+ return validated.refusal;
+ }
+ if (property === "tool_calls") {
+ return validated.toolCallCollection;
+ }
+ return Reflect.get(target, property, receiver);
+ }
+ });
+ const { content = null, function_call, tool_calls, audio, ...messageRest } = message;
+ const finishReason = finish_reason ?? (audioDoneChoiceIndexes.has(index3) && isCompleteAudio(audio) ? "stop" : null);
+ if (!finishReason) {
+ throw new OpenAIError(`missing finish_reason for choice ${index3}`);
+ }
+ const audioResponse = audio ? { audio } : {};
+ const role = message.role;
+ if (!role) {
+ throw new OpenAIError(`missing role for choice ${index3}`);
+ }
+ if (function_call) {
+ const { arguments: args, name } = function_call;
+ if (args == null) {
+ throw new OpenAIError(`missing function_call.arguments for choice ${index3}`);
+ }
+ if (!name) {
+ throw new OpenAIError(`missing function_call.name for choice ${index3}`);
+ }
+ return {
+ ...choiceRest,
+ message: {
+ ...audioResponse,
+ content,
+ function_call: { arguments: args, name },
+ role,
+ refusal: message.refusal ?? null
+ },
+ finish_reason: finishReason,
+ index: index3,
+ logprobs
+ };
+ }
+ if (tool_calls) {
+ return {
+ ...choiceRest,
+ index: index3,
+ finish_reason: finishReason,
+ logprobs,
+ message: {
+ ...messageRest,
+ ...audioResponse,
+ role,
+ content,
+ refusal: message.refusal ?? null,
+ tool_calls: mapCapturedSnapshotArray(tool_calls, MAX_STREAM_TOOL_CALLS, "tool-call", (tool_call, i) => {
+ const captured = validated.toolCalls.get(i);
+ if (!captured) {
+ const identity = ownFunctionToolIdentity(tool_call);
+ if (identity && shouldParseToolCall(params, {
+ type: identity.type,
+ function: { name: identity.name }
+ })) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ }
+ if (captured && captured.tool !== tool_call) {
+ throw new OpenAIError("Chat completion stream contains a changed tool call identity");
+ }
+ const stableFunction = captured && new Proxy(captured.function, {
+ get(target, property, receiver) {
+ if (property === "arguments") {
+ return captured.arguments;
+ }
+ if (property === "name") {
+ return captured.name;
+ }
+ return Reflect.get(target, property, receiver);
+ }
+ });
+ const stableTool = captured && stableFunction ? new Proxy(tool_call, {
+ get(target, property, receiver) {
+ if (property === "type") {
+ return captured.type;
+ }
+ if (property === "function") {
+ return stableFunction;
+ }
+ return Reflect.get(target, property, receiver);
+ }
+ }) : tool_call;
+ if (stableTool.type == null) {
+ throw new OpenAIError(`missing choices[${index3}].tool_calls[${i}].type`);
+ }
+ if (stableTool.type === "custom") {
+ const { custom, type: type2, id: id3, ...toolRest2 } = stableTool;
+ const { input = "", name: name2, ...customRest } = custom || {};
+ if (name2 == null) {
+ throw new OpenAIError(`missing choices[${index3}].tool_calls[${i}].custom.name`);
+ }
+ return {
+ ...toolRest2,
+ id: id3 || `call_${uuid4()}`,
+ type: type2,
+ custom: { ...customRest, name: name2, input }
+ };
+ }
+ const { function: fn, type, id: id2, ...toolRest } = stableTool;
+ const { arguments: args, name, ...fnRest } = fn || {};
+ if (name == null) {
+ throw new OpenAIError(`missing choices[${index3}].tool_calls[${i}].function.name`);
+ }
+ if (args == null) {
+ throw new OpenAIError(`missing choices[${index3}].tool_calls[${i}].function.arguments`);
+ }
+ return {
+ ...toolRest,
+ id: id2 || `call_${uuid4()}`,
+ type,
+ function: { ...fnRest, name, arguments: args }
+ };
+ })
+ }
+ };
+ }
+ return {
+ ...choiceRest,
+ message: { ...messageRest, ...audioResponse, content, role, refusal: message.refusal ?? null },
+ finish_reason: finishReason,
+ index: index3,
+ logprobs
+ };
+ }),
+ created,
+ model,
+ object: "chat.completion",
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...system_fingerprint ? { system_fingerprint } : {}
+ };
+ return maybeParseChatCompletion(completion, params);
+}
+function isCompleteAudio(audio) {
+ return audio?.id != null && audio.data != null && audio.transcript != null && audio.expires_at != null;
+}
+function assertIsEmpty(obj) {
+ void obj;
+}
+function assertNever(_x) {
+ return _x;
+}
+var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_rejectsUnfinishedTurns, _ChatCompletionStream_audioDoneChoiceIndexes, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_hasAutoParseableTool, _ChatCompletionStream_partialJSONParseBudget, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_validateStructuredSnapshots, _ChatCompletionStream_endRequest, _ChatCompletionStream_accumulateChatCompletion, CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX, MAX_STREAM_CHOICES, MAX_STREAM_TOOL_CALLS, MAX_PARTIAL_JSON_BYTES, MAX_PARTIAL_JSON_FRAGMENTS, MAX_PARTIAL_JSON_DEPTH, MAX_PARTIAL_JSON_PARSE_WORK, EAGER_PARTIAL_JSON_BYTES, MAX_SERIALIZED_PARSER_SCHEMA_NODES, stringifyParserSchemaValue, MAX_SERIALIZED_PARSER_SCHEMA_BYTES, MAX_SERIALIZED_PARSER_SCHEMA_DEPTH, OMITTED_SERIALIZED_PARSER_VALUE, UNSAFE_SERIALIZED_PARSER_VALUE, ChatCompletionStream;
+var init_ChatCompletionStream = __esm({
+ "node_modules/openai/lib/ChatCompletionStream.mjs"() {
+ init_tslib();
+ init_parser2();
+ init_error2();
+ init_request_options();
+ init_uuid();
+ init_values();
+ init_parser();
+ init_streaming2();
+ init_AbstractChatCompletionRunner();
+ CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX = "chat.completion.chunk.message:";
+ MAX_STREAM_CHOICES = 128;
+ MAX_STREAM_TOOL_CALLS = 128;
+ MAX_PARTIAL_JSON_BYTES = 16 * 1024 * 1024;
+ MAX_PARTIAL_JSON_FRAGMENTS = 65536;
+ MAX_PARTIAL_JSON_DEPTH = 128;
+ MAX_PARTIAL_JSON_PARSE_WORK = 64 * 1024 * 1024;
+ EAGER_PARTIAL_JSON_BYTES = 1024;
+ MAX_SERIALIZED_PARSER_SCHEMA_NODES = 4096;
+ stringifyParserSchemaValue = JSON.stringify;
+ MAX_SERIALIZED_PARSER_SCHEMA_BYTES = 1024 * 1024;
+ MAX_SERIALIZED_PARSER_SCHEMA_DEPTH = 64;
+ OMITTED_SERIALIZED_PARSER_VALUE = Symbol("omitted serialized parser value");
+ UNSAFE_SERIALIZED_PARSER_VALUE = Symbol("unsafe serialized parser value");
+ ChatCompletionStream = class _ChatCompletionStream extends AbstractChatCompletionRunner {
+ /** Creates an unstarted stream, retaining request parameters for structured-output parsing. */
+ constructor(params) {
+ super();
+ _ChatCompletionStream_instances.add(this);
+ _ChatCompletionStream_params.set(this, void 0);
+ _ChatCompletionStream_rejectsUnfinishedTurns.set(this, false);
+ _ChatCompletionStream_audioDoneChoiceIndexes.set(this, void 0);
+ _ChatCompletionStream_choiceEventStates.set(this, void 0);
+ _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
+ _ChatCompletionStream_hasAutoParseableTool.set(this, void 0);
+ _ChatCompletionStream_partialJSONParseBudget.set(this, void 0);
+ __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_hasAutoParseableTool, false, "f");
+ const tools = params?.tools;
+ const lengthDescriptor = tools && Object.getOwnPropertyDescriptor(tools, "length");
+ const length = lengthDescriptor && "value" in lengthDescriptor ? lengthDescriptor.value : void 0;
+ if (tools && typeof length === "number" && Number.isSafeInteger(length) && length >= 0) {
+ for (let index3 = 0; index3 < Math.min(length, MAX_STREAM_TOOL_CALLS); index3 += 1) {
+ const descriptor = Object.getOwnPropertyDescriptor(tools, String(index3));
+ if (!descriptor || !("value" in descriptor)) {
+ continue;
+ }
+ const tool = descriptor.value;
+ if (isChatCompletionFunctionTool(tool) && (isAutoParsableTool(tool) || tool.function.strict === true)) {
+ __classPrivateFieldSet(this, _ChatCompletionStream_hasAutoParseableTool, true, "f");
+ break;
+ }
+ }
+ }
+ __classPrivateFieldSet(this, _ChatCompletionStream_partialJSONParseBudget, { bytes: 0, fragments: 0, work: 0 }, "f");
+ }
+ /** The latest accumulated completion, or `undefined` before a chunk arrives or after finalization. */
+ get currentChatCompletionSnapshot() {
+ return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
+ }
+ /**
+ * Intended for use on the frontend, consuming a stream produced with
+ * `.toReadableStream()` on the backend.
+ *
+ * Original input messages are not included in the serialized stream. Tool-result
+ * messages explicitly serialized by a streaming tool runner are replayed.
+ */
+ static fromReadableStream(stream3) {
+ const runner = new _ChatCompletionStream(null);
+ runner._run(() => runner._fromReadableStream(stream3));
+ return runner;
+ }
+ /** Starts a streaming chat completion request and returns its event-driven helper. */
+ static createChatCompletion(client, params, options) {
+ const runner = new _ChatCompletionStream(params);
+ runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, __metadata: { ...options?.__metadata, helperMethod: "stream" } }));
+ return runner;
+ }
+ /** Rejects unfinished turns before tool callbacks while preserving ordinary stream and replay behavior. */
+ _runTools(client, params, runner, options) {
+ __classPrivateFieldSet(this, _ChatCompletionStream_rejectsUnfinishedTurns, true, "f");
+ return super._runTools(client, params, runner, options);
+ }
+ async _createChatCompletion(client, params, options) {
+ this._listenForAbort(options?.signal);
+ const requestParams = { ...params, stream: true };
+ __classPrivateFieldSet(this, _ChatCompletionStream_params, requestParams, "f");
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
+ const parserParams = snapshotChatCompletionParserParams(requestParams);
+ __classPrivateFieldSet(this, _ChatCompletionStream_params, parserParams, "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_hasAutoParseableTool, parserParams.tools?.some((tool) => isChatCompletionFunctionTool(tool) && (isAutoParsableTool(tool) || tool.function.strict === true)) ?? false, "f");
+ const stopObserving = requestParams.tools || requestParams.response_format ? observeSerializedChatCompletionParserParams(requestParams, parserParams, (serialized) => {
+ __classPrivateFieldSet(this, _ChatCompletionStream_params, serialized, "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_hasAutoParseableTool, serialized.tools?.some((tool) => isChatCompletionFunctionTool(tool) && (isAutoParsableTool(tool) || tool.function.strict === true)) ?? false, "f");
+ }) : void 0;
+ const stream3 = await client.chat.completions.create(requestParams, {
+ ...options,
+ signal: this.controller.signal
+ }).finally(stopObserving);
+ this._connected();
+ for await (const chunk of stream3) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
+ }
+ if (stream3.controller.signal?.aborted) {
+ throw this._userAbortError();
+ }
+ return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
+ }
+ async _fromReadableStream(readableStream, options) {
+ this._listenForAbort(options?.signal);
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
+ this._connected();
+ const stream3 = Stream.fromReadableStream(readableStream, this.controller);
+ let chatId;
+ for await (const item of stream3) {
+ if ("error" in item && hasOwn(item, "error") && typeof item.error === "object" && item.error !== null) {
+ throw new APIError(void 0, item.error, void 0, void 0);
+ }
+ if (isChatCompletionReadableStreamMessage(item)) {
+ const message = getChatCompletionReadableStreamMessage(item);
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
+ const toolCalls = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f").choices[0]?.message.tool_calls;
+ for (const [index3, id] of message.tool_call_ids?.entries() ?? []) {
+ const toolCall = toolCalls?.[index3];
+ if (toolCall && id) {
+ toolCall.id = id;
+ }
+ }
+ this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
+ chatId = void 0;
+ }
+ this._addMessage(message.message);
+ continue;
+ }
+ const chunk = item;
+ if (chatId && chunk.id && chatId !== chunk.id) {
+ this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
+ }
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
+ if (chunk.id) {
+ chatId = chunk.id;
+ }
+ }
+ if (stream3.controller.signal?.aborted) {
+ throw this._userAbortError();
+ }
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
+ return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
+ }
+ const lastChatCompletion = this._chatCompletions[this._chatCompletions.length - 1];
+ if (lastChatCompletion) {
+ return lastChatCompletion;
+ }
+ throw new OpenAIError(`request ended without sending any chunks`);
+ }
+ /** Iterates over raw API chunks; stopping iteration early aborts the underlying request. */
+ [(_ChatCompletionStream_params = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_rejectsUnfinishedTurns = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_audioDoneChoiceIndexes = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_choiceEventStates = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_hasAutoParseableTool = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_partialJSONParseBudget = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() {
+ if (this.ended) {
+ return;
+ }
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_partialJSONParseBudget, { bytes: 0, fragments: 0, work: 0 }, "f");
+ }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState2(choice) {
+ let state3 = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
+ if (state3) {
+ return state3;
+ }
+ state3 = {
+ content_done: false,
+ content_parse_state: void 0,
+ refusal_done: false,
+ logprobs_content_done: false,
+ logprobs_refusal_done: false,
+ done_tool_calls: /* @__PURE__ */ new Set(),
+ current_tool_call_index: null,
+ tool_call_parse_states: /* @__PURE__ */ new Map(),
+ tool_call_identities: /* @__PURE__ */ new Map()
+ };
+ __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state3;
+ return state3;
+ }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) {
+ if (this.ended) {
+ return;
+ }
+ const capturedChoiceFrames = /* @__PURE__ */ new WeakMap();
+ const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk, capturedChoiceFrames);
+ this._emit("chunk", chunk, completion);
+ for (const choice of chunk.choices) {
+ const capturedChoice = capturedChoiceFrames.get(choice);
+ const choiceSnapshot = completion.choices[capturedChoice?.index ?? choice.index];
+ const capturedToolCalls = capturedChoice?.tool_calls ?? [];
+ const { delta } = choice;
+ const structuredResponse = isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format);
+ const boundedSnapshot = structuredResponse || __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f");
+ const messageSnapshot = boundedSnapshot ? captureStructuredMessageSnapshot(choiceSnapshot) : choiceSnapshot.message;
+ const refusal = boundedSnapshot ? captureStructuredJSONSnapshot(messageSnapshot, "refusal") : messageSnapshot.refusal;
+ const parseableContent = !refusal && structuredResponse;
+ const messageContent = parseableContent ? captureStructuredJSONSnapshot(messageSnapshot, "content") : messageSnapshot.content;
+ if (delta?.content != null && messageSnapshot.role === "assistant" && messageContent) {
+ this._emit("content", delta.content, messageContent);
+ this._emit("content.delta", {
+ delta: delta.content,
+ snapshot: messageContent,
+ parsed: messageSnapshot.parsed
+ });
+ }
+ if (delta?.refusal != null && messageSnapshot.role === "assistant" && refusal) {
+ this._emit("refusal.delta", {
+ delta: delta.refusal,
+ snapshot: refusal
+ });
+ }
+ if (choice.logprobs?.content != null && messageSnapshot.role === "assistant") {
+ this._emit("logprobs.content.delta", {
+ content: choice.logprobs?.content,
+ snapshot: choiceSnapshot.logprobs?.content ?? []
+ });
+ }
+ if (choice.logprobs?.refusal != null && messageSnapshot.role === "assistant") {
+ this._emit("logprobs.refusal.delta", {
+ refusal: choice.logprobs?.refusal,
+ snapshot: choiceSnapshot.logprobs?.refusal ?? []
+ });
+ }
+ const state3 = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
+ if (choiceSnapshot.finish_reason) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
+ if (state3.current_tool_call_index != null) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state3.current_tool_call_index);
+ }
+ }
+ for (const toolCall of capturedToolCalls) {
+ if (state3.current_tool_call_index !== toolCall.index) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
+ if (state3.current_tool_call_index != null) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state3.current_tool_call_index);
+ }
+ }
+ state3.current_tool_call_index = toolCall.index;
+ }
+ for (const toolCallDelta of capturedToolCalls) {
+ const toolCallSnapshot = messageSnapshot.tool_calls?.[toolCallDelta.index];
+ if (!toolCallSnapshot?.type) {
+ continue;
+ }
+ if (toolCallSnapshot.type === "function") {
+ const boundIdentity = state3.tool_call_identities.get(toolCallDelta.index);
+ let argumentsSnapshot;
+ if (boundIdentity?.parseable) {
+ const capturedArguments = captureStructuredJSONSnapshot(toolCallSnapshot.function, "arguments");
+ if (typeof capturedArguments !== "string") {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ argumentsSnapshot = capturedArguments;
+ } else {
+ argumentsSnapshot = toolCallSnapshot.function.arguments;
+ }
+ this._emit("tool_calls.function.arguments.delta", {
+ name: toolCallSnapshot.function.name,
+ index: toolCallDelta.index,
+ arguments: argumentsSnapshot,
+ parsed_arguments: toolCallSnapshot.function.parsed_arguments,
+ arguments_delta: toolCallDelta.arguments_delta
+ });
+ } else if (toolCallSnapshot.type !== "custom") {
+ assertNever(toolCallSnapshot);
+ }
+ }
+ }
+ }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent2(choiceSnapshot, toolCallIndex) {
+ const state3 = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
+ if (state3.done_tool_calls.has(toolCallIndex)) {
+ return;
+ }
+ const messageSnapshot = __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f") ? captureStructuredMessageSnapshot(choiceSnapshot) : choiceSnapshot.message;
+ const toolCallSnapshot = messageSnapshot.tool_calls?.[toolCallIndex];
+ if (!toolCallSnapshot) {
+ throw new Error("no tool call snapshot");
+ }
+ const boundIdentity = state3.tool_call_identities.get(toolCallIndex);
+ if (boundIdentity) {
+ assertBoundToolCallIdentity(toolCallSnapshot, boundIdentity);
+ }
+ if (!toolCallSnapshot.type) {
+ throw new Error("tool call snapshot missing `type`");
+ }
+ if (toolCallSnapshot.type === "function") {
+ const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name);
+ let parsedArguments = null;
+ const parseable = isAutoParsableTool(inputTool) || inputTool?.function.strict === true;
+ let argumentsSnapshot;
+ if (parseable) {
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"));
+ }
+ const capturedArguments = captureStructuredJSONSnapshot(toolCallSnapshot.function, "arguments");
+ if (typeof capturedArguments !== "string") {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ argumentsSnapshot = capturedArguments;
+ } else {
+ argumentsSnapshot = toolCallSnapshot.function.arguments;
+ }
+ if (isAutoParsableTool(inputTool)) {
+ parsedArguments = inputTool.$parseRaw(validateStructuredJSONSnapshot(argumentsSnapshot));
+ } else if (inputTool?.function.strict) {
+ parsedArguments = parseResponseFormatContent({ type: "json_schema", $parseRaw: void 0 }, validateStructuredJSONSnapshot(argumentsSnapshot));
+ }
+ if (choiceSnapshot.finish_reason) {
+ state3.done_tool_calls.add(toolCallIndex);
+ }
+ this._emit("tool_calls.function.arguments.done", {
+ name: toolCallSnapshot.function.name,
+ index: toolCallIndex,
+ arguments: argumentsSnapshot,
+ parsed_arguments: parsedArguments
+ });
+ } else if (toolCallSnapshot.type !== "custom") {
+ assertNever(toolCallSnapshot);
+ }
+ }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents2(choiceSnapshot) {
+ const state3 = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
+ const structuredResponse = isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format);
+ const boundedSnapshot = structuredResponse || __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f");
+ const messageSnapshot = boundedSnapshot ? captureStructuredMessageSnapshot(choiceSnapshot) : choiceSnapshot.message;
+ const refusal = boundedSnapshot ? captureStructuredJSONSnapshot(messageSnapshot, "refusal") : messageSnapshot.refusal;
+ const parseableContent = !refusal && structuredResponse;
+ const content = parseableContent ? captureStructuredJSONSnapshot(messageSnapshot, "content") : messageSnapshot.content;
+ if (content != null && (content !== "" || !refusal && !messageSnapshot.tool_calls?.length && !messageSnapshot.function_call) && !state3.content_done) {
+ if (parseableContent && __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"));
+ }
+ state3.content_done = true;
+ this._emit("content.done", {
+ content,
+ parsed: refusal ? null : parseResponseFormatContent(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format, parseableContent ? validateStructuredJSONSnapshot(content) : content)
+ });
+ }
+ if (refusal && !state3.refusal_done) {
+ state3.refusal_done = true;
+ this._emit("refusal.done", { refusal });
+ }
+ if (choiceSnapshot.logprobs?.content && !state3.logprobs_content_done) {
+ state3.logprobs_content_done = true;
+ this._emit("logprobs.content.done", { content: choiceSnapshot.logprobs.content });
+ }
+ if (choiceSnapshot.logprobs?.refusal && !state3.logprobs_refusal_done) {
+ state3.logprobs_refusal_done = true;
+ this._emit("logprobs.refusal.done", { refusal: choiceSnapshot.logprobs.refusal });
+ }
+ }, _ChatCompletionStream_validateStructuredSnapshots = function _ChatCompletionStream_validateStructuredSnapshots2(snapshot) {
+ const finalJSONBudget = { bytes: 0, fragments: 0, work: 0 };
+ const parseableContent = isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format);
+ const validatedMessages = /* @__PURE__ */ new WeakMap();
+ const choices = captureSnapshotArray(snapshot, "choices", MAX_STREAM_CHOICES, "choice");
+ if (!choices) {
+ throw new OpenAIError("Chat completion stream contains an unsafe snapshot choice collection");
+ }
+ for (let choiceIndex = 0; choiceIndex < choices.length; choiceIndex += 1) {
+ const choice = captureSnapshotArrayItem(choices, choiceIndex);
+ if (!choice) {
+ continue;
+ }
+ const message = captureStructuredMessageSnapshot(choice);
+ const refusal = captureStructuredJSONSnapshot(message, "refusal");
+ const content = captureStructuredJSONSnapshot(message, "content");
+ const validatedTools = /* @__PURE__ */ new Map();
+ const toolCalls = captureSnapshotArray(message, "tool_calls", MAX_STREAM_TOOL_CALLS, "tool-call");
+ validatedMessages.set(choice, Object.freeze({
+ message,
+ content,
+ refusal,
+ toolCallCollection: toolCalls,
+ toolCalls: validatedTools
+ }));
+ const state3 = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
+ if (parseableContent && !refusal && typeof content === "string") {
+ validateStructuredJSONSnapshot(content, finalJSONBudget, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"));
+ }
+ for (const [index3, identity] of state3?.tool_call_identities ?? []) {
+ const toolCall = toolCalls && captureSnapshotArrayItem(toolCalls, index3);
+ if (!toolCall) {
+ throw new OpenAIError("Chat completion stream contains a changed tool call identity");
+ }
+ assertBoundToolCallIdentity(toolCall, identity);
+ }
+ if (!__classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f")) {
+ continue;
+ }
+ for (let toolCallIndex = 0; toolCallIndex < (toolCalls?.length ?? 0); toolCallIndex += 1) {
+ const toolCall = captureSnapshotArrayItem(toolCalls, toolCallIndex);
+ if (!toolCall) {
+ continue;
+ }
+ const identity = ownFunctionToolIdentity(toolCall);
+ if (!identity) {
+ const type = Object.getOwnPropertyDescriptor(toolCall, "type");
+ if (type && !("value" in type)) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ if (type?.value !== "function") {
+ continue;
+ }
+ const fn2 = Object.getOwnPropertyDescriptor(toolCall, "function");
+ if (fn2 && !("value" in fn2)) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ if (fn2 && typeof fn2.value === "object" && fn2.value !== null) {
+ const name = Object.getOwnPropertyDescriptor(fn2.value, "name");
+ if (name && !("value" in name)) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ }
+ continue;
+ }
+ if (!shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), {
+ type: identity.type,
+ function: { name: identity.name }
+ })) {
+ continue;
+ }
+ const descriptor = Object.getOwnPropertyDescriptor(toolCall, "function");
+ if (!descriptor || !("value" in descriptor)) {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ const fn = descriptor.value;
+ const argumentsSnapshot = captureStructuredJSONSnapshot(fn, "arguments");
+ if (typeof argumentsSnapshot !== "string") {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ validateStructuredJSONSnapshot(argumentsSnapshot, finalJSONBudget, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"));
+ validatedTools.set(toolCallIndex, Object.freeze({
+ tool: toolCall,
+ function: fn,
+ type: identity.type,
+ name: identity.name,
+ arguments: argumentsSnapshot
+ }));
+ }
+ }
+ return validatedMessages;
+ }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest2() {
+ if (this.ended) {
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
+ }
+ const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
+ if (!snapshot) {
+ throw new OpenAIError(`request ended without sending any chunks`);
+ }
+ const validatedMessages = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, snapshot);
+ const audioDoneChoiceIndexes = __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
+ return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), audioDoneChoiceIndexes, validatedMessages);
+ }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk, capturedChoiceFrames) {
+ var _a5, _b, _c, _d, _e;
+ let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
+ const { choices, obfuscation: _obfuscation, ...rest } = chunk;
+ if (!snapshot) {
+ const newSnapshot = {
+ ...rest,
+ choices: []
+ };
+ __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, newSnapshot, "f");
+ snapshot = newSnapshot;
+ } else if (chunk.id) {
+ assignOwnProperties(snapshot, rest);
+ }
+ const requestedChoiceCount = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.n;
+ const maxChoices = typeof requestedChoiceCount === "number" && Number.isSafeInteger(requestedChoiceCount) && requestedChoiceCount > 0 ? Math.min(requestedChoiceCount, MAX_STREAM_CHOICES) : MAX_STREAM_CHOICES;
+ for (const chunkChoice of chunk.choices) {
+ const { delta, finish_reason, index: index3, logprobs = null, ...other } = chunkChoice;
+ const capturedToolCalls = [];
+ capturedChoiceFrames.set(chunkChoice, Object.freeze({ index: index3, tool_calls: capturedToolCalls }));
+ if (!Number.isSafeInteger(index3) || index3 < 0 || index3 >= maxChoices) {
+ throw new OpenAIError(`Chat completion stream contains an invalid choice index: ${index3}`);
+ }
+ let choice = snapshot.choices[index3];
+ if (!choice) {
+ const newChoice = { finish_reason, index: index3, message: {}, logprobs: null, ...other };
+ snapshot.choices[index3] = newChoice;
+ choice = newChoice;
+ }
+ if (isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format) || __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f")) {
+ captureStructuredJSONSnapshot(captureStructuredMessageSnapshot(choice), "refusal");
+ }
+ if (logprobs) {
+ if (choice.logprobs) {
+ const { content: content2, refusal: refusal2, ...rest3 } = logprobs;
+ assertIsEmpty(rest3);
+ assignOwnProperties(choice.logprobs, rest3);
+ if (content2) {
+ (_a5 = choice.logprobs).content ?? (_a5.content = []);
+ choice.logprobs.content.push(...content2);
+ }
+ if (refusal2) {
+ (_b = choice.logprobs).refusal ?? (_b.refusal = []);
+ choice.logprobs.refusal.push(...refusal2);
+ }
+ } else {
+ choice.logprobs = { ...logprobs };
+ if (logprobs.content) {
+ choice.logprobs.content = [...logprobs.content];
+ }
+ if (logprobs.refusal) {
+ choice.logprobs.refusal = [...logprobs.refusal];
+ }
+ }
+ }
+ if (finish_reason) {
+ choice.finish_reason = finish_reason;
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && (__classPrivateFieldGet(this, _ChatCompletionStream_rejectsUnfinishedTurns, "f") || hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")))) {
+ if (finish_reason === "length") {
+ throw new LengthFinishReasonError();
+ }
+ if (finish_reason === "content_filter") {
+ throw new ContentFilterFinishReasonError();
+ }
+ }
+ }
+ assignOwnProperties(choice, other);
+ if (!delta) {
+ Object.freeze(capturedToolCalls);
+ continue;
+ }
+ __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").delete(index3);
+ const { audio, content, refusal, function_call, role, ...capturedDeltaFields } = delta;
+ const { tool_calls: capturedToolCallDelta, ...rest2 } = capturedDeltaFields;
+ const tool_calls = hasOwn(capturedDeltaFields, "tool_calls") ? capturedToolCallDelta : delta.tool_calls;
+ assertIsEmpty(rest2);
+ assignOwnProperties(choice.message, rest2);
+ if (audio?.expires_at != null && audio.id == null && audio.data == null && audio.transcript == null && content == null && refusal == null && function_call == null && role == null && tool_calls == null && Object.keys(rest2).length === 0) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").add(index3);
+ }
+ if (refusal) {
+ choice.message.refusal = (choice.message.refusal || "") + refusal;
+ }
+ if (role) {
+ choice.message.role = role;
+ }
+ if (audio) {
+ const audioSnapshot = (_c = choice.message).audio ?? (_c.audio = {});
+ if (audio.id != null) {
+ audioSnapshot.id = audio.id;
+ }
+ if (audio.data != null) {
+ audioSnapshot.data = (audioSnapshot.data ?? "") + audio.data;
+ }
+ if (audio.transcript != null) {
+ audioSnapshot.transcript = (audioSnapshot.transcript ?? "") + audio.transcript;
+ }
+ if (audio.expires_at != null) {
+ audioSnapshot.expires_at = audio.expires_at;
+ }
+ }
+ if (function_call) {
+ if (choice.message.function_call) {
+ if (function_call.name) {
+ choice.message.function_call.name = function_call.name;
+ }
+ if (function_call.arguments) {
+ (_d = choice.message.function_call).arguments ?? (_d.arguments = "");
+ choice.message.function_call.arguments += function_call.arguments;
+ }
+ } else {
+ choice.message.function_call = function_call;
+ }
+ }
+ if (content != null) {
+ if (!choice.message.refusal && isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format)) {
+ const eventState = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choice);
+ const parseState = eventState.content_parse_state ?? (eventState.content_parse_state = createPartialJSONParseState());
+ const shouldParse = recordPartialJSONFragment(parseState, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"), content);
+ choice.message.content = (captureStructuredJSONSnapshot(choice.message, "content") || "") + content;
+ if (!parseState.has_non_whitespace) {
+ choice.message.parsed = null;
+ } else if (shouldParse && reservePartialJSONParse(parseState, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"))) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, snapshot);
+ choice.message.parsed = parseStructuredStreamingJSON(validateStructuredJSONSnapshot(choice.message.content));
+ } else if (content.length > 0) {
+ choice.message.parsed = null;
+ }
+ } else {
+ choice.message.content = (choice.message.content || "") + content;
+ }
+ }
+ if (tool_calls) {
+ const toolCallSnapshots = (_e = choice.message).tool_calls ?? (_e.tool_calls = []);
+ for (const toolCallDelta of tool_calls) {
+ const { index: index4, id, type, function: fn, custom, ...rest3 } = toolCallDelta;
+ if (!Number.isSafeInteger(index4) || index4 < 0 || index4 >= MAX_STREAM_TOOL_CALLS) {
+ throw new OpenAIError(`Chat completion stream contains an invalid tool call index: ${index4}`);
+ }
+ let argumentsDelta = "";
+ const tool_call = toolCallSnapshots[index4] ?? (toolCallSnapshots[index4] = {});
+ const functionName = fn?.name;
+ const eventState = __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f") ? __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choice) : void 0;
+ let boundIdentity = eventState?.tool_call_identities.get(index4);
+ if (boundIdentity) {
+ assertBoundToolCallIdentity(tool_call, boundIdentity);
+ if (type !== void 0 && type !== boundIdentity.type || functionName !== void 0 && functionName !== boundIdentity.name) {
+ throw new OpenAIError("Chat completion stream contains a changed tool call identity");
+ }
+ }
+ assignOwnProperties(tool_call, rest3);
+ if (id) {
+ tool_call.id = id;
+ }
+ if (type) {
+ tool_call.type = type;
+ }
+ if (custom) {
+ const customSnapshot = tool_call.custom ?? (tool_call.custom = { name: custom.name ?? "", input: "" });
+ if (custom.name) {
+ customSnapshot.name = custom.name;
+ }
+ if (custom.input) {
+ customSnapshot.input += custom.input;
+ }
+ }
+ if (fn) {
+ const functionSnapshot = tool_call.function ?? (tool_call.function = { name: functionName ?? "", arguments: "" });
+ if (functionName) {
+ functionSnapshot.name = functionName;
+ }
+ if (eventState && !boundIdentity) {
+ const identity = ownFunctionToolIdentity(tool_call);
+ const configuredTool = identity && __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === identity.name);
+ if (identity) {
+ boundIdentity = {
+ ...identity,
+ parseable: configuredTool !== void 0 && shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), {
+ type: identity.type,
+ function: { name: identity.name }
+ })
+ };
+ eventState.tool_call_identities.set(index4, boundIdentity);
+ if (!boundIdentity.parseable) {
+ const provisionalState = eventState.tool_call_parse_states.get(index4);
+ if (provisionalState) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f").bytes -= provisionalState.bytes;
+ __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f").fragments -= provisionalState.fragments;
+ __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f").work -= provisionalState.work;
+ eventState.tool_call_parse_states.delete(index4);
+ }
+ }
+ }
+ }
+ const argumentFragment = fn.arguments;
+ if (argumentFragment != null) {
+ argumentsDelta = argumentFragment;
+ if (eventState && boundIdentity?.parseable !== false) {
+ let parseState = eventState.tool_call_parse_states.get(index4);
+ if (!parseState) {
+ parseState = createPartialJSONParseState();
+ eventState.tool_call_parse_states.set(index4, parseState);
+ }
+ const shouldParse = recordPartialJSONFragment(parseState, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"), argumentFragment);
+ const previousArguments = captureStructuredJSONSnapshot(functionSnapshot, "arguments");
+ if (typeof previousArguments !== "string") {
+ throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
+ }
+ functionSnapshot.arguments = previousArguments + argumentFragment;
+ if (shouldParse && boundIdentity?.parseable === true && reservePartialJSONParse(parseState, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"))) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, snapshot);
+ functionSnapshot.parsed_arguments = parseStructuredStreamingJSON(validateStructuredJSONSnapshot(functionSnapshot.arguments));
+ } else if (argumentFragment.length > 0 && hasOwn(functionSnapshot, "parsed_arguments")) {
+ functionSnapshot.parsed_arguments = void 0;
+ }
+ } else {
+ functionSnapshot.arguments += argumentFragment;
+ }
+ }
+ }
+ capturedToolCalls.push(Object.freeze({ index: index4, arguments_delta: argumentsDelta }));
+ }
+ }
+ Object.freeze(capturedToolCalls);
+ }
+ return snapshot;
+ }, Symbol.asyncIterator)]() {
+ return this._createIterator((push) => {
+ const onChunk = (chunk) => push(chunk);
+ this.on("chunk", onChunk);
+ return () => this.off("chunk", onChunk);
+ }, { onReturn: () => this.abort() });
+ }
+ /** Serializes raw completion chunks into a readable stream for transfer to another runtime. */
+ toReadableStream() {
+ const stream3 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
+ return stream3.toReadableStream();
+ }
+ };
+ }
+});
+
+// node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
+var ChatCompletionStreamingRunner;
+var init_ChatCompletionStreamingRunner = __esm({
+ "node_modules/openai/lib/ChatCompletionStreamingRunner.mjs"() {
+ init_ChatCompletionStream();
+ init_error2();
+ init_streaming2();
+ init_chatCompletionUtils();
+ ChatCompletionStreamingRunner = class _ChatCompletionStreamingRunner extends ChatCompletionStream {
+ /** Restores a serialized tool run, including intermediate completions and tool-result messages. */
+ static fromReadableStream(stream3) {
+ const runner = new _ChatCompletionStreamingRunner(null);
+ runner._run(() => runner._fromReadableStream(stream3));
+ return runner;
+ }
+ /** Serializes completion chunks and tool-result messages for replay in another runtime. */
+ toReadableStream() {
+ let lastChunk;
+ let toolCallIds;
+ const iterator = this._createIterator((push) => {
+ const onChunk = (chunk) => {
+ lastChunk = chunk;
+ push(chunk);
+ };
+ const onMessage = (message) => {
+ if (isAssistantMessage(message)) {
+ toolCallIds = message.tool_calls?.map((toolCall) => toolCall.id);
+ return;
+ }
+ if (isToolMessage(message)) {
+ if (!lastChunk) {
+ throw new OpenAIError("cannot serialize a tool message before receiving any chunks");
+ }
+ push(makeChatCompletionReadableStreamMessageChunk(lastChunk, message, toolCallIds));
+ toolCallIds = void 0;
+ }
+ };
+ this.on("chunk", onChunk);
+ this.on("message", onMessage);
+ return () => {
+ this.off("chunk", onChunk);
+ this.off("message", onMessage);
+ };
+ }, { onReturn: () => this.abort() });
+ const stream3 = new Stream(() => iterator, this.controller);
+ return stream3.toReadableStream();
+ }
+ /** Starts a streaming tool loop and returns its event-driven conversation runner. */
+ static runTools(client, params, options) {
+ const runner = new _ChatCompletionStreamingRunner(
+ // @ts-expect-error TODO these types are incompatible
+ params
+ );
+ const opts = {
+ ...options,
+ __metadata: { ...options?.__metadata, helperMethod: "runTools" }
+ };
+ runner._run(() => runner._runTools(client, params, runner, opts));
+ return runner;
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/chat/completions/completions.mjs
+var Completions;
+var init_completions = __esm({
+ "node_modules/openai/resources/chat/completions/completions.mjs"() {
+ init_resource();
+ init_messages();
+ init_messages();
+ init_pagination();
+ init_path();
+ init_ChatCompletionRunner();
+ init_ChatCompletionStreamingRunner();
+ init_ChatCompletionStream();
+ init_parser();
+ init_ChatCompletionStreamingRunner();
+ init_RunnableFunction();
+ init_ChatCompletionStream();
+ init_ChatCompletionRunner();
+ Completions = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.messages = new Messages(this._client);
+ }
+ create(body, options) {
+ return this._client.post("/chat/completions", {
+ body,
+ ...options,
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get a stored chat completion. Only Chat Completions that have been created with
+ * the `store` parameter set to `true` will be returned.
+ *
+ * @example
+ * ```ts
+ * const chatCompletion =
+ * await client.chat.completions.retrieve('completion_id');
+ * ```
+ */
+ retrieve(completionID, options) {
+ return this._client.get(path`/chat/completions/${completionID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modify a stored chat completion. Only Chat Completions that have been created
+ * with the `store` parameter set to `true` can be modified. Currently, the only
+ * supported modification is to update the `metadata` field.
+ *
+ * @example
+ * ```ts
+ * const chatCompletion = await client.chat.completions.update(
+ * 'completion_id',
+ * { metadata: { foo: 'string' } },
+ * );
+ * ```
+ */
+ update(completionID, body, options) {
+ return this._client.post(path`/chat/completions/${completionID}`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List stored Chat Completions. Only Chat Completions that have been stored with
+ * the `store` parameter set to `true` will be returned.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const chatCompletion of client.chat.completions.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/chat/completions", CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a stored chat completion. Only Chat Completions that have been created
+ * with the `store` parameter set to `true` can be deleted.
+ *
+ * @example
+ * ```ts
+ * const chatCompletionDeleted =
+ * await client.chat.completions.delete('completion_id');
+ * ```
+ */
+ delete(completionID, options) {
+ return this._client.delete(path`/chat/completions/${completionID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ parse(body, options) {
+ validateInputTools(body.tools);
+ return this._client.chat.completions.create(body, {
+ ...options,
+ __metadata: { ...options?.__metadata, helperMethod: "chat.completions.parse" }
+ })._thenUnwrap((completion) => parseChatCompletion(completion, body));
+ }
+ runTools(body, options) {
+ if (body.stream) {
+ return ChatCompletionStreamingRunner.runTools(this._client, body, options);
+ }
+ return ChatCompletionRunner.runTools(this._client, body, options);
+ }
+ /**
+ * Creates a chat completion stream
+ */
+ stream(body, options) {
+ return ChatCompletionStream.createChatCompletion(this._client, body, options);
+ }
+ };
+ Completions.Messages = Messages;
+ }
+});
+
+// node_modules/openai/resources/chat/chat.mjs
+var Chat;
+var init_chat = __esm({
+ "node_modules/openai/resources/chat/chat.mjs"() {
+ init_resource();
+ init_completions();
+ init_completions();
+ Chat = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.completions = new Completions(this._client);
+ }
+ };
+ Chat.Completions = Completions;
+ }
+});
+
+// node_modules/openai/resources/chat/completions/index.mjs
+var init_completions2 = __esm({
+ "node_modules/openai/resources/chat/completions/index.mjs"() {
+ init_completions();
+ init_completions();
+ init_messages();
+ }
+});
+
+// node_modules/openai/resources/chat/index.mjs
+var init_chat2 = __esm({
+ "node_modules/openai/resources/chat/index.mjs"() {
+ init_chat();
+ init_completions2();
+ }
+});
+
+// node_modules/openai/resources/shared.mjs
+var init_shared = __esm({
+ "node_modules/openai/resources/shared.mjs"() {
+ }
+});
+
+// node_modules/openai/resources/admin/organization/admin-api-keys.mjs
+var AdminAPIKeys;
+var init_admin_api_keys = __esm({
+ "node_modules/openai/resources/admin/organization/admin-api-keys.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ AdminAPIKeys = class extends APIResource {
+ /**
+ * Create an organization admin API key
+ *
+ * @example
+ * ```ts
+ * const adminAPIKey =
+ * await client.admin.organization.adminAPIKeys.create({
+ * name: 'New Admin Key',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/organization/admin_api_keys", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieve a single organization API key
+ *
+ * @example
+ * ```ts
+ * const adminAPIKey =
+ * await client.admin.organization.adminAPIKeys.retrieve(
+ * 'key_id',
+ * );
+ * ```
+ */
+ retrieve(keyID, options) {
+ return this._client.get(path`/organization/admin_api_keys/${keyID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * List organization API keys
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const adminAPIKey of client.admin.organization.adminAPIKeys.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/admin_api_keys", CursorPage, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Delete an organization admin API key
+ *
+ * @example
+ * ```ts
+ * const adminAPIKey =
+ * await client.admin.organization.adminAPIKeys.delete(
+ * 'key_id',
+ * );
+ * ```
+ */
+ delete(keyID, options) {
+ return this._client.delete(path`/organization/admin_api_keys/${keyID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/audit-logs.mjs
+var AuditLogs;
+var init_audit_logs = __esm({
+ "node_modules/openai/resources/admin/organization/audit-logs.mjs"() {
+ init_resource();
+ init_pagination();
+ AuditLogs = class extends APIResource {
+ /**
+ * List user actions and configuration changes within this organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const auditLogListResponse of client.admin.organization.auditLogs.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/audit_logs", ConversationCursorPage, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/certificates.mjs
+var Certificates;
+var init_certificates = __esm({
+ "node_modules/openai/resources/admin/organization/certificates.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Certificates = class extends APIResource {
+ /**
+ * Upload a certificate to the organization. This does **not** automatically
+ * activate the certificate.
+ *
+ * Organizations can upload up to 50 certificates.
+ *
+ * @example
+ * ```ts
+ * const certificate =
+ * await client.admin.organization.certificates.create({
+ * certificate: 'certificate',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/organization/certificates", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get a certificate that has been uploaded to the organization.
+ *
+ * You can get a certificate regardless of whether it is active or not.
+ *
+ * @example
+ * ```ts
+ * const certificate =
+ * await client.admin.organization.certificates.retrieve(
+ * 'certificate_id',
+ * );
+ * ```
+ */
+ retrieve(certificateID, query = {}, options) {
+ return this._client.get(path`/organization/certificates/${certificateID}`, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Modify a certificate. Note that only the name can be modified.
+ *
+ * @example
+ * ```ts
+ * const certificate =
+ * await client.admin.organization.certificates.update(
+ * 'certificate_id',
+ * );
+ * ```
+ */
+ update(certificateID, body, options) {
+ return this._client.post(path`/organization/certificates/${certificateID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * List uploaded certificates for this organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateListResponse of client.admin.organization.certificates.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/certificates", ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Delete a certificate from the organization.
+ *
+ * The certificate must be inactive for the organization and all projects.
+ *
+ * @example
+ * ```ts
+ * const certificate =
+ * await client.admin.organization.certificates.delete(
+ * 'certificate_id',
+ * );
+ * ```
+ */
+ delete(certificateID, options) {
+ return this._client.delete(path`/organization/certificates/${certificateID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Activate certificates at the organization level.
+ *
+ * You can atomically and idempotently activate up to 10 certificates at a time.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateActivateResponse of client.admin.organization.certificates.activate(
+ * { certificate_ids: ['cert_abc'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ activate(body, options) {
+ return this._client.getAPIList("/organization/certificates/activate", Page, {
+ body,
+ method: "post",
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deactivate certificates at the organization level.
+ *
+ * You can atomically and idempotently deactivate up to 10 certificates at a time.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateDeactivateResponse of client.admin.organization.certificates.deactivate(
+ * { certificate_ids: ['cert_abc'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ deactivate(body, options) {
+ return this._client.getAPIList("/organization/certificates/deactivate", Page, { body, method: "post", ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/data-retention.mjs
+var DataRetention;
+var init_data_retention = __esm({
+ "node_modules/openai/resources/admin/organization/data-retention.mjs"() {
+ init_resource();
+ DataRetention = class extends APIResource {
+ /**
+ * Retrieves organization data retention controls.
+ *
+ * @example
+ * ```ts
+ * const organizationDataRetention =
+ * await client.admin.organization.dataRetention.retrieve();
+ * ```
+ */
+ retrieve(options) {
+ return this._client.get("/organization/data_retention", {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates organization data retention controls.
+ *
+ * @example
+ * ```ts
+ * const organizationDataRetention =
+ * await client.admin.organization.dataRetention.update({
+ * retention_type: 'zero_data_retention',
+ * });
+ * ```
+ */
+ update(body, options) {
+ return this._client.post("/organization/data_retention", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/invites.mjs
+var Invites;
+var init_invites = __esm({
+ "node_modules/openai/resources/admin/organization/invites.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Invites = class extends APIResource {
+ /**
+ * Create an invite for a user to the organization. The invite must be accepted by
+ * the user before they have access to the organization.
+ *
+ * @example
+ * ```ts
+ * const invite =
+ * await client.admin.organization.invites.create({
+ * email: 'email',
+ * role: 'reader',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/organization/invites", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an invite.
+ *
+ * @example
+ * ```ts
+ * const invite =
+ * await client.admin.organization.invites.retrieve(
+ * 'invite_id',
+ * );
+ * ```
+ */
+ retrieve(inviteID, options) {
+ return this._client.get(path`/organization/invites/${inviteID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Returns a list of invites in the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const invite of client.admin.organization.invites.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/invites", ConversationCursorPage, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Delete an invite. If the invite has already been accepted, it cannot be deleted.
+ *
+ * @example
+ * ```ts
+ * const invite =
+ * await client.admin.organization.invites.delete(
+ * 'invite_id',
+ * );
+ * ```
+ */
+ delete(inviteID, options) {
+ return this._client.delete(path`/organization/invites/${inviteID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/roles.mjs
+var Roles;
+var init_roles = __esm({
+ "node_modules/openai/resources/admin/organization/roles.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Roles = class extends APIResource {
+ /**
+ * Creates a custom role for the organization.
+ *
+ * @example
+ * ```ts
+ * const role = await client.admin.organization.roles.create({
+ * permissions: ['string'],
+ * role_name: 'role_name',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/organization/roles", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an organization role.
+ *
+ * @example
+ * ```ts
+ * const role = await client.admin.organization.roles.retrieve(
+ * 'role_id',
+ * );
+ * ```
+ */
+ retrieve(roleID, options) {
+ return this._client.get(path`/organization/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates an existing organization role.
+ *
+ * @example
+ * ```ts
+ * const role = await client.admin.organization.roles.update(
+ * 'role_id',
+ * );
+ * ```
+ */
+ update(roleID, body, options) {
+ return this._client.post(path`/organization/roles/${roleID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the roles configured for the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const role of client.admin.organization.roles.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/roles", NextCursorPage, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes a custom role from the organization.
+ *
+ * @example
+ * ```ts
+ * const role = await client.admin.organization.roles.delete(
+ * 'role_id',
+ * );
+ * ```
+ */
+ delete(roleID, options) {
+ return this._client.delete(path`/organization/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/spend-alerts.mjs
+var SpendAlerts;
+var init_spend_alerts = __esm({
+ "node_modules/openai/resources/admin/organization/spend-alerts.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ SpendAlerts = class extends APIResource {
+ /**
+ * Creates an organization spend alert.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendAlert =
+ * await client.admin.organization.spendAlerts.create({
+ * currency: 'USD',
+ * interval: 'month',
+ * notification_channel: {
+ * recipients: ['string'],
+ * type: 'email',
+ * },
+ * threshold_amount: 0,
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/organization/spend_alerts", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an organization spend alert.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendAlert =
+ * await client.admin.organization.spendAlerts.retrieve(
+ * 'alert_id',
+ * );
+ * ```
+ */
+ retrieve(alertID, options) {
+ return this._client.get(path`/organization/spend_alerts/${alertID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates an organization spend alert.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendAlert =
+ * await client.admin.organization.spendAlerts.update(
+ * 'alert_id',
+ * {
+ * currency: 'USD',
+ * interval: 'month',
+ * notification_channel: {
+ * recipients: ['string'],
+ * type: 'email',
+ * },
+ * threshold_amount: 0,
+ * },
+ * );
+ * ```
+ */
+ update(alertID, body, options) {
+ return this._client.post(path`/organization/spend_alerts/${alertID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists organization spend alerts.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const organizationSpendAlert of client.admin.organization.spendAlerts.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/spend_alerts", ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes an organization spend alert.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendAlertDeleted =
+ * await client.admin.organization.spendAlerts.delete(
+ * 'alert_id',
+ * );
+ * ```
+ */
+ delete(alertID, options) {
+ return this._client.delete(path`/organization/spend_alerts/${alertID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/spend-limit.mjs
+var SpendLimit;
+var init_spend_limit = __esm({
+ "node_modules/openai/resources/admin/organization/spend-limit.mjs"() {
+ init_resource();
+ SpendLimit = class extends APIResource {
+ /**
+ * Get the organization's hard spend limit.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendLimit =
+ * await client.admin.organization.spendLimit.retrieve();
+ * ```
+ */
+ retrieve(options) {
+ return this._client.get("/organization/spend_limit", {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Create or replace the organization's hard spend limit.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendLimit =
+ * await client.admin.organization.spendLimit.update({
+ * currency: 'USD',
+ * interval: 'month',
+ * threshold_amount: 1,
+ * });
+ * ```
+ */
+ update(body, options) {
+ return this._client.post("/organization/spend_limit", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Delete the organization's hard spend limit.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendLimitDeleted =
+ * await client.admin.organization.spendLimit.delete();
+ * ```
+ */
+ delete(options) {
+ return this._client.delete("/organization/spend_limit", {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/usage.mjs
+var Usage;
+var init_usage = __esm({
+ "node_modules/openai/resources/admin/organization/usage.mjs"() {
+ init_resource();
+ Usage = class extends APIResource {
+ /**
+ * Get audio speeches usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.audioSpeeches({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ audioSpeeches(query, options) {
+ return this._client.get("/organization/usage/audio_speeches", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get audio transcriptions usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.audioTranscriptions(
+ * { start_time: 0 },
+ * );
+ * ```
+ */
+ audioTranscriptions(query, options) {
+ return this._client.get("/organization/usage/audio_transcriptions", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get code interpreter sessions usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.codeInterpreterSessions(
+ * { start_time: 0 },
+ * );
+ * ```
+ */
+ codeInterpreterSessions(query, options) {
+ return this._client.get("/organization/usage/code_interpreter_sessions", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get completions usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.completions({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ completions(query, options) {
+ return this._client.get("/organization/usage/completions", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get costs details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.costs({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ costs(query, options) {
+ return this._client.get("/organization/costs", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get embeddings usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.embeddings({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ embeddings(query, options) {
+ return this._client.get("/organization/usage/embeddings", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get file search calls usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.fileSearchCalls({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ fileSearchCalls(query, options) {
+ return this._client.get("/organization/usage/file_search_calls", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get images usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.images({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ images(query, options) {
+ return this._client.get("/organization/usage/images", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get moderations usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.moderations({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ moderations(query, options) {
+ return this._client.get("/organization/usage/moderations", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get vector stores usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.vectorStores({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ vectorStores(query, options) {
+ return this._client.get("/organization/usage/vector_stores", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get web search calls usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.webSearchCalls({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ webSearchCalls(query, options) {
+ return this._client.get("/organization/usage/web_search_calls", {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/groups/roles.mjs
+var Roles2;
+var init_roles2 = __esm({
+ "node_modules/openai/resources/admin/organization/groups/roles.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Roles2 = class extends APIResource {
+ /**
+ * Assigns an organization role to a group within the organization.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.groups.roles.create(
+ * 'group_id',
+ * { role_id: 'role_id' },
+ * );
+ * ```
+ */
+ create(groupID, body, options) {
+ return this._client.post(path`/organization/groups/${groupID}/roles`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an organization role assigned to a group.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.groups.roles.retrieve(
+ * 'role_id',
+ * { group_id: 'group_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options) {
+ const { group_id } = params;
+ return this._client.get(path`/organization/groups/${group_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the organization roles assigned to a group within the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const roleListResponse of client.admin.organization.groups.roles.list(
+ * 'group_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(groupID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/groups/${groupID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Unassigns an organization role from a group within the organization.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.groups.roles.delete(
+ * 'role_id',
+ * { group_id: 'group_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options) {
+ const { group_id } = params;
+ return this._client.delete(path`/organization/groups/${group_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/groups/users.mjs
+var Users;
+var init_users = __esm({
+ "node_modules/openai/resources/admin/organization/groups/users.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Users = class extends APIResource {
+ /**
+ * Adds a user to a group.
+ *
+ * @example
+ * ```ts
+ * const user =
+ * await client.admin.organization.groups.users.create(
+ * 'group_id',
+ * { user_id: 'user_id' },
+ * );
+ * ```
+ */
+ create(groupID, body, options) {
+ return this._client.post(path`/organization/groups/${groupID}/users`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a user in a group.
+ *
+ * @example
+ * ```ts
+ * const user =
+ * await client.admin.organization.groups.users.retrieve(
+ * 'user_id',
+ * { group_id: 'group_id' },
+ * );
+ * ```
+ */
+ retrieve(userID, params, options) {
+ const { group_id } = params;
+ return this._client.get(path`/organization/groups/${group_id}/users/${userID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the users assigned to a group.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const organizationGroupUser of client.admin.organization.groups.users.list(
+ * 'group_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(groupID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/groups/${groupID}/users`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Removes a user from a group.
+ *
+ * @example
+ * ```ts
+ * const user =
+ * await client.admin.organization.groups.users.delete(
+ * 'user_id',
+ * { group_id: 'group_id' },
+ * );
+ * ```
+ */
+ delete(userID, params, options) {
+ const { group_id } = params;
+ return this._client.delete(path`/organization/groups/${group_id}/users/${userID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/groups/groups.mjs
+var Groups;
+var init_groups = __esm({
+ "node_modules/openai/resources/admin/organization/groups/groups.mjs"() {
+ init_resource();
+ init_roles2();
+ init_roles2();
+ init_users();
+ init_users();
+ init_pagination();
+ init_path();
+ Groups = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.users = new Users(this._client);
+ this.roles = new Roles2(this._client);
+ }
+ /**
+ * Creates a new group in the organization.
+ *
+ * @example
+ * ```ts
+ * const group = await client.admin.organization.groups.create(
+ * { name: 'x' },
+ * );
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/organization/groups", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a group.
+ *
+ * @example
+ * ```ts
+ * const group =
+ * await client.admin.organization.groups.retrieve(
+ * 'group_id',
+ * );
+ * ```
+ */
+ retrieve(groupID, options) {
+ return this._client.get(path`/organization/groups/${groupID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates a group's information.
+ *
+ * @example
+ * ```ts
+ * const group = await client.admin.organization.groups.update(
+ * 'group_id',
+ * { name: 'x' },
+ * );
+ * ```
+ */
+ update(groupID, body, options) {
+ return this._client.post(path`/organization/groups/${groupID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists all groups in the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const group of client.admin.organization.groups.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/groups", NextCursorPage, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes a group from the organization.
+ *
+ * @example
+ * ```ts
+ * const group = await client.admin.organization.groups.delete(
+ * 'group_id',
+ * );
+ * ```
+ */
+ delete(groupID, options) {
+ return this._client.delete(path`/organization/groups/${groupID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ Groups.Users = Users;
+ Groups.Roles = Roles2;
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/api-keys.mjs
+var APIKeys;
+var init_api_keys = __esm({
+ "node_modules/openai/resources/admin/organization/projects/api-keys.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ APIKeys = class extends APIResource {
+ /**
+ * Retrieves an API key in the project.
+ *
+ * @example
+ * ```ts
+ * const projectAPIKey =
+ * await client.admin.organization.projects.apiKeys.retrieve(
+ * 'api_key_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(apiKeyID, params, options) {
+ const { project_id } = params;
+ return this._client.get(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Returns a list of API keys in the project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectAPIKey of client.admin.organization.projects.apiKeys.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/api_keys`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes an API key from the project.
+ *
+ * Returns confirmation of the key deletion, or an error if the key belonged to a
+ * service account.
+ *
+ * @example
+ * ```ts
+ * const apiKey =
+ * await client.admin.organization.projects.apiKeys.delete(
+ * 'api_key_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(apiKeyID, params, options) {
+ const { project_id } = params;
+ return this._client.delete(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/certificates.mjs
+var Certificates2;
+var init_certificates2 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/certificates.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Certificates2 = class extends APIResource {
+ /**
+ * List certificates for this project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateListResponse of client.admin.organization.projects.certificates.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/certificates`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Activate certificates at the project level.
+ *
+ * You can atomically and idempotently activate up to 10 certificates at a time.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateActivateResponse of client.admin.organization.projects.certificates.activate(
+ * 'project_id',
+ * { certificate_ids: ['cert_abc'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ activate(projectID, body, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/certificates/activate`, Page, { body, method: "post", ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deactivate certificates at the project level. You can atomically and
+ * idempotently deactivate up to 10 certificates at a time.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateDeactivateResponse of client.admin.organization.projects.certificates.deactivate(
+ * 'project_id',
+ * { certificate_ids: ['cert_abc'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ deactivate(projectID, body, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/certificates/deactivate`, Page, { body, method: "post", ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/data-retention.mjs
+var DataRetention2;
+var init_data_retention2 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/data-retention.mjs"() {
+ init_resource();
+ init_path();
+ DataRetention2 = class extends APIResource {
+ /**
+ * Retrieves project data retention controls.
+ *
+ * @example
+ * ```ts
+ * const projectDataRetention =
+ * await client.admin.organization.projects.dataRetention.retrieve(
+ * 'project_id',
+ * );
+ * ```
+ */
+ retrieve(projectID, options) {
+ return this._client.get(path`/organization/projects/${projectID}/data_retention`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates project data retention controls.
+ *
+ * @example
+ * ```ts
+ * const projectDataRetention =
+ * await client.admin.organization.projects.dataRetention.update(
+ * 'project_id',
+ * { retention_type: 'organization_default' },
+ * );
+ * ```
+ */
+ update(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}/data_retention`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs
+var HostedToolPermissions;
+var init_hosted_tool_permissions = __esm({
+ "node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs"() {
+ init_resource();
+ init_path();
+ HostedToolPermissions = class extends APIResource {
+ /**
+ * Returns hosted tool permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectHostedToolPermissions =
+ * await client.admin.organization.projects.hostedToolPermissions.retrieve(
+ * 'project_id',
+ * );
+ * ```
+ */
+ retrieve(projectID, options) {
+ return this._client.get(path`/organization/projects/${projectID}/hosted_tool_permissions`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates hosted tool permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectHostedToolPermissions =
+ * await client.admin.organization.projects.hostedToolPermissions.update(
+ * 'project_id',
+ * );
+ * ```
+ */
+ update(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}/hosted_tool_permissions`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/model-permissions.mjs
+var ModelPermissions;
+var init_model_permissions = __esm({
+ "node_modules/openai/resources/admin/organization/projects/model-permissions.mjs"() {
+ init_resource();
+ init_path();
+ ModelPermissions = class extends APIResource {
+ /**
+ * Returns model permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectModelPermissions =
+ * await client.admin.organization.projects.modelPermissions.retrieve(
+ * 'project_id',
+ * );
+ * ```
+ */
+ retrieve(projectID, options) {
+ return this._client.get(path`/organization/projects/${projectID}/model_permissions`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates model permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectModelPermissions =
+ * await client.admin.organization.projects.modelPermissions.update(
+ * 'project_id',
+ * { mode: 'allow_list', model_ids: ['string'] },
+ * );
+ * ```
+ */
+ update(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}/model_permissions`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes model permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectModelPermissionsDeleted =
+ * await client.admin.organization.projects.modelPermissions.delete(
+ * 'project_id',
+ * );
+ * ```
+ */
+ delete(projectID, options) {
+ return this._client.delete(path`/organization/projects/${projectID}/model_permissions`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/rate-limits.mjs
+var RateLimits;
+var init_rate_limits = __esm({
+ "node_modules/openai/resources/admin/organization/projects/rate-limits.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ RateLimits = class extends APIResource {
+ /**
+ * Returns the rate limits per model for a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectRateLimit of client.admin.organization.projects.rateLimits.listRateLimits(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ listRateLimits(projectID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/rate_limits`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Updates a project rate limit.
+ *
+ * @example
+ * ```ts
+ * const projectRateLimit =
+ * await client.admin.organization.projects.rateLimits.updateRateLimit(
+ * 'rate_limit_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ updateRateLimit(rateLimitID, params, options) {
+ const { project_id, ...body } = params;
+ return this._client.post(path`/organization/projects/${project_id}/rate_limits/${rateLimitID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/roles.mjs
+var Roles3;
+var init_roles3 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/roles.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Roles3 = class extends APIResource {
+ /**
+ * Creates a custom role for a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.roles.create(
+ * 'project_id',
+ * { permissions: ['string'], role_name: 'role_name' },
+ * );
+ * ```
+ */
+ create(projectID, body, options) {
+ return this._client.post(path`/projects/${projectID}/roles`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project role.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.roles.retrieve(
+ * 'role_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options) {
+ const { project_id } = params;
+ return this._client.get(path`/projects/${project_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates an existing project role.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.roles.update(
+ * 'role_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ update(roleID, params, options) {
+ const { project_id, ...body } = params;
+ return this._client.post(path`/projects/${project_id}/roles/${roleID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the roles configured for a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const role of client.admin.organization.projects.roles.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options) {
+ return this._client.getAPIList(path`/projects/${projectID}/roles`, NextCursorPage, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes a custom role from a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.roles.delete(
+ * 'role_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options) {
+ const { project_id } = params;
+ return this._client.delete(path`/projects/${project_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs
+var SpendAlerts2;
+var init_spend_alerts2 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ SpendAlerts2 = class extends APIResource {
+ /**
+ * Creates a project spend alert.
+ *
+ * @example
+ * ```ts
+ * const projectSpendAlert =
+ * await client.admin.organization.projects.spendAlerts.create(
+ * 'project_id',
+ * {
+ * currency: 'USD',
+ * interval: 'month',
+ * notification_channel: {
+ * recipients: ['string'],
+ * type: 'email',
+ * },
+ * threshold_amount: 0,
+ * },
+ * );
+ * ```
+ */
+ create(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}/spend_alerts`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project spend alert.
+ *
+ * @example
+ * ```ts
+ * const projectSpendAlert =
+ * await client.admin.organization.projects.spendAlerts.retrieve(
+ * 'alert_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(alertID, params, options) {
+ const { project_id } = params;
+ return this._client.get(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates a project spend alert.
+ *
+ * @example
+ * ```ts
+ * const projectSpendAlert =
+ * await client.admin.organization.projects.spendAlerts.update(
+ * 'alert_id',
+ * {
+ * project_id: 'project_id',
+ * currency: 'USD',
+ * interval: 'month',
+ * notification_channel: {
+ * recipients: ['string'],
+ * type: 'email',
+ * },
+ * threshold_amount: 0,
+ * },
+ * );
+ * ```
+ */
+ update(alertID, params, options) {
+ const { project_id, ...body } = params;
+ return this._client.post(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists project spend alerts.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectSpendAlert of client.admin.organization.projects.spendAlerts.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/spend_alerts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes a project spend alert.
+ *
+ * @example
+ * ```ts
+ * const projectSpendAlertDeleted =
+ * await client.admin.organization.projects.spendAlerts.delete(
+ * 'alert_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(alertID, params, options) {
+ const { project_id } = params;
+ return this._client.delete(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/spend-limit.mjs
+var SpendLimit2;
+var init_spend_limit2 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/spend-limit.mjs"() {
+ init_resource();
+ init_path();
+ SpendLimit2 = class extends APIResource {
+ /**
+ * Get a project's hard spend limit.
+ *
+ * @example
+ * ```ts
+ * const projectSpendLimit =
+ * await client.admin.organization.projects.spendLimit.retrieve(
+ * 'proj_123',
+ * );
+ * ```
+ */
+ retrieve(projectID, options) {
+ return this._client.get(path`/organization/projects/${projectID}/spend_limit`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Create or replace a project's hard spend limit.
+ *
+ * @example
+ * ```ts
+ * const projectSpendLimit =
+ * await client.admin.organization.projects.spendLimit.update(
+ * 'proj_123',
+ * {
+ * currency: 'USD',
+ * interval: 'month',
+ * threshold_amount: 1,
+ * },
+ * );
+ * ```
+ */
+ update(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}/spend_limit`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Delete a project's hard spend limit.
+ *
+ * @example
+ * ```ts
+ * const projectSpendLimitDeleted =
+ * await client.admin.organization.projects.spendLimit.delete(
+ * 'proj_123',
+ * );
+ * ```
+ */
+ delete(projectID, options) {
+ return this._client.delete(path`/organization/projects/${projectID}/spend_limit`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/groups/roles.mjs
+var Roles4;
+var init_roles4 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/groups/roles.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Roles4 = class extends APIResource {
+ /**
+ * Assigns a project role to a group within a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.groups.roles.create(
+ * 'group_id',
+ * { project_id: 'project_id', role_id: 'role_id' },
+ * );
+ * ```
+ */
+ create(groupID, params, options) {
+ const { project_id, ...body } = params;
+ return this._client.post(path`/projects/${project_id}/groups/${groupID}/roles`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project role assigned to a group.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.groups.roles.retrieve(
+ * 'role_id',
+ * { project_id: 'project_id', group_id: 'group_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options) {
+ const { project_id, group_id } = params;
+ return this._client.get(path`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the project roles assigned to a group within a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const roleListResponse of client.admin.organization.projects.groups.roles.list(
+ * 'group_id',
+ * { project_id: 'project_id' },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(groupID, params, options) {
+ const { project_id, ...query } = params;
+ return this._client.getAPIList(path`/projects/${project_id}/groups/${groupID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Unassigns a project role from a group within a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.groups.roles.delete(
+ * 'role_id',
+ * { project_id: 'project_id', group_id: 'group_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options) {
+ const { project_id, group_id } = params;
+ return this._client.delete(path`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/groups/groups.mjs
+var Groups2;
+var init_groups2 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/groups/groups.mjs"() {
+ init_resource();
+ init_roles4();
+ init_roles4();
+ init_pagination();
+ init_path();
+ Groups2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.roles = new Roles4(this._client);
+ }
+ /**
+ * Grants a group access to a project.
+ *
+ * @example
+ * ```ts
+ * const projectGroup =
+ * await client.admin.organization.projects.groups.create(
+ * 'project_id',
+ * { group_id: 'group_id', role: 'role' },
+ * );
+ * ```
+ */
+ create(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}/groups`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project's group.
+ *
+ * @example
+ * ```ts
+ * const projectGroup =
+ * await client.admin.organization.projects.groups.retrieve(
+ * 'group_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(groupID, params, options) {
+ const { project_id, ...query } = params;
+ return this._client.get(path`/organization/projects/${project_id}/groups/${groupID}`, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the groups that have access to a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectGroup of client.admin.organization.projects.groups.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/groups`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Revokes a group's access to a project.
+ *
+ * @example
+ * ```ts
+ * const group =
+ * await client.admin.organization.projects.groups.delete(
+ * 'group_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(groupID, params, options) {
+ const { project_id } = params;
+ return this._client.delete(path`/organization/projects/${project_id}/groups/${groupID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ Groups2.Roles = Roles4;
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/service-accounts/api-keys.mjs
+var APIKeys2;
+var init_api_keys2 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/service-accounts/api-keys.mjs"() {
+ init_resource();
+ init_path();
+ APIKeys2 = class extends APIResource {
+ /**
+ * Creates an API key for a service account in the project.
+ *
+ * @example
+ * ```ts
+ * const apiKey =
+ * await client.admin.organization.projects.serviceAccounts.apiKeys.create(
+ * 'service_account_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ create(serviceAccountID, params, options) {
+ const { project_id, ...body } = params;
+ return this._client.post(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}/api_keys`, { body, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/service-accounts/service-accounts.mjs
+var ServiceAccounts;
+var init_service_accounts = __esm({
+ "node_modules/openai/resources/admin/organization/projects/service-accounts/service-accounts.mjs"() {
+ init_resource();
+ init_api_keys2();
+ init_api_keys2();
+ init_pagination();
+ init_path();
+ ServiceAccounts = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.apiKeys = new APIKeys2(this._client);
+ }
+ /**
+ * Creates a new service account in the project. By default, this also returns an
+ * unredacted API key for the service account.
+ *
+ * @example
+ * ```ts
+ * const serviceAccount =
+ * await client.admin.organization.projects.serviceAccounts.create(
+ * 'project_id',
+ * { name: 'name' },
+ * );
+ * ```
+ */
+ create(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}/service_accounts`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a service account in the project.
+ *
+ * @example
+ * ```ts
+ * const projectServiceAccount =
+ * await client.admin.organization.projects.serviceAccounts.retrieve(
+ * 'service_account_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(serviceAccountID, params, options) {
+ const { project_id } = params;
+ return this._client.get(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates a service account in the project.
+ *
+ * @example
+ * ```ts
+ * const projectServiceAccount =
+ * await client.admin.organization.projects.serviceAccounts.update(
+ * 'service_account_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ update(serviceAccountID, params, options) {
+ const { project_id, ...body } = params;
+ return this._client.post(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { body, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Returns a list of service accounts in the project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectServiceAccount of client.admin.organization.projects.serviceAccounts.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/service_accounts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes a service account from the project.
+ *
+ * Returns confirmation of service account deletion, or an error if the project is
+ * archived (archived projects have no service accounts).
+ *
+ * @example
+ * ```ts
+ * const serviceAccount =
+ * await client.admin.organization.projects.serviceAccounts.delete(
+ * 'service_account_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(serviceAccountID, params, options) {
+ const { project_id } = params;
+ return this._client.delete(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ };
+ ServiceAccounts.APIKeys = APIKeys2;
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/users/roles.mjs
+var Roles5;
+var init_roles5 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/users/roles.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Roles5 = class extends APIResource {
+ /**
+ * Assigns a project role to a user within a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.users.roles.create(
+ * 'user_id',
+ * { project_id: 'project_id', role_id: 'role_id' },
+ * );
+ * ```
+ */
+ create(userID, params, options) {
+ const { project_id, ...body } = params;
+ return this._client.post(path`/projects/${project_id}/users/${userID}/roles`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project role assigned to a user.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.users.roles.retrieve(
+ * 'role_id',
+ * { project_id: 'project_id', user_id: 'user_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options) {
+ const { project_id, user_id } = params;
+ return this._client.get(path`/projects/${project_id}/users/${user_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the project roles assigned to a user within a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const roleListResponse of client.admin.organization.projects.users.roles.list(
+ * 'user_id',
+ * { project_id: 'project_id' },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(userID, params, options) {
+ const { project_id, ...query } = params;
+ return this._client.getAPIList(path`/projects/${project_id}/users/${userID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Unassigns a project role from a user within a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.users.roles.delete(
+ * 'role_id',
+ * { project_id: 'project_id', user_id: 'user_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options) {
+ const { project_id, user_id } = params;
+ return this._client.delete(path`/projects/${project_id}/users/${user_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/users/users.mjs
+var Users2;
+var init_users2 = __esm({
+ "node_modules/openai/resources/admin/organization/projects/users/users.mjs"() {
+ init_resource();
+ init_roles5();
+ init_roles5();
+ init_pagination();
+ init_path();
+ Users2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.roles = new Roles5(this._client);
+ }
+ /**
+ * Adds a user to the project. Users must already be members of the organization to
+ * be added to a project.
+ *
+ * @example
+ * ```ts
+ * const projectUser =
+ * await client.admin.organization.projects.users.create(
+ * 'project_id',
+ * { role: 'role' },
+ * );
+ * ```
+ */
+ create(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}/users`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a user in the project.
+ *
+ * @example
+ * ```ts
+ * const projectUser =
+ * await client.admin.organization.projects.users.retrieve(
+ * 'user_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(userID, params, options) {
+ const { project_id } = params;
+ return this._client.get(path`/organization/projects/${project_id}/users/${userID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Modifies a user's role in the project.
+ *
+ * @example
+ * ```ts
+ * const projectUser =
+ * await client.admin.organization.projects.users.update(
+ * 'user_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ update(userID, params, options) {
+ const { project_id, ...body } = params;
+ return this._client.post(path`/organization/projects/${project_id}/users/${userID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Returns a list of users in the project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectUser of client.admin.organization.projects.users.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/projects/${projectID}/users`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes a user from the project.
+ *
+ * Returns confirmation of project user deletion, or an error if the project is
+ * archived (archived projects have no users).
+ *
+ * @example
+ * ```ts
+ * const user =
+ * await client.admin.organization.projects.users.delete(
+ * 'user_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(userID, params, options) {
+ const { project_id } = params;
+ return this._client.delete(path`/organization/projects/${project_id}/users/${userID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ Users2.Roles = Roles5;
+ }
+});
+
+// node_modules/openai/resources/admin/organization/projects/projects.mjs
+var Projects;
+var init_projects = __esm({
+ "node_modules/openai/resources/admin/organization/projects/projects.mjs"() {
+ init_resource();
+ init_api_keys();
+ init_api_keys();
+ init_certificates2();
+ init_certificates2();
+ init_data_retention2();
+ init_data_retention2();
+ init_hosted_tool_permissions();
+ init_hosted_tool_permissions();
+ init_model_permissions();
+ init_model_permissions();
+ init_rate_limits();
+ init_rate_limits();
+ init_roles3();
+ init_roles3();
+ init_spend_alerts2();
+ init_spend_alerts2();
+ init_spend_limit2();
+ init_spend_limit2();
+ init_groups2();
+ init_groups2();
+ init_service_accounts();
+ init_service_accounts();
+ init_users2();
+ init_users2();
+ init_pagination();
+ init_path();
+ Projects = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.users = new Users2(this._client);
+ this.serviceAccounts = new ServiceAccounts(this._client);
+ this.apiKeys = new APIKeys(this._client);
+ this.rateLimits = new RateLimits(this._client);
+ this.modelPermissions = new ModelPermissions(this._client);
+ this.hostedToolPermissions = new HostedToolPermissions(this._client);
+ this.groups = new Groups2(this._client);
+ this.roles = new Roles3(this._client);
+ this.dataRetention = new DataRetention2(this._client);
+ this.spendLimit = new SpendLimit2(this._client);
+ this.spendAlerts = new SpendAlerts2(this._client);
+ this.certificates = new Certificates2(this._client);
+ }
+ /**
+ * Create a new project in the organization. Projects can be created and archived,
+ * but cannot be deleted.
+ *
+ * @example
+ * ```ts
+ * const project =
+ * await client.admin.organization.projects.create({
+ * name: 'name',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/organization/projects", {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project.
+ *
+ * @example
+ * ```ts
+ * const project =
+ * await client.admin.organization.projects.retrieve(
+ * 'project_id',
+ * );
+ * ```
+ */
+ retrieve(projectID, options) {
+ return this._client.get(path`/organization/projects/${projectID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Modifies a project in the organization.
+ *
+ * @example
+ * ```ts
+ * const project =
+ * await client.admin.organization.projects.update(
+ * 'project_id',
+ * );
+ * ```
+ */
+ update(projectID, body, options) {
+ return this._client.post(path`/organization/projects/${projectID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Returns a list of projects.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const project of client.admin.organization.projects.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/projects", ConversationCursorPage, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Archives a project in the organization. Archived projects cannot be used or
+ * updated.
+ *
+ * @example
+ * ```ts
+ * const project =
+ * await client.admin.organization.projects.archive(
+ * 'project_id',
+ * );
+ * ```
+ */
+ archive(projectID, options) {
+ return this._client.post(path`/organization/projects/${projectID}/archive`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ Projects.Users = Users2;
+ Projects.ServiceAccounts = ServiceAccounts;
+ Projects.APIKeys = APIKeys;
+ Projects.RateLimits = RateLimits;
+ Projects.ModelPermissions = ModelPermissions;
+ Projects.HostedToolPermissions = HostedToolPermissions;
+ Projects.Groups = Groups2;
+ Projects.Roles = Roles3;
+ Projects.DataRetention = DataRetention2;
+ Projects.SpendLimit = SpendLimit2;
+ Projects.SpendAlerts = SpendAlerts2;
+ Projects.Certificates = Certificates2;
+ }
+});
+
+// node_modules/openai/resources/admin/organization/users/roles.mjs
+var Roles6;
+var init_roles6 = __esm({
+ "node_modules/openai/resources/admin/organization/users/roles.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Roles6 = class extends APIResource {
+ /**
+ * Assigns an organization role to a user within the organization.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.users.roles.create(
+ * 'user_id',
+ * { role_id: 'role_id' },
+ * );
+ * ```
+ */
+ create(userID, body, options) {
+ return this._client.post(path`/organization/users/${userID}/roles`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an organization role assigned to a user.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.users.roles.retrieve(
+ * 'role_id',
+ * { user_id: 'user_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options) {
+ const { user_id } = params;
+ return this._client.get(path`/organization/users/${user_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the organization roles assigned to a user within the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const roleListResponse of client.admin.organization.users.roles.list(
+ * 'user_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(userID, query = {}, options) {
+ return this._client.getAPIList(path`/organization/users/${userID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Unassigns an organization role from a user within the organization.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.users.roles.delete(
+ * 'role_id',
+ * { user_id: 'user_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options) {
+ const { user_id } = params;
+ return this._client.delete(path`/organization/users/${user_id}/roles/${roleID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/admin/organization/users/users.mjs
+var Users3;
+var init_users3 = __esm({
+ "node_modules/openai/resources/admin/organization/users/users.mjs"() {
+ init_resource();
+ init_roles6();
+ init_roles6();
+ init_pagination();
+ init_path();
+ Users3 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.roles = new Roles6(this._client);
+ }
+ /**
+ * Retrieves a user by their identifier.
+ *
+ * @example
+ * ```ts
+ * const organizationUser =
+ * await client.admin.organization.users.retrieve('user_id');
+ * ```
+ */
+ retrieve(userID, options) {
+ return this._client.get(path`/organization/users/${userID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Modifies a user's role in the organization.
+ *
+ * @example
+ * ```ts
+ * const organizationUser =
+ * await client.admin.organization.users.update('user_id');
+ * ```
+ */
+ update(userID, body, options) {
+ return this._client.post(path`/organization/users/${userID}`, {
+ body,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists all of the users in the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const organizationUser of client.admin.organization.users.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/organization/users", ConversationCursorPage, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes a user from the organization.
+ *
+ * @example
+ * ```ts
+ * const user = await client.admin.organization.users.delete(
+ * 'user_id',
+ * );
+ * ```
+ */
+ delete(userID, options) {
+ return this._client.delete(path`/organization/users/${userID}`, {
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ };
+ Users3.Roles = Roles6;
+ }
+});
+
+// node_modules/openai/resources/admin/organization/organization.mjs
+var Organization;
+var init_organization = __esm({
+ "node_modules/openai/resources/admin/organization/organization.mjs"() {
+ init_resource();
+ init_admin_api_keys();
+ init_admin_api_keys();
+ init_audit_logs();
+ init_audit_logs();
+ init_certificates();
+ init_certificates();
+ init_data_retention();
+ init_data_retention();
+ init_invites();
+ init_invites();
+ init_roles();
+ init_roles();
+ init_spend_alerts();
+ init_spend_alerts();
+ init_spend_limit();
+ init_spend_limit();
+ init_usage();
+ init_usage();
+ init_groups();
+ init_groups();
+ init_projects();
+ init_projects();
+ init_users3();
+ init_users3();
+ Organization = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.auditLogs = new AuditLogs(this._client);
+ this.adminAPIKeys = new AdminAPIKeys(this._client);
+ this.usage = new Usage(this._client);
+ this.invites = new Invites(this._client);
+ this.users = new Users3(this._client);
+ this.groups = new Groups(this._client);
+ this.roles = new Roles(this._client);
+ this.dataRetention = new DataRetention(this._client);
+ this.spendLimit = new SpendLimit(this._client);
+ this.spendAlerts = new SpendAlerts(this._client);
+ this.certificates = new Certificates(this._client);
+ this.projects = new Projects(this._client);
+ }
+ };
+ Organization.AuditLogs = AuditLogs;
+ Organization.AdminAPIKeys = AdminAPIKeys;
+ Organization.Usage = Usage;
+ Organization.Invites = Invites;
+ Organization.Users = Users3;
+ Organization.Groups = Groups;
+ Organization.Roles = Roles;
+ Organization.DataRetention = DataRetention;
+ Organization.SpendLimit = SpendLimit;
+ Organization.SpendAlerts = SpendAlerts;
+ Organization.Certificates = Certificates;
+ Organization.Projects = Projects;
+ }
+});
+
+// node_modules/openai/resources/admin/admin.mjs
+var Admin;
+var init_admin = __esm({
+ "node_modules/openai/resources/admin/admin.mjs"() {
+ init_resource();
+ init_organization();
+ init_organization();
+ Admin = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.organization = new Organization(this._client);
+ }
+ };
+ Admin.Organization = Organization;
+ }
+});
+
+// node_modules/openai/resources/audio/speech.mjs
+var Speech;
+var init_speech = __esm({
+ "node_modules/openai/resources/audio/speech.mjs"() {
+ init_resource();
+ init_headers();
+ Speech = class extends APIResource {
+ /**
+ * Generates audio from the input text.
+ *
+ * Returns the audio file content, or a stream of audio events.
+ *
+ * @example
+ * ```ts
+ * const speech = await client.audio.speech.create({
+ * input: 'input',
+ * model: 'tts-1',
+ * voice: 'alloy',
+ * });
+ *
+ * const content = await speech.blob();
+ * console.log(content);
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/audio/speech", {
+ body,
+ ...options,
+ headers: buildHeaders([{ Accept: "application/octet-stream" }, options?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/audio/transcriptions.mjs
+var Transcriptions;
+var init_transcriptions = __esm({
+ "node_modules/openai/resources/audio/transcriptions.mjs"() {
+ init_resource();
+ init_uploads();
+ Transcriptions = class extends APIResource {
+ create(body, options) {
+ return this._client.post("/audio/transcriptions", multipartFormRequestOptions({
+ body,
+ ...options,
+ stream: body.stream ?? false,
+ __metadata: { model: body.model },
+ __security: { bearerAuth: true }
+ }, this._client));
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/audio/translations.mjs
+var Translations;
+var init_translations = __esm({
+ "node_modules/openai/resources/audio/translations.mjs"() {
+ init_resource();
+ init_uploads();
+ Translations = class extends APIResource {
+ create(body, options) {
+ return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model }, __security: { bearerAuth: true } }, this._client));
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/audio/audio.mjs
+var Audio;
+var init_audio = __esm({
+ "node_modules/openai/resources/audio/audio.mjs"() {
+ init_resource();
+ init_speech();
+ init_speech();
+ init_transcriptions();
+ init_transcriptions();
+ init_translations();
+ init_translations();
+ Audio = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.transcriptions = new Transcriptions(this._client);
+ this.translations = new Translations(this._client);
+ this.speech = new Speech(this._client);
+ }
+ };
+ Audio.Transcriptions = Transcriptions;
+ Audio.Translations = Translations;
+ Audio.Speech = Speech;
+ }
+});
+
+// node_modules/openai/resources/batches.mjs
+var Batches;
+var init_batches = __esm({
+ "node_modules/openai/resources/batches.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Batches = class extends APIResource {
+ /**
+ * Creates and executes a batch from an uploaded file of requests
+ */
+ create(body, options) {
+ return this._client.post("/batches", { body, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Retrieves a batch.
+ */
+ retrieve(batchID, options) {
+ return this._client.get(path`/batches/${batchID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * List your organization's batches.
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/batches", CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancels an in-progress batch. The batch will be in status `cancelling` for up to
+ * 10 minutes, before changing to `cancelled`, where it will have partial results
+ * (if any) available in the output file.
+ */
+ cancel(batchID, options) {
+ return this._client.post(path`/batches/${batchID}/cancel`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/assistants.mjs
+var Assistants;
+var init_assistants = __esm({
+ "node_modules/openai/resources/beta/assistants.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Assistants = class extends APIResource {
+ /**
+ * Create an assistant with a model and instructions.
+ *
+ * @deprecated
+ */
+ create(body, options) {
+ return this._client.post("/assistants", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves an assistant.
+ *
+ * @deprecated
+ */
+ retrieve(assistantID, options) {
+ return this._client.get(path`/assistants/${assistantID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies an assistant.
+ *
+ * @deprecated
+ */
+ update(assistantID, body, options) {
+ return this._client.post(path`/assistants/${assistantID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of assistants.
+ *
+ * @deprecated
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/assistants", CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete an assistant.
+ *
+ * @deprecated
+ */
+ delete(assistantID, options) {
+ return this._client.delete(path`/assistants/${assistantID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/realtime/sessions.mjs
+var Sessions;
+var init_sessions = __esm({
+ "node_modules/openai/resources/beta/realtime/sessions.mjs"() {
+ init_resource();
+ init_headers();
+ Sessions = class extends APIResource {
+ /**
+ * Create an ephemeral API token for use in client-side applications with the
+ * Realtime API. Can be configured with the same session parameters as the
+ * `session.update` client event.
+ *
+ * It responds with a session object, plus a `client_secret` key which contains a
+ * usable ephemeral API token that can be used to authenticate browser clients for
+ * the Realtime API.
+ *
+ * @example
+ * ```ts
+ * const session =
+ * await client.beta.realtime.sessions.create();
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/realtime/sessions", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/realtime/transcription-sessions.mjs
+var TranscriptionSessions;
+var init_transcription_sessions = __esm({
+ "node_modules/openai/resources/beta/realtime/transcription-sessions.mjs"() {
+ init_resource();
+ init_headers();
+ TranscriptionSessions = class extends APIResource {
+ /**
+ * Create an ephemeral API token for use in client-side applications with the
+ * Realtime API specifically for realtime transcriptions. Can be configured with
+ * the same session parameters as the `transcription_session.update` client event.
+ *
+ * It responds with a session object, plus a `client_secret` key which contains a
+ * usable ephemeral API token that can be used to authenticate browser clients for
+ * the Realtime API.
+ *
+ * @example
+ * ```ts
+ * const transcriptionSession =
+ * await client.beta.realtime.transcriptionSessions.create();
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/realtime/transcription_sessions", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/realtime/realtime.mjs
+var Realtime;
+var init_realtime = __esm({
+ "node_modules/openai/resources/beta/realtime/realtime.mjs"() {
+ init_resource();
+ init_sessions();
+ init_sessions();
+ init_transcription_sessions();
+ init_transcription_sessions();
+ Realtime = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.sessions = new Sessions(this._client);
+ this.transcriptionSessions = new TranscriptionSessions(this._client);
+ }
+ };
+ Realtime.Sessions = Sessions;
+ Realtime.TranscriptionSessions = TranscriptionSessions;
+ }
+});
+
+// node_modules/openai/resources/beta/agents/environments/files.mjs
+var Files;
+var init_files = __esm({
+ "node_modules/openai/resources/beta/agents/environments/files.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Files = class extends APIResource {
+ /**
+ * Copies inline bytes or a Files API file into a connected execution environment.
+ * See
+ * [environment files](https://developers.openai.com/api/docs/guides/agents-api/environments/files).
+ *
+ * @example
+ * ```ts
+ * const environmentFile =
+ * await client.beta.agents.environments.files.create(
+ * 'environment_id',
+ * {
+ * type: 'inline',
+ * path: '/workspace/example.txt',
+ * data: 'SGVsbG8K',
+ * },
+ * );
+ * ```
+ */
+ create(environmentID, body, options) {
+ return this._client.post(path`/agents/environments/${environmentID}/files`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists live files on a connected execution environment with optional directory
+ * filtering and opaque cursor pagination. See
+ * [environment files](https://developers.openai.com/api/docs/guides/agents-api/environments/files).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const environmentFile of client.beta.agents.environments.files.list(
+ * 'environment_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(environmentID, query = {}, options) {
+ return this._client.getAPIList(path`/agents/environments/${environmentID}/files`, TokenPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/environments/templates.mjs
+var Templates;
+var init_templates = __esm({
+ "node_modules/openai/resources/beta/agents/environments/templates.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Templates = class extends APIResource {
+ /**
+ * Creates reusable environment configuration without returning confidential setup
+ * commands or environment values. See
+ * [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
+ *
+ * @example
+ * ```ts
+ * const environmentTemplate =
+ * await client.beta.agents.environments.templates.create();
+ * ```
+ */
+ create(body = {}, options) {
+ return this._client.post("/agents/environments/templates", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves reusable environment configuration without returning confidential
+ * values. See
+ * [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
+ *
+ * @example
+ * ```ts
+ * const environmentTemplate =
+ * await client.beta.agents.environments.templates.retrieve(
+ * 'environment_template_id',
+ * );
+ * ```
+ */
+ retrieve(environmentTemplateID, options) {
+ return this._client.get(path`/agents/environments/templates/${environmentTemplateID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Updates reusable environment configuration without returning confidential
+ * values. See
+ * [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
+ *
+ * @example
+ * ```ts
+ * const environmentTemplate =
+ * await client.beta.agents.environments.templates.update(
+ * 'environment_template_id',
+ * );
+ * ```
+ */
+ update(environmentTemplateID, body = {}, options) {
+ return this._client.post(path`/agents/environments/templates/${environmentTemplateID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists reusable environment templates without returning confidential values. See
+ * [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const environmentTemplate of client.beta.agents.environments.templates.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/agents/environments/templates", CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes reusable environment configuration and all confidential template inputs.
+ * See
+ * [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
+ *
+ * @example
+ * ```ts
+ * const environmentTemplateDeleted =
+ * await client.beta.agents.environments.templates.delete(
+ * 'environment_template_id',
+ * );
+ * ```
+ */
+ delete(environmentTemplateID, options) {
+ return this._client.delete(path`/agents/environments/templates/${environmentTemplateID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/environments/environments.mjs
+var Environments;
+var init_environments = __esm({
+ "node_modules/openai/resources/beta/agents/environments/environments.mjs"() {
+ init_resource();
+ init_files();
+ init_files();
+ init_templates();
+ init_templates();
+ init_headers();
+ init_path();
+ Environments = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.files = new Files(this._client);
+ this.templates = new Templates(this._client);
+ }
+ /**
+ * Retrieves an execution environment's connection status and safe installed
+ * metadata. See
+ * [environment lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle).
+ *
+ * @example
+ * ```ts
+ * const environmentInfo =
+ * await client.beta.agents.environments.retrieve(
+ * 'environment_id',
+ * );
+ * ```
+ */
+ retrieve(environmentID, options) {
+ return this._client.get(path`/agents/environments/${environmentID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Environments.Files = Files;
+ Environments.Templates = Templates;
+ }
+});
+
+// node_modules/openai/lib/agents/turn-state.mjs
+var _TurnState_turnID, _TurnState_turnEnded, _TurnState_eventIDs, _TurnState_calls, TurnState;
+var init_turn_state = __esm({
+ "node_modules/openai/lib/agents/turn-state.mjs"() {
+ init_tslib();
+ TurnState = class {
+ constructor() {
+ _TurnState_turnID.set(this, void 0);
+ _TurnState_turnEnded.set(this, false);
+ _TurnState_eventIDs.set(this, /* @__PURE__ */ new Set());
+ _TurnState_calls.set(this, /* @__PURE__ */ new Set());
+ }
+ /** Records a delivery unless its event ID is in the bounded recent window. */
+ accept(event) {
+ if (__classPrivateFieldGet(this, _TurnState_eventIDs, "f").has(event.event_id)) {
+ return false;
+ }
+ if (__classPrivateFieldGet(this, _TurnState_eventIDs, "f").size === 1024) {
+ const oldest = __classPrivateFieldGet(this, _TurnState_eventIDs, "f").values().next();
+ if (!oldest.done) {
+ __classPrivateFieldGet(this, _TurnState_eventIDs, "f").delete(oldest.value);
+ }
+ }
+ __classPrivateFieldGet(this, _TurnState_eventIDs, "f").add(event.event_id);
+ if (event.type === "agent.session.turn.created" && event.turn.subagent_id === null && __classPrivateFieldGet(this, _TurnState_turnID, "f") === void 0) {
+ __classPrivateFieldSet(this, _TurnState_turnID, event.turn_id, "f");
+ }
+ if ((event.type === "agent.session.turn.completed" || event.type === "agent.session.turn.failed" || event.type === "agent.session.turn.cancelled") && __classPrivateFieldGet(this, _TurnState_turnID, "f") !== void 0 && event.turn_id === __classPrivateFieldGet(this, _TurnState_turnID, "f")) {
+ __classPrivateFieldSet(this, _TurnState_turnEnded, true, "f");
+ }
+ return true;
+ }
+ /** Checks session termination after updating the selected turn state. */
+ terminal(event) {
+ return event.type === "agent.session.failed" || event.type === "agent.session.idle" && __classPrivateFieldGet(this, _TurnState_turnEnded, "f");
+ }
+ /** Returns each tool call once for the full invocation, including subagent turns. */
+ call(event) {
+ if (event.type !== "agent.session.turn.item.added" || event.item.type !== "function_call") {
+ return;
+ }
+ const call = event.item;
+ const key = JSON.stringify([call.turn_id, call.call_id]);
+ if (__classPrivateFieldGet(this, _TurnState_calls, "f").has(key)) {
+ return;
+ }
+ __classPrivateFieldGet(this, _TurnState_calls, "f").add(key);
+ return call;
+ }
+ };
+ _TurnState_turnID = /* @__PURE__ */ new WeakMap(), _TurnState_turnEnded = /* @__PURE__ */ new WeakMap(), _TurnState_eventIDs = /* @__PURE__ */ new WeakMap(), _TurnState_calls = /* @__PURE__ */ new WeakMap();
+ }
+});
+
+// node_modules/openai/lib/agents/agent-session-stream.mjs
+function isInputContent(value) {
+ if (!isObj(value)) {
+ return false;
+ }
+ const content = value;
+ let field;
+ if (content["type"] === "input_text") {
+ field = "text";
+ } else if (content["type"] === "input_image") {
+ field = "image_url";
+ } else {
+ return false;
+ }
+ return hasOwn(content, "type") && hasOwn(content, field) && typeof content[field] === "string";
+}
+function normalizedOutput(value) {
+ if (value === null) {
+ return null;
+ }
+ if (typeof value === "string" || Array.isArray(value) && value.every(isInputContent)) {
+ return value;
+ }
+ throw new OpenAIError("Tool output must be text, content, a JSON object, or null");
+}
+function toolResult(call, value) {
+ const output = isObj(value) ? JSON.stringify(value) : value;
+ const serialized = JSON.stringify(output);
+ if (serialized === void 0) {
+ throw new OpenAIError("Tool output must be JSON serializable");
+ }
+ return {
+ type: "agent.session.input.tool_result",
+ turn_id: call.turn_id,
+ call_id: call.call_id,
+ success: true,
+ output: normalizedOutput(typeof output === "string" ? output : JSON.parse(serialized))
+ };
+}
+async function cancelBody(response) {
+ try {
+ await response?.body?.cancel();
+ } catch {
+ }
+}
+var _AgentSessionStream_instances, _AgentSessionStream_consumed, _AgentSessionStream_stream, _AgentSessionStream_response, _AgentSessionStream_reading, _AgentSessionStream_sessions, _AgentSessionStream_sessionID, _AgentSessionStream_input, _AgentSessionStream_handlers, _AgentSessionStream_inputKey, _AgentSessionStream_options, _AgentSessionStream_iterate, _AgentSessionStream_result, _AgentSessionStream_checkAbort, _AgentSessionStream_abortError, _AgentSessionStream_wait, _AgentSessionStream_submit, AgentSessionStream;
+var init_agent_session_stream = __esm({
+ "node_modules/openai/lib/agents/agent-session-stream.mjs"() {
+ init_tslib();
+ init_turn_state();
+ init_error();
+ init_headers();
+ init_uuid();
+ init_values();
+ AgentSessionStream = class {
+ /** Creates an unstarted helper. Prefer client.beta.agents.sessions.stream(). */
+ constructor(sessions, sessionID, params, options) {
+ _AgentSessionStream_instances.add(this);
+ this.controller = new AbortController();
+ _AgentSessionStream_consumed.set(this, false);
+ _AgentSessionStream_stream.set(this, void 0);
+ _AgentSessionStream_response.set(this, void 0);
+ _AgentSessionStream_reading.set(this, false);
+ _AgentSessionStream_sessions.set(this, void 0);
+ _AgentSessionStream_sessionID.set(this, void 0);
+ _AgentSessionStream_input.set(this, void 0);
+ _AgentSessionStream_handlers.set(this, void 0);
+ _AgentSessionStream_inputKey.set(this, void 0);
+ _AgentSessionStream_options.set(this, void 0);
+ const input = typeof params.input === "string" ? [{ role: "user", content: [{ type: "input_text", text: params.input }] }] : params.input;
+ if (params.input.length === 0) {
+ throw new OpenAIError("input must not be empty");
+ }
+ __classPrivateFieldSet(this, _AgentSessionStream_sessions, sessions, "f");
+ __classPrivateFieldSet(this, _AgentSessionStream_sessionID, sessionID, "f");
+ __classPrivateFieldSet(this, _AgentSessionStream_input, { type: "agent.session.input.message", input }, "f");
+ __classPrivateFieldSet(this, _AgentSessionStream_handlers, new Map(Object.entries(params.toolHandlers ?? {})), "f");
+ const headers = buildHeaders([options?.headers]);
+ __classPrivateFieldSet(this, _AgentSessionStream_inputKey, headers.nulls.has("idempotency-key") ? void 0 : headers.values.get("idempotency-key") ?? params.idempotencyKey ?? options?.idempotencyKey ?? uuid4(), "f");
+ headers.values.delete("idempotency-key");
+ headers.nulls.delete("idempotency-key");
+ const { idempotencyKey: _key, ...rest } = options ?? {};
+ __classPrivateFieldSet(this, _AgentSessionStream_options, { ...rest, headers }, "f");
+ }
+ /** Closes local requests without cancelling the turn; an optional reason becomes the abort error's cause. */
+ abort(reason) {
+ this.controller.abort(reason);
+ __classPrivateFieldGet(this, _AgentSessionStream_stream, "f")?.controller.abort(this.controller.signal.reason);
+ if (!__classPrivateFieldGet(this, _AgentSessionStream_reading, "f")) {
+ void cancelBody(__classPrivateFieldGet(this, _AgentSessionStream_response, "f"));
+ }
+ }
+ /** Starts iteration once; use for await to ensure early exits close the connection. */
+ [(_AgentSessionStream_consumed = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_stream = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_response = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_reading = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_sessions = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_sessionID = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_input = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_handlers = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_inputKey = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_options = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
+ if (__classPrivateFieldGet(this, _AgentSessionStream_consumed, "f")) {
+ throw new OpenAIError("An AgentSessionStream can only be consumed once");
+ }
+ __classPrivateFieldSet(this, _AgentSessionStream_consumed, true, "f");
+ return __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_iterate).call(this);
+ }
+ };
+ _AgentSessionStream_iterate = async function* _AgentSessionStream_iterate2() {
+ const externalSignal = __classPrivateFieldGet(this, _AgentSessionStream_options, "f").signal;
+ const abort = () => this.abort(externalSignal?.aborted ? externalSignal.reason : this.controller.signal.reason);
+ externalSignal?.addEventListener("abort", abort, { once: true });
+ this.controller.signal.addEventListener("abort", abort, { once: true });
+ const options = { ...__classPrivateFieldGet(this, _AgentSessionStream_options, "f"), signal: this.controller.signal };
+ const state3 = new TurnState();
+ try {
+ if (externalSignal?.aborted) {
+ this.abort(externalSignal.reason);
+ }
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ const session = await __classPrivateFieldGet(this, _AgentSessionStream_sessions, "f").retrieve(__classPrivateFieldGet(this, _AgentSessionStream_sessionID, "f"), options);
+ if (session.status !== "idle") {
+ throw new OpenAIError("sessions.stream requires an idle session; use sessions.events.stream for active sessions");
+ }
+ const subscription = await __classPrivateFieldGet(this, _AgentSessionStream_sessions, "f").events.stream(__classPrivateFieldGet(this, _AgentSessionStream_sessionID, "f"), options).withResponse();
+ __classPrivateFieldSet(this, _AgentSessionStream_stream, subscription.data, "f");
+ __classPrivateFieldSet(this, _AgentSessionStream_response, subscription.response, "f");
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ await __classPrivateFieldGet(this, _AgentSessionStream_sessions, "f").events.create(__classPrivateFieldGet(this, _AgentSessionStream_sessionID, "f"), {
+ events: [__classPrivateFieldGet(this, _AgentSessionStream_input, "f")],
+ // Spread creates an own data property without invoking inherited setters or changing the object prototype.
+ ...__classPrivateFieldGet(this, _AgentSessionStream_inputKey, "f") === void 0 ? {} : { "Idempotency-Key": __classPrivateFieldGet(this, _AgentSessionStream_inputKey, "f") }
+ }, {
+ ...options,
+ headers: buildHeaders([options.headers, { "Idempotency-Key": __classPrivateFieldGet(this, _AgentSessionStream_inputKey, "f") ?? null }])
+ });
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ __classPrivateFieldSet(this, _AgentSessionStream_reading, true, "f");
+ for await (const event of __classPrivateFieldGet(this, _AgentSessionStream_stream, "f")) {
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ if (!state3.accept(event)) {
+ continue;
+ }
+ const terminal = state3.terminal(event);
+ const pendingCall = state3.call(event);
+ const handler = pendingCall && __classPrivateFieldGet(this, _AgentSessionStream_handlers, "f").get(pendingCall.name);
+ const call = pendingCall && handler ? structuredClone(pendingCall) : void 0;
+ if (terminal) {
+ __classPrivateFieldGet(this, _AgentSessionStream_stream, "f").controller.abort();
+ }
+ yield event;
+ if (terminal) {
+ return;
+ }
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ if (!call || !handler) {
+ continue;
+ }
+ const result = await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_result).call(this, call, handler);
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_submit).call(this, result, options);
+ }
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ throw new OpenAIError("Session event stream ended before the turn reached idle or failed");
+ } finally {
+ externalSignal?.removeEventListener("abort", abort);
+ this.controller.signal.removeEventListener("abort", abort);
+ this.abort();
+ }
+ }, _AgentSessionStream_result = async function _AgentSessionStream_result2(call, handler) {
+ try {
+ const args = typeof call.arguments === "string" ? JSON.parse(call.arguments) : call.arguments;
+ if (!isObj(args)) {
+ throw new OpenAIError("Function arguments must be a JSON object");
+ }
+ return toolResult(call, await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_wait).call(this, () => handler(args)));
+ } catch {
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ return {
+ type: "agent.session.input.tool_result",
+ turn_id: call.turn_id,
+ call_id: call.call_id,
+ success: false,
+ error: "Tool handler failed."
+ };
+ }
+ }, _AgentSessionStream_checkAbort = function _AgentSessionStream_checkAbort2() {
+ if (this.controller.signal.aborted) {
+ throw __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_abortError).call(this);
+ }
+ }, _AgentSessionStream_abortError = function _AgentSessionStream_abortError2() {
+ const error = new APIUserAbortError();
+ Object.defineProperty(error, "cause", {
+ value: this.controller.signal.reason,
+ writable: true,
+ configurable: true
+ });
+ return error;
+ }, _AgentSessionStream_wait = async function _AgentSessionStream_wait2(action) {
+ let onAbort;
+ const aborted = new Promise((_resolve, reject) => {
+ onAbort = () => reject(__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_abortError).call(this));
+ this.controller.signal.addEventListener("abort", onAbort, { once: true });
+ });
+ try {
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ const invoke = async () => await action();
+ return await Promise.race([invoke(), aborted]);
+ } finally {
+ if (onAbort) {
+ this.controller.signal.removeEventListener("abort", onAbort);
+ }
+ }
+ }, _AgentSessionStream_submit = async function _AgentSessionStream_submit2(result, options, key = uuid4(), attempt = 0) {
+ __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
+ try {
+ await __classPrivateFieldGet(this, _AgentSessionStream_sessions, "f").events.create(__classPrivateFieldGet(this, _AgentSessionStream_sessionID, "f"), { events: [result], "Idempotency-Key": key }, options);
+ } catch (error) {
+ const delay2 = [100, 300, 600][attempt];
+ if (delay2 === void 0 || !(error instanceof BadRequestError) || error.code !== "invalid_request_error" || !error.error || !("message" in error.error) || error.error.message !== `Unknown pending tool call: ${result.call_id}`) {
+ throw error;
+ }
+ let timer;
+ try {
+ await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_wait).call(this, () => (
+ // oxlint-disable-next-line promise/avoid-new -- Own the registration timer so cancellation clears it promptly.
+ new Promise((resolve3) => {
+ timer = setTimeout(resolve3, delay2);
+ })
+ ));
+ } finally {
+ if (timer !== void 0) {
+ clearTimeout(timer);
+ }
+ }
+ await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_submit2).call(this, result, options, key, attempt + 1);
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/artifacts.mjs
+var Artifacts;
+var init_artifacts = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/artifacts.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Artifacts = class extends APIResource {
+ /**
+ * Retrieves immutable metadata for one durable session artifact. See
+ * [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
+ *
+ * @example
+ * ```ts
+ * const sessionArtifact =
+ * await client.beta.agents.sessions.artifacts.retrieve(
+ * 'artifact_id',
+ * { session_id: 'session_id' },
+ * );
+ * ```
+ */
+ retrieve(artifactID, params, options) {
+ const { session_id } = params;
+ return this._client.get(path`/agents/sessions/${session_id}/artifacts/${artifactID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists immutable artifacts published by completed hosted session turns. See
+ * [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const sessionArtifact of client.beta.agents.sessions.artifacts.list(
+ * 'session_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(sessionID, query = {}, options) {
+ return this._client.getAPIList(path`/agents/sessions/${sessionID}/artifacts`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes an immutable session artifact without deleting its live environment file
+ * or original Files API object. See
+ * [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
+ *
+ * @example
+ * ```ts
+ * const sessionArtifactDeleted =
+ * await client.beta.agents.sessions.artifacts.delete(
+ * 'artifact_id',
+ * { session_id: 'session_id' },
+ * );
+ * ```
+ */
+ delete(artifactID, params, options) {
+ const { session_id } = params;
+ return this._client.delete(path`/agents/sessions/${session_id}/artifacts/${artifactID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Downloads immutable session artifact bytes after the execution environment
+ * expires. See
+ * [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.beta.agents.sessions.artifacts.content(
+ * 'artifact_id',
+ * { session_id: 'session_id' },
+ * );
+ *
+ * const content = await response.blob();
+ * console.log(content);
+ * ```
+ */
+ content(artifactID, params, options) {
+ const { session_id } = params;
+ return this._client.get(path`/agents/sessions/${session_id}/artifacts/${artifactID}/content`, {
+ ...options,
+ headers: buildHeaders([
+ { "OpenAI-Beta": "agents=v1", Accept: "application/octet-stream" },
+ options?.headers
+ ]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/events.mjs
+var Events;
+var init_events = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/events.mjs"() {
+ init_resource();
+ init_headers();
+ init_path();
+ Events = class extends APIResource {
+ /**
+ * Submits message, cancellation, or tool-result events to a managed agent session.
+ * Cancellation can recover a still-open turn whose backend execution has ended by
+ * marking it cancelled and abandoning unpublished outputs. Saved results,
+ * published files, and existing terminal outcomes are preserved. HTTP 202 confirms
+ * acceptance, not durable completion. See
+ * [session events](https://developers.openai.com/api/docs/guides/agents-api/sessions/events).
+ *
+ * @example
+ * ```ts
+ * await client.beta.agents.sessions.events.create(
+ * 'session_id',
+ * {
+ * events: [
+ * {
+ * input: [
+ * {
+ * content: [{ text: 'text', type: 'input_text' }],
+ * role: 'user',
+ * },
+ * ],
+ * type: 'agent.session.input.message',
+ * },
+ * ],
+ * },
+ * );
+ * ```
+ */
+ create(sessionID, params, options) {
+ const { "Idempotency-Key": idempotencyKey, ...body } = params;
+ return this._client.post(path`/agents/sessions/${sessionID}/events`, {
+ body,
+ ...options,
+ headers: buildHeaders([
+ {
+ "OpenAI-Beta": "agents=v1",
+ Accept: "*/*",
+ ...idempotencyKey != null ? { "Idempotency-Key": idempotencyKey } : void 0
+ },
+ options?.headers
+ ]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Streams live events for an agent session. See
+ * [session events](https://developers.openai.com/api/docs/guides/agents-api/sessions/events).
+ *
+ * @example
+ * ```ts
+ * const agentSessionEvent =
+ * await client.beta.agents.sessions.events.stream(
+ * 'session_id',
+ * );
+ * ```
+ */
+ stream(sessionID, options) {
+ return this._client.get(path`/agents/sessions/${sessionID}/events`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1", Accept: "text/event-stream" }, options?.headers]),
+ stream: true,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/items.mjs
+var Items;
+var init_items = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/items.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Items = class extends APIResource {
+ /**
+ * Lists items produced by the session's root agent, including its interactions
+ * with subagents. Each subagent has its own item history. See
+ * [inspecting agent output](https://developers.openai.com/api/docs/guides/agents-api/observability).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const agentSessionItem of client.beta.agents.sessions.items.list(
+ * 'session_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(sessionID, query = {}, options) {
+ return this._client.getAPIList(path`/agents/sessions/${sessionID}/items`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/turns.mjs
+var Turns;
+var init_turns = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/turns.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Turns = class extends APIResource {
+ /**
+ * Retrieves a turn's current status, timestamps, usage, and error. Returns 404 if
+ * the turn does not belong to the session. See
+ * [session turns](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage#inspect-session-turns).
+ *
+ * @example
+ * ```ts
+ * const turn =
+ * await client.beta.agents.sessions.turns.retrieve(
+ * 'turn_id',
+ * { session_id: 'session_id' },
+ * );
+ * ```
+ */
+ retrieve(turnID, params, options) {
+ const { session_id } = params;
+ return this._client.get(path`/agents/sessions/${session_id}/turns/${turnID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists turns by creation time and turn ID. The after cursor is exclusive in the
+ * selected order. See
+ * [session turns](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage#inspect-session-turns).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const turn of client.beta.agents.sessions.turns.list(
+ * 'session_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(sessionID, query = {}, options) {
+ return this._client.getAPIList(path`/agents/sessions/${sessionID}/turns`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/subagents/items.mjs
+var Items2;
+var init_items2 = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/subagents/items.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Items2 = class extends APIResource {
+ /**
+ * Lists this subagent's own items across all of its turns. See
+ * [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const agentSessionItem of client.beta.agents.sessions.subagents.items.list(
+ * 'subagent_id',
+ * { session_id: 'session_id' },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(subagentID, params, options) {
+ const { session_id, ...query } = params;
+ return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagentID}/items`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/subagents/turns/items.mjs
+var Items3;
+var init_items3 = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/subagents/turns/items.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Items3 = class extends APIResource {
+ /**
+ * Lists items belonging to one turn of this subagent. See
+ * [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const agentSessionItem of client.beta.agents.sessions.subagents.turns.items.list(
+ * 'turn_id',
+ * { session_id: 'session_id', subagent_id: 'subagent_id' },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(turnID, params, options) {
+ const { session_id, subagent_id, ...query } = params;
+ return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagent_id}/turns/${turnID}/items`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/subagents/turns/turns.mjs
+var Turns2;
+var init_turns2 = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/subagents/turns/turns.mjs"() {
+ init_resource();
+ init_items3();
+ init_items3();
+ init_pagination();
+ init_headers();
+ init_path();
+ Turns2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.items = new Items3(this._client);
+ }
+ /**
+ * Retrieves a turn belonging to this subagent. See
+ * [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
+ *
+ * @example
+ * ```ts
+ * const turn =
+ * await client.beta.agents.sessions.subagents.turns.retrieve(
+ * 'turn_id',
+ * {
+ * session_id: 'session_id',
+ * subagent_id: 'subagent_id',
+ * },
+ * );
+ * ```
+ */
+ retrieve(turnID, params, options) {
+ const { session_id, subagent_id } = params;
+ return this._client.get(path`/agents/sessions/${session_id}/subagents/${subagent_id}/turns/${turnID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists all turns of this subagent, including turns after a resume. See
+ * [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const turn of client.beta.agents.sessions.subagents.turns.list(
+ * 'subagent_id',
+ * { session_id: 'session_id' },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(subagentID, params, options) {
+ const { session_id, ...query } = params;
+ return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagentID}/turns`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Turns2.Items = Items3;
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/subagents/subagents.mjs
+var Subagents;
+var init_subagents = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/subagents/subagents.mjs"() {
+ init_resource();
+ init_items2();
+ init_items2();
+ init_turns2();
+ init_turns2();
+ init_pagination();
+ init_headers();
+ init_path();
+ Subagents = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.items = new Items2(this._client);
+ this.turns = new Turns2(this._client);
+ }
+ /**
+ * Retrieves a subagent belonging to this session. See
+ * [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
+ *
+ * @example
+ * ```ts
+ * const subagent =
+ * await client.beta.agents.sessions.subagents.retrieve(
+ * 'subagent_id',
+ * { session_id: 'session_id' },
+ * );
+ * ```
+ */
+ retrieve(subagentID, params, options) {
+ const { session_id } = params;
+ return this._client.get(path`/agents/sessions/${session_id}/subagents/${subagentID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists subagents in a session, including nested and closed subagents. See
+ * [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const subagent of client.beta.agents.sessions.subagents.list(
+ * 'session_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(sessionID, query = {}, options) {
+ return this._client.getAPIList(path`/agents/sessions/${sessionID}/subagents`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Subagents.Items = Items2;
+ Subagents.Turns = Turns2;
+ }
+});
+
+// node_modules/openai/resources/beta/agents/sessions/sessions.mjs
+var Sessions2;
+var init_sessions2 = __esm({
+ "node_modules/openai/resources/beta/agents/sessions/sessions.mjs"() {
+ init_agent_session_stream();
+ init_resource();
+ init_artifacts();
+ init_artifacts();
+ init_events();
+ init_events();
+ init_items();
+ init_items();
+ init_turns();
+ init_turns();
+ init_subagents();
+ init_subagents();
+ init_pagination();
+ init_headers();
+ init_path();
+ Sessions2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.subagents = new Subagents(this._client);
+ this.artifacts = new Artifacts(this._client);
+ this.items = new Items(this._client);
+ this.events = new Events(this._client);
+ this.turns = new Turns(this._client);
+ }
+ /** Stream one turn on an idle session with a single input writer. See AgentSessionStream for lifecycle and tool handling. */
+ stream(sessionID, params, options) {
+ return new AgentSessionStream(this, sessionID, params, options);
+ }
+ create(body, options) {
+ return this._client.post("/agents/sessions", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves the current state of a managed agent session. See
+ * [managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage).
+ *
+ * @example
+ * ```ts
+ * const agentSession =
+ * await client.beta.agents.sessions.retrieve('session_id');
+ * ```
+ */
+ retrieve(sessionID, options) {
+ return this._client.get(path`/agents/sessions/${sessionID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Updates session metadata, model, reasoning effort, or service tier. Model
+ * settings apply to subsequent turns. Omitted fields are unchanged. See
+ * [managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage).
+ *
+ * @example
+ * ```ts
+ * const agentSession =
+ * await client.beta.agents.sessions.update('session_id');
+ * ```
+ */
+ update(sessionID, body = {}, options) {
+ return this._client.post(path`/agents/sessions/${sessionID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists managed agent sessions using ID-based pagination and the requested sort
+ * order. See
+ * [managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const agentSession of client.beta.agents.sessions.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/agents/sessions", CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Removes a managed agent session from the public API and returns a deletion
+ * confirmation. If backend execution has ended, deletion can cancel a still-open
+ * public turn and abandon unpublished outputs. Running execution must be cancelled
+ * first. Physical cleanup may continue asynchronously. See
+ * [managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage).
+ *
+ * @example
+ * ```ts
+ * const agentSessionDeleted =
+ * await client.beta.agents.sessions.delete('session_id');
+ * ```
+ */
+ delete(sessionID, options) {
+ return this._client.delete(path`/agents/sessions/${sessionID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Sessions2.Subagents = Subagents;
+ Sessions2.Artifacts = Artifacts;
+ Sessions2.Items = Items;
+ Sessions2.Events = Events;
+ Sessions2.Turns = Turns;
+ }
+});
+
+// node_modules/openai/resources/beta/agents/vaults/credentials.mjs
+var Credentials;
+var init_credentials = __esm({
+ "node_modules/openai/resources/beta/agents/vaults/credentials.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Credentials = class extends APIResource {
+ /**
+ * Creates a vault credential. Secret values are write-only and are never returned.
+ * See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * const credential =
+ * await client.beta.agents.vaults.credentials.create(
+ * 'vault_id',
+ * {
+ * auth: {
+ * access_token: 'access_token',
+ * mcp_server_url: 'mcp_server_url',
+ * type: 'mcp_oauth',
+ * },
+ * name: 'x',
+ * },
+ * );
+ * ```
+ */
+ create(vaultID, body, options) {
+ return this._client.post(path`/vaults/${vaultID}/credentials`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves vault credential metadata without returning secret values. See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * const credential =
+ * await client.beta.agents.vaults.credentials.retrieve(
+ * 'credential_id',
+ * { vault_id: 'vault_id' },
+ * );
+ * ```
+ */
+ retrieve(credentialID, params, options) {
+ const { vault_id } = params;
+ return this._client.get(path`/vaults/${vault_id}/credentials/${credentialID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Rotates a vault credential's write-only secret and returns only credential
+ * metadata. See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * const credential =
+ * await client.beta.agents.vaults.credentials.update(
+ * 'credential_id',
+ * {
+ * vault_id: 'vault_id',
+ * auth: { type: 'mcp_oauth' },
+ * },
+ * );
+ * ```
+ */
+ update(credentialID, params, options) {
+ const { vault_id, ...body } = params;
+ return this._client.post(path`/vaults/${vault_id}/credentials/${credentialID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists a vault's credentials using ID-based pagination without returning secret
+ * values. See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const credential of client.beta.agents.vaults.credentials.list(
+ * 'vault_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(vaultID, query = {}, options) {
+ return this._client.getAPIList(path`/vaults/${vaultID}/credentials`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes a vault credential. See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * const credentialDeleted =
+ * await client.beta.agents.vaults.credentials.delete(
+ * 'credential_id',
+ * { vault_id: 'vault_id' },
+ * );
+ * ```
+ */
+ delete(credentialID, params, options) {
+ const { vault_id } = params;
+ return this._client.delete(path`/vaults/${vault_id}/credentials/${credentialID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/agents/vaults/vaults.mjs
+var Vaults;
+var init_vaults = __esm({
+ "node_modules/openai/resources/beta/agents/vaults/vaults.mjs"() {
+ init_resource();
+ init_credentials();
+ init_credentials();
+ init_pagination();
+ init_headers();
+ init_path();
+ Vaults = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.credentials = new Credentials(this._client);
+ }
+ /**
+ * Creates a vault for the current project. See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * const vault = await client.beta.agents.vaults.create();
+ * ```
+ */
+ create(body = {}, options) {
+ return this._client.post("/vaults", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a vault by its ID. See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * const vault = await client.beta.agents.vaults.retrieve(
+ * 'vault_id',
+ * );
+ * ```
+ */
+ retrieve(vaultID, options) {
+ return this._client.get(path`/vaults/${vaultID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists vaults using ID-based pagination. See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const vault of client.beta.agents.vaults.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/vaults", CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes a vault and all its credentials. See
+ * [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
+ *
+ * @example
+ * ```ts
+ * const vaultDeleted = await client.beta.agents.vaults.delete(
+ * 'vault_id',
+ * );
+ * ```
+ */
+ delete(vaultID, options) {
+ return this._client.delete(path`/vaults/${vaultID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Vaults.Credentials = Credentials;
+ }
+});
+
+// node_modules/openai/resources/beta/agents/agents.mjs
+var Agents;
+var init_agents = __esm({
+ "node_modules/openai/resources/beta/agents/agents.mjs"() {
+ init_resource();
+ init_environments();
+ init_environments();
+ init_sessions2();
+ init_sessions2();
+ init_vaults();
+ init_vaults();
+ init_pagination();
+ init_headers();
+ init_path();
+ Agents = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.environments = new Environments(this._client);
+ this.vaults = new Vaults(this._client);
+ this.sessions = new Sessions2(this._client);
+ }
+ /**
+ * Creates a reusable agent without storing credentials. See
+ * [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
+ *
+ * @example
+ * ```ts
+ * const agent = await client.beta.agents.create({
+ * model: 'model',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/agents", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a reusable agent by ID. See
+ * [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
+ *
+ * @example
+ * ```ts
+ * const agent = await client.beta.agents.retrieve('agent_id');
+ * ```
+ */
+ retrieve(agentID, options) {
+ return this._client.get(path`/agents/${agentID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Updates a reusable agent. See
+ * [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
+ *
+ * @example
+ * ```ts
+ * const agent = await client.beta.agents.update('agent_id');
+ * ```
+ */
+ update(agentID, body = {}, options) {
+ return this._client.post(path`/agents/${agentID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Lists reusable agents in the current project. See
+ * [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const agent of client.beta.agents.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/agents", CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes a reusable agent. See
+ * [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
+ *
+ * @example
+ * ```ts
+ * const agentDeleted = await client.beta.agents.delete(
+ * 'agent_id',
+ * );
+ * ```
+ */
+ delete(agentID, options) {
+ return this._client.delete(path`/agents/${agentID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Agents.Environments = Environments;
+ Agents.Vaults = Vaults;
+ Agents.Sessions = Sessions2;
+ }
+});
+
+// node_modules/openai/resources/beta/chatkit/sessions.mjs
+var Sessions3;
+var init_sessions3 = __esm({
+ "node_modules/openai/resources/beta/chatkit/sessions.mjs"() {
+ init_resource();
+ init_headers();
+ init_path();
+ Sessions3 = class extends APIResource {
+ /**
+ * Create a ChatKit session.
+ *
+ * @example
+ * ```ts
+ * const chatSession =
+ * await client.beta.chatkit.sessions.create({
+ * user: 'x',
+ * workflow: { id: 'id' },
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/chatkit/sessions", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancel an active ChatKit session and return its most recent metadata.
+ *
+ * Cancelling prevents new requests from using the issued client secret.
+ *
+ * @example
+ * ```ts
+ * const chatSession =
+ * await client.beta.chatkit.sessions.cancel('cksess_123');
+ * ```
+ */
+ cancel(sessionID, options) {
+ return this._client.post(path`/chatkit/sessions/${sessionID}/cancel`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/chatkit/threads.mjs
+var Threads;
+var init_threads = __esm({
+ "node_modules/openai/resources/beta/chatkit/threads.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Threads = class extends APIResource {
+ /**
+ * Retrieve a ChatKit thread by its identifier.
+ *
+ * @example
+ * ```ts
+ * const chatkitThread =
+ * await client.beta.chatkit.threads.retrieve('cthr_123');
+ * ```
+ */
+ retrieve(threadID, options) {
+ return this._client.get(path`/chatkit/threads/${threadID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List ChatKit threads with optional pagination and user filters.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const chatkitThread of client.beta.chatkit.threads.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/chatkit/threads", ConversationCursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a ChatKit thread along with its items and stored attachments.
+ *
+ * @example
+ * ```ts
+ * const thread = await client.beta.chatkit.threads.delete(
+ * 'cthr_123',
+ * );
+ * ```
+ */
+ delete(threadID, options) {
+ return this._client.delete(path`/chatkit/threads/${threadID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List items that belong to a ChatKit thread.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const thread of client.beta.chatkit.threads.listItems(
+ * 'cthr_123',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ listItems(threadID, query = {}, options) {
+ return this._client.getAPIList(path`/chatkit/threads/${threadID}/items`, ConversationCursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/chatkit/chatkit.mjs
+var ChatKit;
+var init_chatkit = __esm({
+ "node_modules/openai/resources/beta/chatkit/chatkit.mjs"() {
+ init_resource();
+ init_sessions3();
+ init_sessions3();
+ init_threads();
+ init_threads();
+ ChatKit = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.sessions = new Sessions3(this._client);
+ this.threads = new Threads(this._client);
+ }
+ };
+ ChatKit.Sessions = Sessions3;
+ ChatKit.Threads = Threads;
+ }
+});
+
+// node_modules/openai/resources/beta/responses/input-items.mjs
+var InputItems;
+var init_input_items = __esm({
+ "node_modules/openai/resources/beta/responses/input-items.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ InputItems = class extends APIResource {
+ /**
+ * Returns a list of input items for a given response.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const betaResponseItem of client.beta.responses.inputItems.list(
+ * 'response_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(responseID, params = {}, options) {
+ const { betas, ...query } = params ?? {};
+ return this._client.getAPIList(path`/responses/${responseID}/input_items?beta=true`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
+ options?.headers
+ ]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/responses/input-tokens.mjs
+var InputTokens;
+var init_input_tokens = __esm({
+ "node_modules/openai/resources/beta/responses/input-tokens.mjs"() {
+ init_resource();
+ init_headers();
+ InputTokens = class extends APIResource {
+ /**
+ * Returns input token counts of the request.
+ *
+ * Returns an object with `object` set to `response.input_tokens` and an
+ * `input_tokens` count.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.beta.responses.inputTokens.count();
+ * ```
+ */
+ count(params = {}, options) {
+ const { betas, ...body } = params ?? {};
+ return this._client.post("/responses/input_tokens?beta=true", {
+ body,
+ ...options,
+ headers: buildHeaders([
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
+ options?.headers
+ ]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/responses/responses.mjs
+var Responses;
+var init_responses = __esm({
+ "node_modules/openai/resources/beta/responses/responses.mjs"() {
+ init_resource();
+ init_input_items();
+ init_input_items();
+ init_input_tokens();
+ init_input_tokens();
+ init_headers();
+ init_path();
+ Responses = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.inputItems = new InputItems(this._client);
+ this.inputTokens = new InputTokens(this._client);
+ }
+ create(params, options) {
+ const { betas, ...body } = params;
+ return this._client.post("/responses?beta=true", {
+ body,
+ ...options,
+ headers: buildHeaders([
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
+ options?.headers
+ ]),
+ stream: params.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+ retrieve(responseID, params = {}, options) {
+ const { betas, ...query } = params ?? {};
+ return this._client.get(path`/responses/${responseID}?beta=true`, {
+ query,
+ ...options,
+ headers: buildHeaders([
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
+ options?.headers
+ ]),
+ stream: params?.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes a model response with the given ID.
+ *
+ * @example
+ * ```ts
+ * await client.beta.responses.delete(
+ * 'resp_677efb5139a88190b512bc3fef8e535d',
+ * );
+ * ```
+ */
+ delete(responseID, params = {}, options) {
+ const { betas } = params ?? {};
+ return this._client.delete(path`/responses/${responseID}?beta=true`, {
+ ...options,
+ headers: buildHeaders([
+ { Accept: "*/*", ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
+ options?.headers
+ ]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancels a model response with the given ID. Only responses created with the
+ * `background` parameter set to `true` can be cancelled.
+ * [Learn more](https://developers.openai.com/api/docs/guides/background).
+ *
+ * @example
+ * ```ts
+ * const betaResponse = await client.beta.responses.cancel(
+ * 'resp_677efb5139a88190b512bc3fef8e535d',
+ * );
+ * ```
+ */
+ cancel(responseID, params = {}, options) {
+ const { betas } = params ?? {};
+ return this._client.post(path`/responses/${responseID}/cancel?beta=true`, {
+ ...options,
+ headers: buildHeaders([
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
+ options?.headers
+ ]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Compact a conversation. Returns a compacted response object.
+ *
+ * Learn when and how to compact long-running conversations in the
+ * [conversation state guide](https://developers.openai.com/api/docs/guides/conversation-state#managing-the-context-window).
+ * For ZDR-compatible compaction details, see
+ * [Compaction (advanced)](https://developers.openai.com/api/docs/guides/conversation-state#compaction-advanced).
+ *
+ * @example
+ * ```ts
+ * const betaCompactedResponse =
+ * await client.beta.responses.compact({
+ * model: 'gpt-6-astra',
+ * });
+ * ```
+ */
+ compact(params, options) {
+ const { betas, ...body } = params;
+ return this._client.post("/responses/compact?beta=true", {
+ body,
+ ...options,
+ headers: buildHeaders([
+ { ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
+ options?.headers
+ ]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Responses.InputItems = InputItems;
+ Responses.InputTokens = InputTokens;
+ }
+});
+
+// node_modules/openai/resources/beta/threads/messages.mjs
+var Messages2;
+var init_messages2 = __esm({
+ "node_modules/openai/resources/beta/threads/messages.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Messages2 = class extends APIResource {
+ /**
+ * Create a message.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ create(threadID, body, options) {
+ return this._client.post(path`/threads/${threadID}/messages`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieve a message.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ retrieve(messageID, params, options) {
+ const { thread_id } = params;
+ return this._client.get(path`/threads/${thread_id}/messages/${messageID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies a message.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ update(messageID, params, options) {
+ const { thread_id, ...body } = params;
+ return this._client.post(path`/threads/${thread_id}/messages/${messageID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of messages for a given thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ list(threadID, query = {}, options) {
+ return this._client.getAPIList(path`/threads/${threadID}/messages`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes a message.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ delete(messageID, params, options) {
+ const { thread_id } = params;
+ return this._client.delete(path`/threads/${thread_id}/messages/${messageID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/beta/threads/runs/steps.mjs
+var Steps;
+var init_steps = __esm({
+ "node_modules/openai/resources/beta/threads/runs/steps.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_path();
+ Steps = class extends APIResource {
+ /**
+ * Retrieves a run step.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ retrieve(stepID, params, options) {
+ const { thread_id, run_id, ...query } = params;
+ return this._client.get(path`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of run steps belonging to a run.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ list(runID, params, options) {
+ const { thread_id, ...query } = params;
+ return this._client.getAPIList(path`/threads/${thread_id}/runs/${runID}/steps`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/utils/base64.mjs
+var fromBase64, toFloat32Array;
+var init_base64 = __esm({
+ "node_modules/openai/internal/utils/base64.mjs"() {
+ init_error();
+ init_bytes();
+ fromBase64 = (str) => {
+ if (typeof globalThis.Buffer !== "undefined") {
+ const buf = globalThis.Buffer.from(str, "base64");
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
+ }
+ if (typeof atob !== "undefined") {
+ const bstr = atob(str);
+ const buf = new Uint8Array(bstr.length);
+ for (let i = 0; i < bstr.length; i++) {
+ buf[i] = bstr.charCodeAt(i);
+ }
+ return buf;
+ }
+ throw new OpenAIError("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined");
+ };
+ toFloat32Array = (base64Str) => {
+ if (typeof Buffer !== "undefined") {
+ const buf = Buffer.from(base64Str, "base64");
+ if (buf.length % Float32Array.BYTES_PER_ELEMENT !== 0) {
+ throw new RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");
+ }
+ return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT));
+ } else {
+ const binaryStr = atob(base64Str);
+ const len = binaryStr.length;
+ const bytes = new Uint8Array(len);
+ for (let i = 0; i < len; i++) {
+ bytes[i] = binaryStr.charCodeAt(i);
+ }
+ return Array.from(new Float32Array(bytes.buffer));
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/utils/env.mjs
+var readEnv;
+var init_env = __esm({
+ "node_modules/openai/internal/utils/env.mjs"() {
+ readEnv = (env) => {
+ try {
+ if (typeof globalThis.process !== "undefined") {
+ return globalThis.process.env?.[env]?.trim() || void 0;
+ }
+ if (typeof globalThis.Deno !== "undefined") {
+ return globalThis.Deno.env?.get?.(env)?.trim() || void 0;
+ }
+ } catch {
+ return void 0;
+ }
+ return void 0;
+ };
+ }
+});
+
+// node_modules/openai/internal/utils.mjs
+var init_utils2 = __esm({
+ "node_modules/openai/internal/utils.mjs"() {
+ init_values();
+ init_base64();
+ init_env();
+ init_log();
+ init_uuid();
+ init_sleep();
+ init_query();
+ }
+});
+
+// node_modules/openai/internal/assistant-stream-delta.mjs
+function getAssistantStreamDiagnosticProperty(property) {
+ switch (property) {
+ case "value":
+ case "arguments":
+ case "input":
+ case "text":
+ case "content":
+ case "annotations":
+ case "metadata":
+ case "name":
+ case "role":
+ case "status":
+ case "tool_calls":
+ case "step_details": {
+ return property;
+ }
+ default: {
+ return "unknown";
+ }
+ }
+}
+function createAssistantStreamDeltaProjection(cacheArrays) {
+ return { arrays: /* @__PURE__ */ new Map(), cacheArrays, records: /* @__PURE__ */ new WeakMap() };
+}
+function commitAssistantStreamArrayProjection(projection) {
+ for (const [array, projected] of projection.arrays) {
+ if (projected.cacheable && !externallyMutableAssistantStreamValues.has(array)) {
+ assistantStreamArrayStates.set(array, {
+ length: projected.length,
+ ownEntryCount: projected.ownEntryCount
+ });
+ } else {
+ assistantStreamArrayStates.delete(array);
+ }
+ }
+}
+function isPrimitiveAssistantStreamValue(value) {
+ return typeof value === "string" || typeof value === "number";
+}
+function isPrimitiveAssistantStreamArrayDelta(accumulator, delta) {
+ return delta.every(isPrimitiveAssistantStreamValue) && accumulator.every(isPrimitiveAssistantStreamValue);
+}
+function countOwnAssistantStreamArrayEntries(accumulator) {
+ let count = 0;
+ for (const key of Object.keys(accumulator)) {
+ const index3 = Number(key);
+ if (Number.isSafeInteger(index3) && index3 >= 0 && index3 < accumulator.length && String(index3) === key) {
+ count += 1;
+ }
+ }
+ return count;
+}
+function getAssistantStreamArrayOwnEntryCount(accumulator, enforceSparseHoleBudget, cachedState) {
+ if (!enforceSparseHoleBudget) {
+ return 0;
+ }
+ if (cachedState?.length === accumulator.length) {
+ return cachedState.ownEntryCount;
+ }
+ return countOwnAssistantStreamArrayEntries(accumulator);
+}
+function getAssistantStreamDeltaIndex(deltaEntry, kind, baselineLength) {
+ const { index: index3 } = deltaEntry;
+ if (kind === "array" && (index3 === null || index3 === void 0)) {
+ throw new Error("Expected array delta entry to have an `index` property");
+ }
+ if (kind === "array" && typeof index3 !== "number") {
+ throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");
+ }
+ if (!Number.isSafeInteger(index3) || index3 < 0 || index3 >= baselineLength + MAX_ASSISTANT_STREAM_ARRAY_GROWTH || index3 >= MAX_EXTERNALLY_MUTABLE_ASSISTANT_STREAM_ARRAY_LENGTH) {
+ const safeIndex = typeof index3 === "number" ? index3 : "unknown";
+ throw new OpenAIError(`Assistant stream delta contains an invalid ${kind} index: ${safeIndex}`);
+ }
+ return index3;
+}
+function assertValidAssistantStreamArrayDelta(accumulator, delta, kind, projection, validateRecord) {
+ let projectedArray = projection.arrays.get(accumulator);
+ if (!projectedArray) {
+ const enforceSparseHoleBudget = projection.cacheArrays && !externallyMutableAssistantStreamValues.has(accumulator);
+ const cachedState = enforceSparseHoleBudget ? assistantStreamArrayStates.get(accumulator) : void 0;
+ projectedArray = {
+ baselineLength: accumulator.length,
+ cacheable: enforceSparseHoleBudget,
+ enforceSparseHoleBudget,
+ entries: /* @__PURE__ */ new Map(),
+ length: accumulator.length,
+ ownEntryCount: getAssistantStreamArrayOwnEntryCount(accumulator, enforceSparseHoleBudget, cachedState)
+ };
+ projection.arrays.set(accumulator, projectedArray);
+ }
+ for (const deltaEntry of delta) {
+ if (!isObj(deltaEntry)) {
+ throw new Error("Expected array delta entry to be an object but got an invalid value");
+ }
+ const validatedIndex = getAssistantStreamDeltaIndex(deltaEntry, kind, projectedArray.baselineLength);
+ let accumulatedEntry;
+ if (projectedArray.entries.has(validatedIndex)) {
+ accumulatedEntry = projectedArray.entries.get(validatedIndex);
+ } else if (hasOwn(accumulator, validatedIndex)) {
+ accumulatedEntry = accumulator[validatedIndex];
+ if (accumulatedEntry === null || accumulatedEntry === void 0) {
+ projectedArray.entries.set(validatedIndex, deltaEntry);
+ }
+ } else {
+ projectedArray.entries.set(validatedIndex, deltaEntry);
+ projectedArray.ownEntryCount += 1;
+ }
+ const projectedLength = Math.max(projectedArray.length, validatedIndex + 1);
+ if (projectedArray.enforceSparseHoleBudget && projectedLength - projectedArray.ownEntryCount > MAX_ASSISTANT_STREAM_ARRAY_GROWTH) {
+ throw new OpenAIError(`Assistant stream delta contains an invalid ${kind} index: ${validatedIndex}`);
+ }
+ if (isObj(accumulatedEntry)) {
+ validateRecord(accumulatedEntry, deltaEntry, projection);
+ }
+ projectedArray.length = projectedLength;
+ }
+}
+function assertValidAssistantStreamDeltaIndices(accumulator, delta, projection) {
+ let projectedValues = projection.records.get(accumulator);
+ for (const [key, deltaValue] of Object.entries(delta)) {
+ if (key === "index" || key === "type") {
+ continue;
+ }
+ let accumulatedValue;
+ if (projectedValues?.has(key)) {
+ accumulatedValue = projectedValues.get(key);
+ } else if (hasOwn(accumulator, key)) {
+ accumulatedValue = accumulator[key];
+ }
+ if (accumulatedValue === null || accumulatedValue === void 0) {
+ if (!projectedValues) {
+ projectedValues = /* @__PURE__ */ new Map();
+ projection.records.set(accumulator, projectedValues);
+ }
+ projectedValues.set(key, deltaValue);
+ continue;
+ }
+ if (isObj(accumulatedValue) && isObj(deltaValue)) {
+ assertValidAssistantStreamDeltaIndices(accumulatedValue, deltaValue, projection);
+ } else if (Array.isArray(accumulatedValue) && Array.isArray(deltaValue) && !isPrimitiveAssistantStreamArrayDelta(accumulatedValue, deltaValue)) {
+ assertValidAssistantStreamArrayDelta(accumulatedValue, deltaValue, "array", projection, assertValidAssistantStreamDeltaIndices);
+ }
+ }
+}
+function isAssistantStreamValueExternallyMutable(value) {
+ return (isObj(value) || Array.isArray(value)) && externallyMutableAssistantStreamValues.has(value);
+}
+function markAssistantStreamValueExternallyMutable(value) {
+ if (!isObj(value) && !Array.isArray(value) || externallyMutableAssistantStreamValues.has(value)) {
+ return;
+ }
+ externallyMutableAssistantStreamValues.add(value);
+ if (Array.isArray(value)) {
+ assistantStreamArrayStates.delete(value);
+ }
+ for (const key of Reflect.ownKeys(value)) {
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
+ if (descriptor && "value" in descriptor) {
+ markAssistantStreamValueExternallyMutable(descriptor.value);
+ }
+ }
+}
+function defineAssistantStreamArrayEntry(accumulator, index3, value) {
+ if (externallyMutableAssistantStreamValues.has(accumulator)) {
+ markAssistantStreamValueExternallyMutable(value);
+ }
+ Object.defineProperty(accumulator, index3, {
+ configurable: true,
+ enumerable: true,
+ value,
+ writable: true
+ });
+}
+function getRequiredAssistantStreamArrayIndex(deltaEntry) {
+ const { index: index3 } = deltaEntry;
+ if (index3 === null || index3 === void 0) {
+ throw new Error("Expected array delta entry to have an `index` property");
+ }
+ if (typeof index3 !== "number") {
+ throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");
+ }
+ return index3;
+}
+function applyAssistantStreamArrayDelta(accumulator, delta, applyRecord) {
+ if (isPrimitiveAssistantStreamArrayDelta(accumulator, delta)) {
+ accumulator.push(...delta);
+ assistantStreamArrayStates.delete(accumulator);
+ return;
+ }
+ for (const deltaEntry of delta) {
+ if (!isObj(deltaEntry)) {
+ throw new Error("Expected array delta entry to be an object but got an invalid value");
+ }
+ const index3 = getRequiredAssistantStreamArrayIndex(deltaEntry);
+ if (hasOwn(accumulator, index3)) {
+ const accumulatedEntry = accumulator[index3];
+ if (accumulatedEntry === null || accumulatedEntry === void 0) {
+ if (externallyMutableAssistantStreamValues.has(accumulator)) {
+ markAssistantStreamValueExternallyMutable(deltaEntry);
+ }
+ accumulator[index3] = deltaEntry;
+ } else {
+ accumulator[index3] = applyRecord(accumulatedEntry, deltaEntry);
+ }
+ } else {
+ defineAssistantStreamArrayEntry(accumulator, index3, deltaEntry);
+ }
+ }
+}
+function applyAssistantStreamDelta(accumulator, delta) {
+ const externallyMutable = externallyMutableAssistantStreamValues.has(accumulator);
+ for (const [key, deltaValue] of Object.entries(delta)) {
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
+ throw new OpenAIError(`Assistant stream delta contains an unsafe property: ${key}`);
+ }
+ if (!hasOwn(accumulator, key)) {
+ if (externallyMutable) {
+ markAssistantStreamValueExternallyMutable(deltaValue);
+ }
+ accumulator[key] = deltaValue;
+ continue;
+ }
+ let accumulatedValue = accumulator[key];
+ if (accumulatedValue === null || accumulatedValue === void 0) {
+ if (externallyMutable) {
+ markAssistantStreamValueExternallyMutable(deltaValue);
+ }
+ accumulator[key] = deltaValue;
+ continue;
+ }
+ if (key === "index" || key === "type") {
+ accumulator[key] = deltaValue;
+ continue;
+ }
+ if (typeof accumulatedValue === "string" && typeof deltaValue === "string") {
+ accumulatedValue += deltaValue;
+ } else if (typeof accumulatedValue === "number" && typeof deltaValue === "number") {
+ accumulatedValue += deltaValue;
+ } else if (isObj(accumulatedValue) && isObj(deltaValue)) {
+ accumulatedValue = applyAssistantStreamDelta(accumulatedValue, deltaValue);
+ } else if (Array.isArray(accumulatedValue) && Array.isArray(deltaValue)) {
+ applyAssistantStreamArrayDelta(accumulatedValue, deltaValue, applyAssistantStreamDelta);
+ continue;
+ } else {
+ throw new TypeError(`Unhandled record type: ${getAssistantStreamDiagnosticProperty(key)}`);
+ }
+ accumulator[key] = accumulatedValue;
+ }
+ return accumulator;
+}
+function assertSafeAssistantStreamDelta(value) {
+ if (!isObj(value) && !Array.isArray(value)) {
+ return;
+ }
+ for (const [key, nestedValue] of Object.entries(value)) {
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
+ throw new OpenAIError(`Assistant stream delta contains an unsafe property: ${key}`);
+ }
+ assertSafeAssistantStreamDelta(nestedValue);
+ }
+}
+function accumulateAssistantStreamDelta(accumulator, delta, cacheArrays = false) {
+ assertSafeAssistantStreamDelta(delta);
+ const accumulatorRecord = accumulator;
+ const deltaRecord = delta;
+ const projection = createAssistantStreamDeltaProjection(cacheArrays && !isAssistantStreamValueExternallyMutable(accumulator));
+ assertValidAssistantStreamDeltaIndices(accumulatorRecord, deltaRecord, projection);
+ applyAssistantStreamDelta(accumulatorRecord, deltaRecord);
+ commitAssistantStreamArrayProjection(projection);
+ return accumulator;
+}
+function createAssistantStreamArrayDeltaCommit(accumulator, delta, kind, cacheArrays = true) {
+ assertSafeAssistantStreamDelta(delta);
+ const projection = createAssistantStreamDeltaProjection(cacheArrays && !isAssistantStreamValueExternallyMutable(accumulator));
+ assertValidAssistantStreamArrayDelta(accumulator, delta, kind, projection, assertValidAssistantStreamDeltaIndices);
+ return () => commitAssistantStreamArrayProjection(projection);
+}
+var MAX_ASSISTANT_STREAM_ARRAY_GROWTH, MAX_EXTERNALLY_MUTABLE_ASSISTANT_STREAM_ARRAY_LENGTH, assistantStreamArrayStates, externallyMutableAssistantStreamValues;
+var init_assistant_stream_delta = __esm({
+ "node_modules/openai/internal/assistant-stream-delta.mjs"() {
+ init_error2();
+ init_utils2();
+ MAX_ASSISTANT_STREAM_ARRAY_GROWTH = 1024;
+ MAX_EXTERNALLY_MUTABLE_ASSISTANT_STREAM_ARRAY_LENGTH = 65536;
+ assistantStreamArrayStates = /* @__PURE__ */ new WeakMap();
+ externallyMutableAssistantStreamValues = /* @__PURE__ */ new WeakSet();
+ }
+});
+
+// node_modules/openai/lib/AssistantStream.mjs
+function stabilizeAssistantStreamEvent(event) {
+ const eventDescriptor = Object.getOwnPropertyDescriptor(event, "event");
+ const dataDescriptor = Object.getOwnPropertyDescriptor(event, "data");
+ const eventType = Reflect.get(event, "event", event);
+ const data = Reflect.get(event, "data", event);
+ let stableData = data;
+ if (eventType === "thread.message.created" || eventType === "thread.message.in_progress" || eventType === "thread.message.delta" || eventType === "thread.message.completed" || eventType === "thread.message.incomplete" || eventType === "thread.run.step.created" || eventType === "thread.run.step.in_progress" || eventType === "thread.run.step.delta" || eventType === "thread.run.step.completed" || eventType === "thread.run.step.failed" || eventType === "thread.run.step.cancelled" || eventType === "thread.run.step.expired") {
+ const messageID = Object.getOwnPropertyDescriptor(data, "id");
+ if (messageID && "value" in messageID && // SAFETY: The own id descriptor was found above; keep its live read unknown while comparing it with the captured descriptor value.
+ data.id !== messageID.value) {
+ const canonicalID = messageID.value;
+ stableData = new Proxy(data, {
+ get(target, property) {
+ return property === "id" ? canonicalID : Reflect.get(target, property, target);
+ }
+ });
+ }
+ }
+ const stableEvent = Object.freeze({ event: eventType, data: stableData });
+ const ordinaryEvent = eventDescriptor !== void 0 && "value" in eventDescriptor && eventDescriptor.value === eventType && dataDescriptor !== void 0 && "value" in dataDescriptor && dataDescriptor.value === data && stableData === data;
+ return {
+ event: stableEvent,
+ exposedEvent: ordinaryEvent ? event : { event: eventType, data: stableData }
+ };
+}
+function assertNever2(_x) {
+ return _x;
+}
+var _AssistantStream_instances, _AssistantStream_runStepSnapshots, _AssistantStream_runStepIDOwners, _AssistantStream_activeRunStepID, _AssistantStream_messageSnapshots, _AssistantStream_messageIDOwners, _AssistantStream_messageSnapshot, _AssistantStream_activeMessageID, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_validateRunStepEvent, _AssistantStream_reserveRunStepAlias, _AssistantStream_validateMessageEvent, _AssistantStream_reserveMessageAlias, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_emitExposed, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun, AssistantStream;
+var init_AssistantStream = __esm({
+ "node_modules/openai/lib/AssistantStream.mjs"() {
+ init_tslib();
+ init_streaming2();
+ init_error2();
+ init_EventStream();
+ init_utils2();
+ init_assistant_stream_delta();
+ AssistantStream = class _AssistantStream extends EventStream2 {
+ constructor() {
+ super(...arguments);
+ _AssistantStream_instances.add(this);
+ _AssistantStream_runStepSnapshots.set(this, /* @__PURE__ */ Object.create(null));
+ _AssistantStream_runStepIDOwners.set(this, /* @__PURE__ */ new Map());
+ _AssistantStream_activeRunStepID.set(this, void 0);
+ _AssistantStream_messageSnapshots.set(this, /* @__PURE__ */ Object.create(null));
+ _AssistantStream_messageIDOwners.set(this, /* @__PURE__ */ new Map());
+ _AssistantStream_messageSnapshot.set(this, void 0);
+ _AssistantStream_activeMessageID.set(this, void 0);
+ _AssistantStream_finalRun.set(this, void 0);
+ _AssistantStream_currentContentIndex.set(this, void 0);
+ _AssistantStream_currentContent.set(this, void 0);
+ _AssistantStream_currentToolCallIndex.set(this, void 0);
+ _AssistantStream_currentToolCall.set(this, void 0);
+ _AssistantStream_currentEvent.set(this, void 0);
+ _AssistantStream_currentRunSnapshot.set(this, void 0);
+ _AssistantStream_currentRunStepSnapshot.set(this, void 0);
+ }
+ /** Iterates over cloned raw assistant events; stopping early aborts the underlying request. */
+ [(_AssistantStream_runStepSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_runStepIDOwners = /* @__PURE__ */ new WeakMap(), _AssistantStream_activeRunStepID = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageIDOwners = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_activeMessageID = /* @__PURE__ */ new WeakMap(), _AssistantStream_finalRun = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContentIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCallIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCall = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentEvent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunStepSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
+ return this._createIterator((push) => {
+ const onEvent = (event) => push(structuredClone(event));
+ this.on("event", onEvent);
+ return () => this.off("event", onEvent);
+ }, { onReturn: () => this.abort() });
+ }
+ /** Restores an assistant stream from events serialized by `toReadableStream()`. */
+ static fromReadableStream(stream3) {
+ const runner = new _AssistantStream();
+ runner._run(() => runner._fromReadableStream(stream3));
+ return runner;
+ }
+ async _fromReadableStream(readableStream, options) {
+ this._listenForAbort(options?.signal);
+ this._connected();
+ const stream3 = Stream.fromReadableStream(readableStream, this.controller);
+ for await (const event of stream3) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
+ }
+ if (stream3.controller.signal?.aborted) {
+ throw this._userAbortError();
+ }
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
+ }
+ /** Serializes assistant events into a readable stream for transfer to another runtime. */
+ toReadableStream() {
+ const stream3 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
+ return stream3.toReadableStream();
+ }
+ /** Submits tool outputs and starts streaming the continuation of an existing assistant run. */
+ static createToolAssistantStream(runId, runs, params, options) {
+ const runner = new _AssistantStream();
+ runner._run(() => runner._runToolAssistantStream(runId, runs, params, {
+ ...options,
+ __metadata: { ...options?.__metadata, helperMethod: "stream" }
+ }));
+ return runner;
+ }
+ async _createToolAssistantStream(run2, runId, params, options) {
+ this._listenForAbort(options?.signal);
+ const body = { ...params, stream: true };
+ const stream3 = await run2.submitToolOutputs(runId, body, {
+ ...options,
+ signal: this.controller.signal
+ });
+ this._connected();
+ for await (const event of stream3) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
+ }
+ if (stream3.controller.signal?.aborted) {
+ throw this._userAbortError();
+ }
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
+ }
+ /** Creates an assistant thread and starts streaming its newly created run. */
+ static createThreadAssistantStream(params, thread, options) {
+ const runner = new _AssistantStream();
+ runner._run(() => runner._threadAssistantStream(params, thread, {
+ ...options,
+ __metadata: { ...options?.__metadata, helperMethod: "stream" }
+ }));
+ return runner;
+ }
+ /** Creates a run on an existing assistant thread and starts streaming its events. */
+ static createAssistantStream(threadId, runs, params, options) {
+ const runner = new _AssistantStream();
+ runner._run(() => runner._runAssistantStream(threadId, runs, params, {
+ ...options,
+ __metadata: { ...options?.__metadata, helperMethod: "stream" }
+ }));
+ return runner;
+ }
+ /** Returns the most recent raw event, or `undefined` before any event arrives. */
+ currentEvent() {
+ markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"));
+ return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f");
+ }
+ /** Returns the latest run snapshot, or `undefined` before a run event arrives. */
+ currentRun() {
+ markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"));
+ return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f");
+ }
+ /** Returns the message currently being accumulated, or `undefined` before message creation. */
+ currentMessageSnapshot() {
+ markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f");
+ }
+ /** Returns the run step currently being accumulated, or `undefined` before a step begins. */
+ currentRunStepSnapshot() {
+ markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"));
+ return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f");
+ }
+ /** Waits for successful completion and returns the final snapshot of every observed run step. */
+ async finalRunSteps() {
+ await this.done();
+ return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"));
+ }
+ /**
+ * Waits for successful completion and returns the final snapshot of every observed message.
+ * Terminal message events replace accumulated snapshots without mutating earlier snapshots.
+ */
+ async finalMessages() {
+ await this.done();
+ return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f"));
+ }
+ /** Waits for completion and returns the final run, or rejects if no terminal run was received. */
+ async finalRun() {
+ await this.done();
+ if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) {
+ throw new Error("Final run was not received.");
+ }
+ return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
+ }
+ async _createThreadAssistantStream(thread, params, options) {
+ this._listenForAbort(options?.signal);
+ const body = { ...params, stream: true };
+ const stream3 = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
+ this._connected();
+ for await (const event of stream3) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
+ }
+ if (stream3.controller.signal?.aborted) {
+ throw this._userAbortError();
+ }
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
+ }
+ async _createAssistantStream(run2, threadId, params, options) {
+ this._listenForAbort(options?.signal);
+ const body = { ...params, stream: true };
+ const stream3 = await run2.create(threadId, body, { ...options, signal: this.controller.signal });
+ this._connected();
+ for await (const event of stream3) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
+ }
+ if (stream3.controller.signal?.aborted) {
+ throw this._userAbortError();
+ }
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
+ }
+ /**
+ * Applies an assistant delta to its mutable snapshot, concatenating text and
+ * merging nested objects and indexed array entries.
+ */
+ static accumulateDelta(acc, delta) {
+ return accumulateAssistantStreamDelta(acc, delta);
+ }
+ _addRun(run2) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "run", run2);
+ return run2;
+ }
+ async _threadAssistantStream(params, thread, options) {
+ return await this._createThreadAssistantStream(thread, params, options);
+ }
+ async _runAssistantStream(threadId, runs, params, options) {
+ return await this._createAssistantStream(runs, threadId, params, options);
+ }
+ async _runToolAssistantStream(runId, runs, params, options) {
+ return await this._createToolAssistantStream(runs, runId, params, options);
+ }
+ };
+ _AssistantStream_addEvent = function _AssistantStream_addEvent2(event) {
+ if (this.ended) {
+ return;
+ }
+ const { event: stableEvent, exposedEvent } = stabilizeAssistantStreamEvent(event);
+ let messageID;
+ let messageData;
+ let runStepID;
+ let runStepData;
+ switch (stableEvent.event) {
+ case "thread.message.created":
+ case "thread.message.in_progress":
+ case "thread.message.delta":
+ case "thread.message.completed":
+ case "thread.message.incomplete": {
+ messageID = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_validateMessageEvent).call(this, stableEvent);
+ messageData = stableEvent.data;
+ break;
+ }
+ case "thread.run.step.created":
+ case "thread.run.step.in_progress":
+ case "thread.run.step.delta":
+ case "thread.run.step.completed":
+ case "thread.run.step.failed":
+ case "thread.run.step.cancelled":
+ case "thread.run.step.expired": {
+ runStepID = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_validateRunStepEvent).call(this, stableEvent);
+ runStepData = stableEvent.data;
+ break;
+ }
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentEvent, exposedEvent, "f");
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, exposedEvent);
+ if (messageID !== void 0 && messageData !== void 0) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveMessageAlias).call(this, messageData, messageID);
+ }
+ if (runStepID !== void 0 && runStepData !== void 0) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, runStepData, runStepID);
+ }
+ if (runStepID === void 0 && __classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f") !== void 0 && __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f")) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"), __classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f"));
+ }
+ switch (stableEvent.event) {
+ case "thread.created": {
+ break;
+ }
+ case "thread.run.created":
+ case "thread.run.queued":
+ case "thread.run.in_progress":
+ case "thread.run.requires_action":
+ case "thread.run.completed":
+ case "thread.run.incomplete":
+ case "thread.run.failed":
+ case "thread.run.cancelling":
+ case "thread.run.cancelled":
+ case "thread.run.expired": {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, stableEvent);
+ break;
+ }
+ case "thread.run.step.created":
+ case "thread.run.step.in_progress":
+ case "thread.run.step.delta":
+ case "thread.run.step.completed":
+ case "thread.run.step.failed":
+ case "thread.run.step.cancelled":
+ case "thread.run.step.expired": {
+ if (runStepID === void 0) {
+ throw new OpenAIError("Received assistant run-step event without a canonical run-step ID");
+ }
+ const activeRunStep = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
+ if (activeRunStep) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, activeRunStep, runStepID);
+ }
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, stableEvent, runStepID);
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, stableEvent.data, runStepID);
+ const retainedRunStep = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
+ if (retainedRunStep) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, retainedRunStep, runStepID);
+ }
+ break;
+ }
+ case "thread.message.created":
+ case "thread.message.in_progress":
+ case "thread.message.delta":
+ case "thread.message.completed":
+ case "thread.message.incomplete": {
+ if (messageID !== void 0 && __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveMessageAlias).call(this, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"), messageID);
+ }
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, stableEvent);
+ if (messageID !== void 0) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveMessageAlias).call(this, stableEvent.data, messageID);
+ const retainedMessage = __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[messageID];
+ if (retainedMessage) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveMessageAlias).call(this, retainedMessage, messageID);
+ }
+ }
+ break;
+ }
+ case "error": {
+ throw new APIError(void 0, stableEvent.data, void 0, void 0);
+ }
+ default: {
+ assertNever2(stableEvent);
+ }
+ }
+ }, _AssistantStream_endRequest = function _AssistantStream_endRequest2() {
+ if (this.ended) {
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
+ }
+ if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) {
+ throw new Error("Final run has not been received");
+ }
+ return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
+ }, _AssistantStream_validateRunStepEvent = function _AssistantStream_validateRunStepEvent2(event) {
+ const descriptor = Object.getOwnPropertyDescriptor(event.data, "id");
+ const runStepID = descriptor && "value" in descriptor ? descriptor.value : void 0;
+ if (typeof runStepID !== "string" || runStepID.length === 0) {
+ throw new OpenAIError("Received assistant run-step event with an invalid run-step ID");
+ }
+ if (event.event === "thread.run.step.delta") {
+ const delta = event.data.delta;
+ if (delta && hasOwn(delta, "id")) {
+ throw new OpenAIError("Run-step deltas must not contain an id field");
+ }
+ }
+ if (event.event === "thread.run.step.created") {
+ if (__classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f") !== void 0) {
+ throw new OpenAIError(`Received run-step creation for "${runStepID}" before the active run step "${__classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f")}" reached a terminal state`);
+ }
+ if (hasOwn(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"), runStepID) || __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").has(runStepID)) {
+ throw new OpenAIError(`Received run-step creation for run step "${runStepID}", which has already been created`);
+ }
+ __classPrivateFieldSet(this, _AssistantStream_activeRunStepID, runStepID, "f");
+ __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").set(runStepID, runStepID);
+ return runStepID;
+ }
+ if (__classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f") !== void 0) {
+ if (runStepID !== __classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f")) {
+ throw new OpenAIError(`Received ${event.event} for run step "${runStepID}", which does not match the active run step "${__classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f")}"`);
+ }
+ return runStepID;
+ }
+ if (event.event === "thread.run.step.delta") {
+ if (!hasOwn(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"), runStepID)) {
+ throw new OpenAIError("Received a RunStepDelta before creation of a snapshot");
+ }
+ throw new OpenAIError(`Received run-step delta for "${runStepID}" with no active run step`);
+ }
+ if (hasOwn(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"), runStepID) || __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").has(runStepID)) {
+ throw new OpenAIError(`Received run-step event for run step "${runStepID}", which has already been created`);
+ }
+ __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").set(runStepID, runStepID);
+ if (event.event === "thread.run.step.in_progress") {
+ __classPrivateFieldSet(this, _AssistantStream_activeRunStepID, runStepID, "f");
+ }
+ return runStepID;
+ }, _AssistantStream_reserveRunStepAlias = function _AssistantStream_reserveRunStepAlias2(data, canonicalID) {
+ const descriptor = Object.getOwnPropertyDescriptor(data, "id");
+ const runStepID = descriptor && "value" in descriptor ? descriptor.value : void 0;
+ if (typeof runStepID !== "string" || runStepID.length === 0) {
+ throw new OpenAIError("Received assistant run-step event with an invalid run-step ID");
+ }
+ const owner = __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").get(runStepID);
+ if (owner !== void 0 && owner !== canonicalID) {
+ throw new OpenAIError(`Received run-step creation for run step "${runStepID}", which has already been created`);
+ }
+ __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").set(runStepID, canonicalID);
+ }, _AssistantStream_validateMessageEvent = function _AssistantStream_validateMessageEvent2(event) {
+ const descriptor = Object.getOwnPropertyDescriptor(event.data, "id");
+ const messageID = descriptor && "value" in descriptor ? descriptor.value : void 0;
+ if (typeof messageID !== "string" || messageID.length === 0) {
+ throw new OpenAIError("Received assistant message event with an invalid message ID");
+ }
+ if (event.event === "thread.message.created") {
+ if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
+ throw new OpenAIError(`Received message creation for "${messageID}" before the active message "${__classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")}" reached a terminal state`);
+ }
+ if (hasOwn(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f"), messageID) || __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").has(messageID)) {
+ throw new OpenAIError(`Received message creation for message "${messageID}", which has already been created`);
+ }
+ __classPrivateFieldSet(this, _AssistantStream_activeMessageID, messageID, "f");
+ __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").set(messageID, messageID);
+ return messageID;
+ }
+ if (!__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
+ if (event.event === "thread.message.delta") {
+ throw new OpenAIError("Received a delta with no existing snapshot (there should be one from message creation)");
+ }
+ throw new OpenAIError("Received thread message event with no existing snapshot");
+ }
+ if (messageID !== __classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")) {
+ throw new OpenAIError(`Received ${event.event} for message "${messageID}", which does not match the active message "${__classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")}"`);
+ }
+ return messageID;
+ }, _AssistantStream_reserveMessageAlias = function _AssistantStream_reserveMessageAlias2(data, canonicalID) {
+ const descriptor = Object.getOwnPropertyDescriptor(data, "id");
+ const messageID = descriptor && "value" in descriptor ? descriptor.value : void 0;
+ if (typeof messageID !== "string" || messageID.length === 0) {
+ throw new OpenAIError("Received assistant message event with an invalid message ID");
+ }
+ const owner = __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").get(messageID);
+ if (owner !== void 0 && owner !== canonicalID) {
+ throw new OpenAIError(`Received message creation for message "${messageID}", which has already been created`);
+ }
+ __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").set(messageID, canonicalID);
+ }, _AssistantStream_handleMessage = function _AssistantStream_handleMessage2(event) {
+ const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
+ if (!__classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")) {
+ throw new OpenAIError("Received thread message event with no active message ID");
+ }
+ __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[__classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")] = accumulatedMessage;
+ for (const content of newContent) {
+ const snapshotContent = accumulatedMessage.content[content.index];
+ if (snapshotContent?.type === "text") {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "textCreated", snapshotContent.text);
+ }
+ }
+ switch (event.event) {
+ case "thread.message.created": {
+ __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, void 0, "f");
+ __classPrivateFieldSet(this, _AssistantStream_currentContent, void 0, "f");
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "messageCreated", event.data);
+ break;
+ }
+ case "thread.message.in_progress": {
+ break;
+ }
+ case "thread.message.delta": {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "messageDelta", event.data.delta, accumulatedMessage);
+ if (event.data.delta.content) {
+ for (const content of event.data.delta.content) {
+ if (content.type === "text" && content.text) {
+ const textDelta = content.text;
+ const snapshot = accumulatedMessage.content[content.index];
+ if (snapshot && snapshot.type === "text") {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "textDelta", textDelta, snapshot.text);
+ } else {
+ throw new Error("The snapshot associated with this text delta is not text or missing");
+ }
+ }
+ if (content.index !== __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) {
+ if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) {
+ switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) {
+ case "text": {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "textDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ break;
+ }
+ case "image_file": {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "imageFileDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ break;
+ }
+ }
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f");
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
+ }
+ }
+ break;
+ }
+ case "thread.message.completed":
+ case "thread.message.incomplete": {
+ if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== void 0) {
+ const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")];
+ if (currentContent) {
+ switch (currentContent.type) {
+ case "image_file": {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "imageFileDone", currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ break;
+ }
+ case "text": {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "textDone", currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ break;
+ }
+ }
+ }
+ }
+ if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "messageDone", event.data);
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, void 0, "f");
+ __classPrivateFieldSet(this, _AssistantStream_currentContent, void 0, "f");
+ __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, void 0, "f");
+ __classPrivateFieldSet(this, _AssistantStream_activeMessageID, void 0, "f");
+ }
+ }
+ }, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep2(event, runStepID) {
+ const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event, runStepID);
+ __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
+ switch (event.event) {
+ case "thread.run.step.created": {
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, void 0, "f");
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "runStepCreated", event.data);
+ break;
+ }
+ case "thread.run.step.delta": {
+ const delta = event.data.delta;
+ if (delta.step_details && delta.step_details.type === "tool_calls" && delta.step_details.tool_calls && accumulatedRunStep.step_details.type === "tool_calls") {
+ for (const toolCall of delta.step_details.tool_calls) {
+ if (toolCall.index === __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
+ } else {
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallCreated", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
+ }
+ }
+ }
+ }
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "runStepDelta", event.data.delta, accumulatedRunStep);
+ break;
+ }
+ case "thread.run.step.completed":
+ case "thread.run.step.failed":
+ case "thread.run.step.cancelled":
+ case "thread.run.step.expired": {
+ __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, void 0, "f");
+ __classPrivateFieldSet(this, _AssistantStream_activeRunStepID, void 0, "f");
+ const details = event.data.step_details;
+ if (details.type === "tool_calls" && __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
+ }
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "runStepDone", event.data, accumulatedRunStep);
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, void 0, "f");
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
+ break;
+ }
+ case "thread.run.step.in_progress": {
+ break;
+ }
+ }
+ }, _AssistantStream_emitExposed = function _AssistantStream_emitExposed2(event, ...args) {
+ if (this._hasListeners(event)) {
+ for (const value of args) {
+ markAssistantStreamValueExternallyMutable(value);
+ }
+ }
+ this._emit(event, ...args);
+ }, _AssistantStream_handleEvent = function _AssistantStream_handleEvent2(event) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "event", event);
+ }, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep2(event, runStepID) {
+ switch (event.event) {
+ case "thread.run.step.created": {
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID] = event.data;
+ return event.data;
+ }
+ case "thread.run.step.delta": {
+ const snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
+ if (!snapshot) {
+ throw new Error("Received a RunStepDelta before creation of a snapshot");
+ }
+ const delta = event.data.delta;
+ if (delta) {
+ if (hasOwn(delta, "id")) {
+ throw new OpenAIError("Run-step deltas must not contain an id field");
+ }
+ const accumulated = accumulateAssistantStreamDelta(snapshot, delta, true);
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID] = accumulated;
+ }
+ return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
+ }
+ case "thread.run.step.completed":
+ case "thread.run.step.failed":
+ case "thread.run.step.cancelled":
+ case "thread.run.step.expired":
+ case "thread.run.step.in_progress": {
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID] = event.data;
+ break;
+ }
+ }
+ if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID]) {
+ return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
+ }
+ throw new Error("No snapshot available");
+ }, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage2(event, snapshot) {
+ const newContent = [];
+ switch (event.event) {
+ case "thread.message.created": {
+ return [event.data, newContent];
+ }
+ case "thread.message.delta": {
+ if (!snapshot) {
+ throw new Error("Received a delta with no existing snapshot (there should be one from message creation)");
+ }
+ const data = event.data;
+ if (data.delta.content) {
+ assertSafeAssistantStreamDelta(data.delta);
+ const cacheArrays = !isAssistantStreamValueExternallyMutable(snapshot);
+ const commitProjection = createAssistantStreamArrayDeltaCommit(snapshot.content, data.delta.content, "content", cacheArrays);
+ for (const contentElement of data.delta.content) {
+ if (hasOwn(snapshot.content, contentElement.index)) {
+ const currentContent = snapshot.content[contentElement.index];
+ snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent, cacheArrays);
+ } else {
+ defineAssistantStreamArrayEntry(snapshot.content, contentElement.index, contentElement);
+ newContent.push(contentElement);
+ }
+ }
+ commitProjection();
+ }
+ return [snapshot, newContent];
+ }
+ case "thread.message.in_progress":
+ case "thread.message.completed":
+ case "thread.message.incomplete": {
+ if (snapshot) {
+ return [event.event === "thread.message.in_progress" ? snapshot : event.data, newContent];
+ }
+ throw new Error("Received thread message event with no existing snapshot");
+ }
+ }
+ throw new Error("Tried to accumulate a non-message event");
+ }, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent2(contentElement, currentContent, cacheArrays) {
+ return accumulateAssistantStreamDelta(currentContent, contentElement, cacheArrays);
+ }, _AssistantStream_handleRun = function _AssistantStream_handleRun2(event) {
+ __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f");
+ switch (event.event) {
+ case "thread.run.created": {
+ break;
+ }
+ case "thread.run.queued": {
+ break;
+ }
+ case "thread.run.in_progress": {
+ break;
+ }
+ case "thread.run.requires_action":
+ case "thread.run.cancelled":
+ case "thread.run.failed":
+ case "thread.run.completed":
+ case "thread.run.expired":
+ case "thread.run.incomplete": {
+ __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f");
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, void 0, "f");
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
+ break;
+ }
+ case "thread.run.cancelling": {
+ break;
+ }
+ }
+ };
+ }
+});
+
+// node_modules/openai/lib/polling.mjs
+function sleepUntilAborted(milliseconds, signal) {
+ return new Promise((resolve3, reject) => {
+ let timer;
+ let registered;
+ let settled = false;
+ const removeAbortListener = (listener) => {
+ try {
+ signal.removeEventListener("abort", listener);
+ } catch {
+ }
+ };
+ const cleanup = () => {
+ if (timer !== void 0) {
+ clearTimeout(timer);
+ timer = void 0;
+ }
+ if (registered) {
+ const listener = registered;
+ registered = void 0;
+ removeAbortListener(listener);
+ }
+ };
+ const abort = () => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ cleanup();
+ try {
+ const error = new APIUserAbortError();
+ Object.defineProperty(error, "cause", {
+ value: signal.reason,
+ writable: true,
+ configurable: true
+ });
+ reject(error);
+ } catch (error) {
+ reject(error);
+ }
+ };
+ if (signal.aborted) {
+ abort();
+ return;
+ }
+ timer = setTimeout(() => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ cleanup();
+ resolve3();
+ }, milliseconds);
+ registered = abort;
+ try {
+ signal.addEventListener("abort", abort, { once: true });
+ if (settled) {
+ removeAbortListener(abort);
+ } else if (signal.aborted) {
+ abort();
+ }
+ } catch (error) {
+ if (settled) {
+ removeAbortListener(abort);
+ } else {
+ settled = true;
+ cleanup();
+ reject(error);
+ }
+ }
+ });
+}
+async function pollWithResponse(retrieve, intermediateStatuses, terminalStatuses, options) {
+ const headers = buildHeaders([
+ options?.headers,
+ {
+ "X-Stainless-Poll-Helper": "true",
+ "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0
+ }
+ ]);
+ while (true) {
+ const { data, response } = await retrieve(headers).withResponse();
+ const { status } = data;
+ if (intermediateStatuses.includes(status)) {
+ let sleepInterval = 5e3;
+ const pollIntervalMs = options?.pollIntervalMs;
+ if (pollIntervalMs || pollIntervalMs === 0) {
+ sleepInterval = pollIntervalMs;
+ } else {
+ const headerInterval = response.headers.get("openai-poll-after-ms");
+ if (headerInterval) {
+ const headerIntervalMs = Number.parseInt(headerInterval);
+ if (!Number.isNaN(headerIntervalMs)) {
+ sleepInterval = headerIntervalMs;
+ }
+ }
+ }
+ const signal = options && Object.prototype.propertyIsEnumerable.call(options, "signal") ? options.signal : void 0;
+ await (signal ? sleepUntilAborted(sleepInterval, signal) : sleep(sleepInterval));
+ } else if (terminalStatuses.includes(status)) {
+ return data;
+ }
+ }
+}
+var init_polling = __esm({
+ "node_modules/openai/lib/polling.mjs"() {
+ init_error();
+ init_headers();
+ init_sleep();
+ }
+});
+
+// node_modules/openai/lib/assistant-run-polling.mjs
+function pollAssistantRun(resource, runID, params, options) {
+ return pollWithResponse((headers) => resource.retrieve(runID, params, {
+ ...options,
+ headers: { ...options?.headers, ...headers }
+ }), ["queued", "in_progress", "cancelling"], ["requires_action", "incomplete", "cancelled", "completed", "failed", "expired"], options);
+}
+var init_assistant_run_polling = __esm({
+ "node_modules/openai/lib/assistant-run-polling.mjs"() {
+ init_polling();
+ }
+});
+
+// node_modules/openai/resources/beta/threads/runs/runs.mjs
+var Runs;
+var init_runs = __esm({
+ "node_modules/openai/resources/beta/threads/runs/runs.mjs"() {
+ init_resource();
+ init_steps();
+ init_steps();
+ init_pagination();
+ init_headers();
+ init_AssistantStream();
+ init_assistant_run_polling();
+ init_path();
+ Runs = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.steps = new Steps(this._client);
+ }
+ create(threadID, params, options) {
+ const { include, ...body } = params;
+ return this._client.post(path`/threads/${threadID}/runs`, {
+ query: { include },
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ stream: params.stream ?? false,
+ __synthesizeEventData: true,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a run.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ retrieve(runID, params, options) {
+ const { thread_id } = params;
+ return this._client.get(path`/threads/${thread_id}/runs/${runID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies a run.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ update(runID, params, options) {
+ const { thread_id, ...body } = params;
+ return this._client.post(path`/threads/${thread_id}/runs/${runID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of runs belonging to a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ list(threadID, query = {}, options) {
+ return this._client.getAPIList(path`/threads/${threadID}/runs`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancels a run that is `in_progress`.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ cancel(runID, params, options) {
+ const { thread_id } = params;
+ return this._client.post(path`/threads/${thread_id}/runs/${runID}/cancel`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * A helper to create a run an poll for a terminal state. More information on Run
+ * lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ async createAndPoll(threadId, body, options) {
+ const run2 = await this.create(threadId, body, options);
+ return await this.poll(run2.id, { thread_id: threadId }, options);
+ }
+ /**
+ * Create a Run stream
+ *
+ * @deprecated use `stream` instead
+ */
+ createAndStream(threadId, body, options) {
+ return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);
+ }
+ /**
+ * A helper to poll a run status until it reaches a terminal state. More
+ * information on Run lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ async poll(runId, params, options) {
+ return await pollAssistantRun(this, runId, params, options);
+ }
+ /**
+ * Create a Run stream
+ */
+ stream(threadId, body, options) {
+ return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);
+ }
+ submitToolOutputs(runID, params, options) {
+ const { thread_id, ...body } = params;
+ return this._client.post(path`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ stream: params.stream ?? false,
+ __synthesizeEventData: true,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * A helper to submit a tool output to a run and poll for a terminal run state.
+ * More information on Run lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ async submitToolOutputsAndPoll(runId, params, options) {
+ const run2 = await this.submitToolOutputs(runId, params, options);
+ return await this.poll(run2.id, params, options);
+ }
+ /**
+ * Submit the tool outputs from a previous run and stream the run to a terminal
+ * state. More information on Run lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ submitToolOutputsStream(runId, params, options) {
+ return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options);
+ }
+ };
+ Runs.Steps = Steps;
+ }
+});
+
+// node_modules/openai/resources/beta/threads/threads.mjs
+var Threads2;
+var init_threads2 = __esm({
+ "node_modules/openai/resources/beta/threads/threads.mjs"() {
+ init_resource();
+ init_messages2();
+ init_messages2();
+ init_runs();
+ init_runs();
+ init_headers();
+ init_AssistantStream();
+ init_path();
+ Threads2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.runs = new Runs(this._client);
+ this.messages = new Messages2(this._client);
+ }
+ /**
+ * Create a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ create(body = {}, options) {
+ return this._client.post("/threads", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ retrieve(threadID, options) {
+ return this._client.get(path`/threads/${threadID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ update(threadID, body, options) {
+ return this._client.post(path`/threads/${threadID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ delete(threadID, options) {
+ return this._client.delete(path`/threads/${threadID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ createAndRun(body, options) {
+ return this._client.post("/threads/runs", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ stream: body.stream ?? false,
+ __synthesizeEventData: true,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * A helper to create a thread, start a run and then poll for a terminal state.
+ * More information on Run lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ async createAndRunPoll(body, options) {
+ const run2 = await this.createAndRun(body, options);
+ return await this.runs.poll(run2.id, { thread_id: run2.thread_id }, options);
+ }
+ /**
+ * Create a thread and stream the run back
+ */
+ createAndRunStream(body, options) {
+ return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options);
+ }
+ };
+ Threads2.Runs = Runs;
+ Threads2.Messages = Messages2;
+ }
+});
+
+// node_modules/openai/resources/beta/beta.mjs
+var Beta;
+var init_beta = __esm({
+ "node_modules/openai/resources/beta/beta.mjs"() {
+ init_resource();
+ init_assistants();
+ init_assistants();
+ init_realtime();
+ init_realtime();
+ init_agents();
+ init_agents();
+ init_chatkit();
+ init_chatkit();
+ init_responses();
+ init_responses();
+ init_threads2();
+ init_threads2();
+ Beta = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.realtime = new Realtime(this._client);
+ this.agents = new Agents(this._client);
+ this.responses = new Responses(this._client);
+ this.chatkit = new ChatKit(this._client);
+ this.assistants = new Assistants(this._client);
+ this.threads = new Threads2(this._client);
+ }
+ };
+ Beta.Realtime = Realtime;
+ Beta.Agents = Agents;
+ Beta.Responses = Responses;
+ Beta.ChatKit = ChatKit;
+ Beta.Assistants = Assistants;
+ Beta.Threads = Threads2;
+ }
+});
+
+// node_modules/openai/resources/completions.mjs
+var Completions2;
+var init_completions3 = __esm({
+ "node_modules/openai/resources/completions.mjs"() {
+ init_resource();
+ Completions2 = class extends APIResource {
+ create(body, options) {
+ return this._client.post("/completions", {
+ body,
+ ...options,
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/containers/files/content.mjs
+var Content;
+var init_content = __esm({
+ "node_modules/openai/resources/containers/files/content.mjs"() {
+ init_resource();
+ init_headers();
+ init_path();
+ Content = class extends APIResource {
+ /**
+ * Retrieve Container File Content
+ */
+ retrieve(fileID, params, options) {
+ const { container_id } = params;
+ return this._client.get(path`/containers/${container_id}/files/${fileID}/content`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/containers/files/files.mjs
+var Files2;
+var init_files2 = __esm({
+ "node_modules/openai/resources/containers/files/files.mjs"() {
+ init_resource();
+ init_content();
+ init_content();
+ init_pagination();
+ init_headers();
+ init_uploads();
+ init_path();
+ Files2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.content = new Content(this._client);
+ }
+ /**
+ * Create a Container File
+ *
+ * You can send either a multipart/form-data request with the raw file content, or
+ * a JSON request with a file ID.
+ */
+ create(containerID, body, options) {
+ return this._client.post(path`/containers/${containerID}/files`, maybeMultipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Retrieve Container File
+ */
+ retrieve(fileID, params, options) {
+ const { container_id } = params;
+ return this._client.get(path`/containers/${container_id}/files/${fileID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List Container files
+ */
+ list(containerID, query = {}, options) {
+ return this._client.getAPIList(path`/containers/${containerID}/files`, CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete Container File
+ */
+ delete(fileID, params, options) {
+ const { container_id } = params;
+ return this._client.delete(path`/containers/${container_id}/files/${fileID}`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Files2.Content = Content;
+ }
+});
+
+// node_modules/openai/resources/containers/containers.mjs
+var Containers;
+var init_containers = __esm({
+ "node_modules/openai/resources/containers/containers.mjs"() {
+ init_resource();
+ init_files2();
+ init_files2();
+ init_pagination();
+ init_headers();
+ init_path();
+ Containers = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.files = new Files2(this._client);
+ }
+ /**
+ * Create Container
+ */
+ create(body, options) {
+ return this._client.post("/containers", { body, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Retrieve Container
+ */
+ retrieve(containerID, options) {
+ return this._client.get(path`/containers/${containerID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List Containers
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/containers", CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete Container
+ */
+ delete(containerID, options) {
+ return this._client.delete(path`/containers/${containerID}`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Containers.Files = Files2;
+ }
+});
+
+// node_modules/openai/resources/content-provenance-checks.mjs
+var ContentProvenanceChecks;
+var init_content_provenance_checks = __esm({
+ "node_modules/openai/resources/content-provenance-checks.mjs"() {
+ init_resource();
+ init_uploads();
+ ContentProvenanceChecks = class extends APIResource {
+ /**
+ * Check whether an image or audio file contains known OpenAI provenance signals.
+ * [Learn more about content provenance](https://developers.openai.com/api/docs/guides/content-provenance).
+ *
+ * If `not_detected`, it means the tool did not find supported signals in the
+ * uploaded file. The content could still have been generated by OpenAI if the
+ * metadata was stripped or has evidence of tampering, the watermark was degraded,
+ * it comes from a legacy generation model, or it was created before provenance
+ * signals were available. Content could also still be AI-generated by another
+ * company's model, which the tool currently does not detect.
+ */
+ create(body, options) {
+ return this._client.post("/content_provenance_checks", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/conversations/items.mjs
+var Items4;
+var init_items4 = __esm({
+ "node_modules/openai/resources/conversations/items.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Items4 = class extends APIResource {
+ /**
+ * Create items in a conversation with the given ID.
+ */
+ create(conversationID, params, options) {
+ const { include, ...body } = params;
+ return this._client.post(path`/conversations/${conversationID}/items`, {
+ query: { include },
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get a single item from a conversation with the given IDs.
+ */
+ retrieve(itemID, params, options) {
+ const { conversation_id, ...query } = params;
+ return this._client.get(path`/conversations/${conversation_id}/items/${itemID}`, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List all items for a conversation with the given ID.
+ */
+ list(conversationID, query = {}, options) {
+ return this._client.getAPIList(path`/conversations/${conversationID}/items`, ConversationCursorPage, { query, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Delete an item from a conversation with the given IDs.
+ */
+ delete(itemID, params, options) {
+ const { conversation_id } = params;
+ return this._client.delete(path`/conversations/${conversation_id}/items/${itemID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/conversations/conversations.mjs
+var Conversations;
+var init_conversations = __esm({
+ "node_modules/openai/resources/conversations/conversations.mjs"() {
+ init_resource();
+ init_items4();
+ init_items4();
+ init_path();
+ Conversations = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.items = new Items4(this._client);
+ }
+ /**
+ * Create a conversation.
+ */
+ create(body = {}, options) {
+ return this._client.post("/conversations", { body, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Get a conversation
+ */
+ retrieve(conversationID, options) {
+ return this._client.get(path`/conversations/${conversationID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Update a conversation
+ */
+ update(conversationID, body, options) {
+ return this._client.post(path`/conversations/${conversationID}`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a conversation. Items in the conversation will not be deleted.
+ */
+ delete(conversationID, options) {
+ return this._client.delete(path`/conversations/${conversationID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Conversations.Items = Items4;
+ }
+});
+
+// node_modules/openai/lib/embeddings.mjs
+function createEmbedding(client, body, options) {
+ const hasUserProvidedEncodingFormat = !!body.encoding_format;
+ const encodingFormat = hasUserProvidedEncodingFormat ? body.encoding_format : "base64";
+ if (hasUserProvidedEncodingFormat) {
+ loggerFor(client).debug("embeddings/user defined encoding_format:", body.encoding_format);
+ }
+ const optimizedBody = { ...body, encoding_format: encodingFormat };
+ const requestOptions = {
+ body: optimizedBody,
+ ...options,
+ __security: { bearerAuth: true }
+ };
+ const response = client.post("/embeddings", requestOptions);
+ if (hasUserProvidedEncodingFormat) {
+ return response;
+ }
+ loggerFor(client).debug("embeddings/decoding base64 embeddings from base64");
+ return response._thenUnwrap((data) => {
+ const embeddings = data?.data;
+ if (embeddings !== void 0) {
+ if (!Array.isArray(embeddings)) {
+ throw new TypeError("Expected embeddings response data to be an array");
+ }
+ const { length } = embeddings;
+ for (let index3 = 0; index3 < length; index3 += 1) {
+ if (index3 in embeddings) {
+ const embeddingBase64Obj = embeddings[index3];
+ const { embedding } = embeddingBase64Obj;
+ if (Array.isArray(embedding)) {
+ continue;
+ }
+ embeddingBase64Obj.embedding = toFloat32Array(embedding);
+ }
+ }
+ }
+ return data;
+ });
+}
+var init_embeddings = __esm({
+ "node_modules/openai/lib/embeddings.mjs"() {
+ init_utils2();
+ }
+});
+
+// node_modules/openai/resources/embeddings.mjs
+var Embeddings;
+var init_embeddings2 = __esm({
+ "node_modules/openai/resources/embeddings.mjs"() {
+ init_resource();
+ init_embeddings();
+ Embeddings = class extends APIResource {
+ create(body, options) {
+ return createEmbedding(this._client, body, options);
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/evals/runs/output-items.mjs
+var OutputItems;
+var init_output_items = __esm({
+ "node_modules/openai/resources/evals/runs/output-items.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ OutputItems = class extends APIResource {
+ /**
+ * Get an evaluation run output item by ID.
+ */
+ retrieve(outputItemID, params, options) {
+ const { eval_id, run_id } = params;
+ return this._client.get(path`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get a list of output items for an evaluation run.
+ */
+ list(runID, params, options) {
+ const { eval_id, ...query } = params;
+ return this._client.getAPIList(path`/evals/${eval_id}/runs/${runID}/output_items`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/evals/runs/runs.mjs
+var Runs2;
+var init_runs2 = __esm({
+ "node_modules/openai/resources/evals/runs/runs.mjs"() {
+ init_resource();
+ init_output_items();
+ init_output_items();
+ init_pagination();
+ init_path();
+ Runs2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.outputItems = new OutputItems(this._client);
+ }
+ /**
+ * Kicks off a new run for a given evaluation, specifying the data source, and what
+ * model configuration to use to test. The datasource will be validated against the
+ * schema specified in the config of the evaluation.
+ */
+ create(evalID, body, options) {
+ return this._client.post(path`/evals/${evalID}/runs`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get an evaluation run by ID.
+ */
+ retrieve(runID, params, options) {
+ const { eval_id } = params;
+ return this._client.get(path`/evals/${eval_id}/runs/${runID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get a list of runs for an evaluation.
+ */
+ list(evalID, query = {}, options) {
+ return this._client.getAPIList(path`/evals/${evalID}/runs`, CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete an eval run.
+ */
+ delete(runID, params, options) {
+ const { eval_id } = params;
+ return this._client.delete(path`/evals/${eval_id}/runs/${runID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancel an ongoing evaluation run.
+ */
+ cancel(runID, params, options) {
+ const { eval_id } = params;
+ return this._client.post(path`/evals/${eval_id}/runs/${runID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Runs2.OutputItems = OutputItems;
+ }
+});
+
+// node_modules/openai/resources/evals/evals.mjs
+var Evals;
+var init_evals = __esm({
+ "node_modules/openai/resources/evals/evals.mjs"() {
+ init_resource();
+ init_runs2();
+ init_runs2();
+ init_pagination();
+ init_path();
+ Evals = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.runs = new Runs2(this._client);
+ }
+ /**
+ * Create the structure of an evaluation that can be used to test a model's
+ * performance. An evaluation is a set of testing criteria and the config for a
+ * data source, which dictates the schema of the data used in the evaluation. After
+ * creating an evaluation, you can run it on different models and model parameters.
+ * We support several types of graders and datasources. For more information, see
+ * the [Evals guide](https://developers.openai.com/api/docs/guides/evals).
+ */
+ create(body, options) {
+ return this._client.post("/evals", { body, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Get an evaluation by ID.
+ */
+ retrieve(evalID, options) {
+ return this._client.get(path`/evals/${evalID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Update certain properties of an evaluation.
+ */
+ update(evalID, body, options) {
+ return this._client.post(path`/evals/${evalID}`, { body, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * List evaluations for a project.
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/evals", CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete an evaluation.
+ */
+ delete(evalID, options) {
+ return this._client.delete(path`/evals/${evalID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ };
+ Evals.Runs = Runs2;
+ }
+});
+
+// node_modules/openai/lib/file-processing.mjs
+async function waitForFileProcessing(resource, id, pollInterval, maxWait) {
+ const terminalStates = /* @__PURE__ */ new Set(["processed", "error", "deleted"]);
+ const start = performance.now();
+ let file = await resource.retrieve(id);
+ while (!file.status || !terminalStates.has(file.status)) {
+ await sleep(pollInterval);
+ file = await resource.retrieve(id);
+ if (performance.now() - start > maxWait) {
+ throw new APIConnectionTimeoutError({
+ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
+ });
+ }
+ }
+ return file;
+}
+var init_file_processing = __esm({
+ "node_modules/openai/lib/file-processing.mjs"() {
+ init_error2();
+ init_sleep();
+ }
+});
+
+// node_modules/openai/resources/files.mjs
+var Files3;
+var init_files3 = __esm({
+ "node_modules/openai/resources/files.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_uploads();
+ init_file_processing();
+ init_path();
+ Files3 = class extends APIResource {
+ /**
+ * Upload a file that can be used across various endpoints. Individual files can be
+ * up to 512 MB, and each project can store up to 2.5 TB of files in total. There
+ * is no organization-wide storage limit. Uploads to this endpoint are rate-limited
+ * to 1,000 requests per minute per authenticated user.
+ *
+ * - The Assistants API supports files up to 2 million tokens and of specific file
+ * types. See the
+ * [Assistants Tools guide](https://developers.openai.com/api/docs/guides/tools)
+ * for details.
+ * - The Fine-tuning API only supports `.jsonl` files. The input also has certain
+ * required formats for fine-tuning
+ * [chat](https://developers.openai.com/api/docs/guides/supervised-fine-tuning#formatting-your-data)
+ * or
+ * [completions](https://developers.openai.com/api/docs/guides/supervised-fine-tuning#formatting-your-data)
+ * models.
+ * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input
+ * also has a specific required
+ * [format](https://developers.openai.com/api/docs/guides/batch#1-prepare-your-batch-file).
+ * - For Retrieval or `file_search` ingestion, upload files here first. If you need
+ * to attach multiple uploaded files to the same vector store, use
+ * [`/vector_stores/{vector_store_id}/file_batches`](https://developers.openai.com/api/reference/resources/vector_stores/subresources/file_batches/methods/create)
+ * instead of attaching them one by one. Vector store attachment has separate
+ * limits from file upload, including 2,000 attached files per minute per
+ * organization.
+ *
+ * Please [contact us](https://help.openai.com/) if you need to increase these
+ * storage limits.
+ */
+ create(body, options) {
+ return this._client.post("/files", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Returns information about a specific file.
+ */
+ retrieve(fileID, options) {
+ return this._client.get(path`/files/${fileID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Returns a list of files.
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/files", CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a file and remove it from all vector stores.
+ */
+ delete(fileID, options) {
+ return this._client.delete(path`/files/${fileID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Returns a response containing the contents of the specified file.
+ */
+ content(fileID, options) {
+ return this._client.get(path`/files/${fileID}/content`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ /**
+ * Waits for the given file to be processed, default timeout is 30 mins.
+ */
+ async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) {
+ return await waitForFileProcessing(this, id, pollInterval, maxWait);
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/fine-tuning/methods.mjs
+var Methods;
+var init_methods = __esm({
+ "node_modules/openai/resources/fine-tuning/methods.mjs"() {
+ init_resource();
+ Methods = class extends APIResource {
+ };
+ }
+});
+
+// node_modules/openai/resources/fine-tuning/alpha/graders.mjs
+var Graders;
+var init_graders = __esm({
+ "node_modules/openai/resources/fine-tuning/alpha/graders.mjs"() {
+ init_resource();
+ Graders = class extends APIResource {
+ /**
+ * Run a grader.
+ *
+ * @example
+ * ```ts
+ * const response = await client.fineTuning.alpha.graders.run({
+ * grader: {
+ * input: 'input',
+ * name: 'name',
+ * operation: 'eq',
+ * reference: 'reference',
+ * type: 'string_check',
+ * },
+ * model_sample: 'model_sample',
+ * });
+ * ```
+ */
+ run(body, options) {
+ return this._client.post("/fine_tuning/alpha/graders/run", {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Validate a grader.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.fineTuning.alpha.graders.validate({
+ * grader: {
+ * input: 'input',
+ * name: 'name',
+ * operation: 'eq',
+ * reference: 'reference',
+ * type: 'string_check',
+ * },
+ * });
+ * ```
+ */
+ validate(body, options) {
+ return this._client.post("/fine_tuning/alpha/graders/validate", {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/fine-tuning/alpha/alpha.mjs
+var Alpha;
+var init_alpha = __esm({
+ "node_modules/openai/resources/fine-tuning/alpha/alpha.mjs"() {
+ init_resource();
+ init_graders();
+ init_graders();
+ Alpha = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.graders = new Graders(this._client);
+ }
+ };
+ Alpha.Graders = Graders;
+ }
+});
+
+// node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs
+var Permissions;
+var init_permissions = __esm({
+ "node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Permissions = class extends APIResource {
+ /**
+ * **NOTE:** Calling this endpoint requires an
+ * [admin API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys).
+ *
+ * This enables organization owners to share fine-tuned models with other projects
+ * in their organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(
+ * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
+ * { project_ids: ['string'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ create(fineTunedModelCheckpoint, body, options) {
+ return this._client.getAPIList(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, Page, { body, method: "post", ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * **NOTE:** This endpoint requires an
+ * [admin API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys).
+ *
+ * Organization owners can use this endpoint to view all permissions for a
+ * fine-tuned model checkpoint.
+ *
+ * @deprecated Retrieve is deprecated. Please swap to the paginated list method instead.
+ */
+ retrieve(fineTunedModelCheckpoint, query = {}, options) {
+ return this._client.get(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, {
+ query,
+ ...options,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * **NOTE:** This endpoint requires an
+ * [admin API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys).
+ *
+ * Organization owners can use this endpoint to view all permissions for a
+ * fine-tuned model checkpoint.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const permissionListResponse of client.fineTuning.checkpoints.permissions.list(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(fineTunedModelCheckpoint, query = {}, options) {
+ return this._client.getAPIList(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * **NOTE:** This endpoint requires an
+ * [admin API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys).
+ *
+ * Organization owners can use this endpoint to delete a permission for a
+ * fine-tuned model checkpoint.
+ *
+ * @example
+ * ```ts
+ * const permission =
+ * await client.fineTuning.checkpoints.permissions.delete(
+ * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB',
+ * {
+ * fine_tuned_model_checkpoint:
+ * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
+ * },
+ * );
+ * ```
+ */
+ delete(permissionID, params, options) {
+ const { fine_tuned_model_checkpoint } = params;
+ return this._client.delete(path`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, { ...options, __security: { adminAPIKeyAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs
+var Checkpoints;
+var init_checkpoints = __esm({
+ "node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs"() {
+ init_resource();
+ init_permissions();
+ init_permissions();
+ Checkpoints = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.permissions = new Permissions(this._client);
+ }
+ };
+ Checkpoints.Permissions = Permissions;
+ }
+});
+
+// node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs
+var Checkpoints2;
+var init_checkpoints2 = __esm({
+ "node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Checkpoints2 = class extends APIResource {
+ /**
+ * List checkpoints for a fine-tuning job.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(fineTuningJobID, query = {}, options) {
+ return this._client.getAPIList(path`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
+var Jobs;
+var init_jobs = __esm({
+ "node_modules/openai/resources/fine-tuning/jobs/jobs.mjs"() {
+ init_resource();
+ init_checkpoints2();
+ init_checkpoints2();
+ init_pagination();
+ init_path();
+ Jobs = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.checkpoints = new Checkpoints2(this._client);
+ }
+ /**
+ * Creates a fine-tuning job which begins the process of creating a new model from
+ * a given dataset.
+ *
+ * Response includes details of the enqueued job including job status and the name
+ * of the fine-tuned models once complete.
+ *
+ * [Learn more about fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization)
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.create({
+ * model: 'gpt-4o-mini',
+ * training_file: 'file-abc123',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/fine_tuning/jobs", { body, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Get info about a fine-tuning job.
+ *
+ * [Learn more about fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization)
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.retrieve(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * );
+ * ```
+ */
+ retrieve(fineTuningJobID, options) {
+ return this._client.get(path`/fine_tuning/jobs/${fineTuningJobID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List your organization's fine-tuning jobs
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const fineTuningJob of client.fineTuning.jobs.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/fine_tuning/jobs", CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Immediately cancel a fine-tune job.
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.cancel(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * );
+ * ```
+ */
+ cancel(fineTuningJobID, options) {
+ return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/cancel`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get status updates for a fine-tuning job.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ listEvents(fineTuningJobID, query = {}, options) {
+ return this._client.getAPIList(path`/fine_tuning/jobs/${fineTuningJobID}/events`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Pause a fine-tune job.
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.pause(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * );
+ * ```
+ */
+ pause(fineTuningJobID, options) {
+ return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/pause`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Resume a fine-tune job.
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.resume(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * );
+ * ```
+ */
+ resume(fineTuningJobID, options) {
+ return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/resume`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Jobs.Checkpoints = Checkpoints2;
+ }
+});
+
+// node_modules/openai/resources/fine-tuning/fine-tuning.mjs
+var FineTuning;
+var init_fine_tuning = __esm({
+ "node_modules/openai/resources/fine-tuning/fine-tuning.mjs"() {
+ init_resource();
+ init_methods();
+ init_methods();
+ init_alpha();
+ init_alpha();
+ init_checkpoints();
+ init_checkpoints();
+ init_jobs();
+ init_jobs();
+ FineTuning = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.methods = new Methods(this._client);
+ this.jobs = new Jobs(this._client);
+ this.checkpoints = new Checkpoints(this._client);
+ this.alpha = new Alpha(this._client);
+ }
+ };
+ FineTuning.Methods = Methods;
+ FineTuning.Jobs = Jobs;
+ FineTuning.Checkpoints = Checkpoints;
+ FineTuning.Alpha = Alpha;
+ }
+});
+
+// node_modules/openai/resources/graders/grader-models.mjs
+var GraderModels;
+var init_grader_models = __esm({
+ "node_modules/openai/resources/graders/grader-models.mjs"() {
+ init_resource();
+ GraderModels = class extends APIResource {
+ };
+ }
+});
+
+// node_modules/openai/resources/graders/graders.mjs
+var Graders2;
+var init_graders2 = __esm({
+ "node_modules/openai/resources/graders/graders.mjs"() {
+ init_resource();
+ init_grader_models();
+ init_grader_models();
+ Graders2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.graderModels = new GraderModels(this._client);
+ }
+ };
+ Graders2.GraderModels = GraderModels;
+ }
+});
+
+// node_modules/openai/resources/images.mjs
+var Images;
+var init_images = __esm({
+ "node_modules/openai/resources/images.mjs"() {
+ init_resource();
+ init_uploads();
+ Images = class extends APIResource {
+ /**
+ * Creates a variation of a given image. This endpoint only supports `dall-e-2`.
+ *
+ * @example
+ * ```ts
+ * const imagesResponse = await client.images.createVariation({
+ * image: fs.createReadStream('otter.png'),
+ * });
+ * ```
+ */
+ createVariation(body, options) {
+ return this._client.post("/images/variations", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ edit(body, options) {
+ return this._client.post("/images/edits", multipartFormRequestOptions({
+ body,
+ ...options,
+ stream: body.stream ?? false,
+ __metadata: { ...options?.__metadata, ...body.model == null ? {} : { model: body.model } },
+ __security: { bearerAuth: true }
+ }, this._client));
+ }
+ generate(body, options) {
+ return this._client.post("/images/generations", {
+ body,
+ ...options,
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/live/sessions.mjs
+var Sessions4;
+var init_sessions4 = __esm({
+ "node_modules/openai/resources/live/sessions.mjs"() {
+ init_resource();
+ init_headers();
+ init_path();
+ Sessions4 = class extends APIResource {
+ /**
+ * Accept an incoming SIP call. Supply session with type live, the model, and
+ * startup configuration. Before accepting calls, follow the
+ * [Live prompting guide](https://developers.openai.com/api/docs/guides/live-prompting)
+ * to write frontend conversation instructions and a separate backend prompt. SIP
+ * media format is negotiated; omit audio.format.
+ *
+ * @example
+ * ```ts
+ * await client.live.sessions.accept('session_id', {
+ * session: { model: 'gpt-live-1', type: 'live' },
+ * });
+ * ```
+ */
+ accept(sessionID, body, options) {
+ return this._client.post(path`/live/sessions/${sessionID}/accept`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get Live session content
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.live.sessions.downloadRecording('live_SQ');
+ *
+ * const content = await response.blob();
+ * console.log(content);
+ * ```
+ */
+ downloadRecording(sessionID, options) {
+ return this._client.get(path`/live/sessions/${sessionID}/content`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ /**
+ * Fork a stored Live session onto a new WebRTC connection.
+ *
+ * @example
+ * ```ts
+ * const response = await client.live.sessions.fork(
+ * 'session_id',
+ * { transport: { sdp: 'x', type: 'webrtc' } },
+ * );
+ * ```
+ */
+ fork(sessionID, body, options) {
+ return this._client.post(path`/live/sessions/${sessionID}/fork`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * End a SIP call identified by session_id.
+ *
+ * @example
+ * ```ts
+ * await client.live.sessions.hangup('session_id');
+ * ```
+ */
+ hangup(sessionID, options) {
+ return this._client.post(path`/live/sessions/${sessionID}/hangup`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Transfer a SIP call to another destination. Supply a nonblank target_uri for the
+ * SIP Refer-To header.
+ *
+ * @example
+ * ```ts
+ * await client.live.sessions.refer('session_id', {
+ * target_uri: 'tel:+14155550123',
+ * });
+ * ```
+ */
+ refer(sessionID, body, options) {
+ return this._client.post(path`/live/sessions/${sessionID}/refer`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Reject an incoming SIP call. Send a required SIP rejection status_code between
+ * 300 and 699.
+ *
+ * @example
+ * ```ts
+ * await client.live.sessions.reject('session_id', {
+ * status_code: 486,
+ * });
+ * ```
+ */
+ reject(sessionID, body, options) {
+ return this._client.post(path`/live/sessions/${sessionID}/reject`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/live/forks/forks.mjs
+var Forks;
+var init_forks = __esm({
+ "node_modules/openai/resources/live/forks/forks.mjs"() {
+ init_resource();
+ Forks = class extends APIResource {
+ };
+ }
+});
+
+// node_modules/openai/resources/live/sideband/sideband.mjs
+var Sideband;
+var init_sideband = __esm({
+ "node_modules/openai/resources/live/sideband/sideband.mjs"() {
+ init_resource();
+ Sideband = class extends APIResource {
+ };
+ }
+});
+
+// node_modules/openai/resources/live/live.mjs
+var Live;
+var init_live = __esm({
+ "node_modules/openai/resources/live/live.mjs"() {
+ init_resource();
+ init_sessions4();
+ init_sessions4();
+ init_forks();
+ init_forks();
+ init_sideband();
+ init_sideband();
+ Live = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.sideband = new Sideband(this._client);
+ this.forks = new Forks(this._client);
+ this.sessions = new Sessions4(this._client);
+ }
+ /**
+ * Create a Live WebRTC session. Start with the
+ * [Live prompting guide](https://developers.openai.com/api/docs/guides/live-prompting).
+ *
+ * @example
+ * ```ts
+ * const live = await client.live.create({
+ * session: { model: 'gpt-live-1' },
+ * transport: { sdp: 'x', type: 'webrtc' },
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/live/sessions", { body, ...options, __security: { bearerAuth: true } });
+ }
+ };
+ Live.Sideband = Sideband;
+ Live.Forks = Forks;
+ Live.Sessions = Sessions4;
+ }
+});
+
+// node_modules/openai/resources/models.mjs
+var Models;
+var init_models2 = __esm({
+ "node_modules/openai/resources/models.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ Models = class extends APIResource {
+ /**
+ * Retrieves a model instance, providing basic information about the model such as
+ * the owner and permissioning.
+ */
+ retrieve(model, options) {
+ return this._client.get(path`/models/${model}`, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Lists the currently available models, and provides basic information about each
+ * one such as the owner and availability.
+ */
+ list(options) {
+ return this._client.getAPIList("/models", Page, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Delete a fine-tuned model. You must have the Owner role in your organization to
+ * delete a model.
+ */
+ delete(model, options) {
+ return this._client.delete(path`/models/${model}`, { ...options, __security: { bearerAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/moderations.mjs
+var Moderations;
+var init_moderations = __esm({
+ "node_modules/openai/resources/moderations.mjs"() {
+ init_resource();
+ Moderations = class extends APIResource {
+ /**
+ * Classifies if text and/or image inputs are potentially harmful. Learn more in
+ * the
+ * [moderation guide](https://developers.openai.com/api/docs/guides/moderation).
+ */
+ create(body, options) {
+ return this._client.post("/moderations", { body, ...options, __security: { bearerAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/multipart-encoding.mjs
+async function encodedMultipartFormRequestOptions(options, client, encodings, rawBodyField = null) {
+ if (options.body === null || typeof options.body !== "object" || Array.isArray(options.body)) {
+ throw new TypeError("Multipart request body must be an object");
+ }
+ const body = Object.fromEntries(Object.entries(options.body).filter(([, value]) => value !== void 0));
+ if (rawBodyField !== null && Object.keys(body).length === 1 && Object.prototype.hasOwnProperty.call(body, rawBodyField)) {
+ const value = body[rawBodyField];
+ if (typeof value !== "string")
+ throw new TypeError("Raw multipart alternative must be a string");
+ return {
+ ...options,
+ body: value,
+ headers: buildHeaders([options.headers, { "content-type": encodings[rawBodyField].content_type }])
+ };
+ }
+ const encoded = [];
+ for (const [name, encoding] of Object.entries(encodings)) {
+ if (!Object.prototype.hasOwnProperty.call(body, name))
+ continue;
+ const value = body[name];
+ const data = encoding.json ? JSON.stringify(value) : value;
+ if (typeof data !== "string")
+ throw new TypeError(`Multipart field ${name} must encode as a string`);
+ encoded.push([name, makeFile([data], "", { type: encoding.content_type })]);
+ delete body[name];
+ }
+ const multipart = await multipartFormRequestOptions({ ...options, body }, client);
+ const form = multipart.body;
+ if (!(form instanceof FormData)) {
+ await form.cancel();
+ throw new TypeError("Unexpected streaming upload in typed multipart request body");
+ }
+ for (const [name, part] of encoded)
+ form.append(name, part, "");
+ return {
+ ...options,
+ body: form,
+ headers: buildHeaders([options.headers, { "content-type": null }])
+ };
+}
+var init_multipart_encoding = __esm({
+ "node_modules/openai/internal/multipart-encoding.mjs"() {
+ init_uploads();
+ init_headers();
+ }
+});
+
+// node_modules/openai/resources/realtime/calls.mjs
+var Calls;
+var init_calls = __esm({
+ "node_modules/openai/resources/realtime/calls.mjs"() {
+ init_resource();
+ init_headers();
+ init_path();
+ init_multipart_encoding();
+ Calls = class extends APIResource {
+ /**
+ * Create a new Realtime API call over WebRTC and receive the SDP answer needed to
+ * complete the peer connection.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.create({
+ * sdp: 'sdp',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/realtime/calls", encodedMultipartFormRequestOptions({
+ body,
+ ...options,
+ headers: buildHeaders([{ Accept: "application/sdp" }, options?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ }, this._client, {
+ sdp: { content_type: "application/sdp", json: false },
+ session: { content_type: "application/json", json: true }
+ }, "sdp"));
+ }
+ /**
+ * Accept an incoming SIP call and configure the realtime session that will handle
+ * it.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.accept('call_id', {
+ * type: 'realtime',
+ * });
+ * ```
+ */
+ accept(callID, body, options) {
+ return this._client.post(path`/realtime/calls/${callID}/accept`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * End an active Realtime API call, whether it was initiated over SIP or WebRTC.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.hangup('call_id');
+ * ```
+ */
+ hangup(callID, options) {
+ return this._client.post(path`/realtime/calls/${callID}/hangup`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Transfer an active SIP call to a new destination using the SIP REFER verb.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.refer('call_id', {
+ * target_uri: 'tel:+14155550123',
+ * });
+ * ```
+ */
+ refer(callID, body, options) {
+ return this._client.post(path`/realtime/calls/${callID}/refer`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Decline an incoming SIP call by returning a SIP status code to the caller.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.reject('call_id');
+ * ```
+ */
+ reject(callID, body = {}, options) {
+ return this._client.post(path`/realtime/calls/${callID}/reject`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/realtime/client-secrets.mjs
+var ClientSecrets;
+var init_client_secrets = __esm({
+ "node_modules/openai/resources/realtime/client-secrets.mjs"() {
+ init_resource();
+ ClientSecrets = class extends APIResource {
+ /**
+ * Create a Realtime client secret with an associated session configuration.
+ *
+ * Client secrets are short-lived tokens that can be passed to a client app, such
+ * as a web frontend or mobile client, which grants access to the Realtime API
+ * without leaking your main API key. You can configure a custom TTL for each
+ * client secret.
+ *
+ * You can also attach session configuration options to the client secret, which
+ * will be applied to any sessions created using that client secret, but these can
+ * also be overridden by the client connection.
+ *
+ * [Learn more about authentication with client secrets over WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc).
+ *
+ * Returns the created client secret and the effective session object. The client
+ * secret is a string that looks like `ek_1234`.
+ *
+ * @example
+ * ```ts
+ * const clientSecret =
+ * await client.realtime.clientSecrets.create();
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/realtime/client_secrets", {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/realtime/realtime.mjs
+var Realtime2;
+var init_realtime2 = __esm({
+ "node_modules/openai/resources/realtime/realtime.mjs"() {
+ init_resource();
+ init_calls();
+ init_calls();
+ init_client_secrets();
+ init_client_secrets();
+ Realtime2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.clientSecrets = new ClientSecrets(this._client);
+ this.calls = new Calls(this._client);
+ }
+ };
+ Realtime2.ClientSecrets = ClientSecrets;
+ Realtime2.Calls = Calls;
+ }
+});
+
+// node_modules/openai/lib/ResponsesParser.mjs
+function maybeParseResponse(response, params) {
+ if (!params || !hasAutoParseableInput2(params)) {
+ const parsed = {
+ ...response,
+ output_parsed: null,
+ output: response.output.map((item) => {
+ if (item.type === "function_call") {
+ return {
+ ...item,
+ parsed_arguments: null
+ };
+ }
+ if (item.type === "message") {
+ return {
+ ...item,
+ content: item.content.map((content) => ({
+ ...content,
+ parsed: null
+ }))
+ };
+ }
+ return item;
+ })
+ };
+ if (needsOutputText(response, parsed)) {
+ addOutputText(parsed);
+ }
+ return parsed;
+ }
+ return parseResponse(response, params);
+}
+function parseResponse(response, params) {
+ const shouldParse = !response.status || response.status === "completed";
+ const output = response.output.map((item) => {
+ if (item.type === "function_call") {
+ return shouldParse ? parseToolCall2(params, item) : { ...item, parsed_arguments: null };
+ }
+ if (item.type === "message") {
+ const content = item.content.map((content2) => {
+ if (content2.type === "output_text") {
+ return {
+ ...content2,
+ parsed: shouldParse ? parseTextFormat(params, content2.text) : null
+ };
+ }
+ return content2;
+ });
+ return {
+ ...item,
+ content
+ };
+ }
+ return item;
+ });
+ const parsed = { ...response, output };
+ if (needsOutputText(response, parsed)) {
+ addOutputText(parsed);
+ }
+ Object.defineProperty(parsed, "output_parsed", {
+ enumerable: true,
+ get() {
+ for (const output2 of parsed.output) {
+ if (output2.type !== "message") {
+ continue;
+ }
+ for (const content of output2.content) {
+ if (content.type === "output_text" && content.parsed !== null) {
+ return content.parsed;
+ }
+ }
+ }
+ return null;
+ }
+ });
+ return parsed;
+}
+function parseTextFormat(params, content) {
+ return parseResponseFormatContent(params.text?.format, content);
+}
+function hasAutoParseableInput2(params) {
+ if (isParseableResponseFormat(params.text?.format)) {
+ return true;
+ }
+ return Array.isArray(params.tools) && params.tools.some((tool) => isAutoParsableTool2(tool) || tool.type === "function" && tool.strict === true || tool.type === "namespace" && tool.tools.some((nested) => nested.type === "function" && (isAutoParsableTool2(nested) || nested.strict === true)));
+}
+function isAutoParsableTool2(tool) {
+ return tool?.["$brand"] === "auto-parseable-tool";
+}
+function getInputToolByName(input_tools, name, namespace) {
+ for (const tool of input_tools) {
+ if (namespace == null) {
+ if (tool.type === "function" && tool.name === name) {
+ return tool;
+ }
+ } else if (tool.type === "namespace" && tool.name === namespace) {
+ return tool.tools.find((nested) => nested.type === "function" && nested.name === name);
+ }
+ }
+ return void 0;
+}
+function parseToolCall2(params, toolCall) {
+ const inputTool = getInputToolByName(params.tools ?? [], toolCall.name, toolCall.namespace);
+ let parsedArguments = null;
+ if (isAutoParsableTool2(inputTool)) {
+ parsedArguments = inputTool.$parseRaw(toolCall.arguments);
+ } else if (inputTool?.strict) {
+ parsedArguments = parseResponseFormatContent({ type: "json_schema", $parseRaw: void 0 }, toolCall.arguments);
+ }
+ return {
+ ...toolCall,
+ parsed_arguments: parsedArguments
+ };
+}
+function needsOutputText(response, target) {
+ return !Object.getOwnPropertyDescriptor(response, "output_text") || target.output_text == null;
+}
+function addOutputText(rsp) {
+ const texts = [];
+ for (const output of rsp.output) {
+ if (output.type !== "message") {
+ continue;
+ }
+ for (const content of output.content) {
+ if (content.type === "output_text") {
+ texts.push(content.text);
+ }
+ }
+ }
+ rsp.output_text = texts.join("");
+}
+var init_ResponsesParser = __esm({
+ "node_modules/openai/lib/ResponsesParser.mjs"() {
+ init_error2();
+ init_parser();
+ }
+});
+
+// node_modules/openai/internal/responses/output-text-index.mjs
+var OutputTextIndex;
+var init_output_text_index = __esm({
+ "node_modules/openai/internal/responses/output-text-index.mjs"() {
+ OutputTextIndex = class {
+ constructor() {
+ this.capacity = 1;
+ this.values = [0, 0];
+ this.size = 0;
+ }
+ get length() {
+ return this.size;
+ }
+ append(value) {
+ if (this.size === this.capacity) {
+ this.grow();
+ }
+ const index3 = this.size;
+ this.size += 1;
+ this.update(index3, value);
+ }
+ update(index3, value) {
+ if (!Number.isSafeInteger(index3) || index3 < 0 || index3 >= this.size) {
+ throw new RangeError(`missing output at index ${index3}`);
+ }
+ let node = this.capacity + index3;
+ const difference = value - (this.values[node] ?? 0);
+ if (difference === 0) {
+ return;
+ }
+ while (node >= 1) {
+ this.values[node] = (this.values[node] ?? 0) + difference;
+ node = Math.floor(node / 2);
+ }
+ }
+ prefixSum(end) {
+ if (!Number.isSafeInteger(end) || end < 0 || end > this.size) {
+ throw new RangeError(`missing output at index ${end}`);
+ }
+ let start = this.capacity;
+ let stop = this.capacity + end;
+ let sum = 0;
+ while (start < stop) {
+ if (start % 2 === 1) {
+ sum += this.values[start] ?? 0;
+ start += 1;
+ }
+ if (stop % 2 === 1) {
+ stop -= 1;
+ sum += this.values[stop] ?? 0;
+ }
+ start = Math.floor(start / 2);
+ stop = Math.floor(stop / 2);
+ }
+ return sum;
+ }
+ grow() {
+ const previousCapacity = this.capacity;
+ this.capacity *= 2;
+ const values = Array.from({ length: this.capacity * 2 }, () => 0);
+ for (let index3 = 0; index3 < this.size; index3 += 1) {
+ values[this.capacity + index3] = this.values[previousCapacity + index3] ?? 0;
+ }
+ for (let index3 = this.capacity - 1; index3 > 0; index3 -= 1) {
+ values[index3] = (values[index3 * 2] ?? 0) + (values[index3 * 2 + 1] ?? 0);
+ }
+ this.values = values;
+ }
+ };
+ }
+});
+
+// node_modules/openai/internal/responses/canonical-output-text.mjs
+function createCanonicalResponseContext() {
+ return {
+ canonicalSnapshot: void 0,
+ outputTextLengths: /* @__PURE__ */ new WeakMap(),
+ outputTextIndex: new OutputTextIndex()
+ };
+}
+function getOutputText(context, output) {
+ if (output.type !== "message") {
+ return "";
+ }
+ let text = "";
+ for (const content of output.content) {
+ if (content.type === "output_text") {
+ text += content.text;
+ }
+ }
+ context.outputTextLengths.set(output, text.length);
+ return text;
+}
+function ensureCanonicalOutputText(context, snapshot) {
+ if (context.canonicalSnapshot === snapshot) {
+ return;
+ }
+ const outputTextIndex = new OutputTextIndex();
+ let text = "";
+ for (const output of snapshot.output) {
+ const outputText = getOutputText(context, output);
+ text += outputText;
+ outputTextIndex.append(outputText.length);
+ }
+ snapshot.output_text = text;
+ context.outputTextIndex = outputTextIndex;
+ context.canonicalSnapshot = snapshot;
+}
+function cloneResponse(context, response) {
+ context.canonicalSnapshot = void 0;
+ context.outputTextLengths = /* @__PURE__ */ new WeakMap();
+ context.outputTextIndex = new OutputTextIndex();
+ const snapshot = structuredClone(response);
+ if (!Object.getOwnPropertyDescriptor(snapshot, "output_text") || snapshot.output_text === null || snapshot.output_text === void 0) {
+ ensureCanonicalOutputText(context, snapshot);
+ } else if (snapshot.output.length === 0 && snapshot.output_text === "") {
+ context.canonicalSnapshot = snapshot;
+ }
+ return snapshot;
+}
+function updateCachedOutputTextLength(context, output, outputIndex, previousText, nextText) {
+ const length = context.outputTextLengths.get(output);
+ if (length !== void 0) {
+ const nextLength = length - previousText.length + nextText.length;
+ context.outputTextLengths.set(output, nextLength);
+ context.outputTextIndex.update(outputIndex, nextLength);
+ }
+}
+function replaceOutputTextSuffix(snapshot, previousText, nextText) {
+ if (previousText.length === 0) {
+ snapshot.output_text += nextText;
+ return;
+ }
+ snapshot.output_text = snapshot.output_text.slice(0, snapshot.output_text.length - previousText.length) + nextText;
+}
+function getPrecedingContentTextLength(context, output, contentIndex, nextText) {
+ if (contentIndex === void 0 || output?.type !== "message") {
+ return 0;
+ }
+ if (contentIndex < output.content.length - contentIndex - 1) {
+ let precedingContentLength = 0;
+ for (let index3 = 0; index3 < contentIndex; index3 += 1) {
+ const precedingContent = output.content[index3];
+ if (precedingContent?.type === "output_text") {
+ precedingContentLength += precedingContent.text.length;
+ }
+ }
+ return precedingContentLength;
+ }
+ let followingContentLength = 0;
+ for (let index3 = contentIndex + 1; index3 < output.content.length; index3 += 1) {
+ const followingContent = output.content[index3];
+ if (followingContent?.type === "output_text") {
+ followingContentLength += followingContent.text.length;
+ }
+ }
+ const outputTextLength = context.outputTextLengths.get(output) ?? getOutputText(context, output).length;
+ return outputTextLength - followingContentLength - nextText.length;
+}
+function updateOutputText(context, snapshot, outputIndex, previousText, nextText, contentIndex) {
+ if (previousText === nextText) {
+ return;
+ }
+ const output = snapshot.output[outputIndex];
+ if (outputIndex === snapshot.output.length - 1 && (contentIndex === void 0 || output?.type === "message" && contentIndex === output.content.length - 1)) {
+ replaceOutputTextSuffix(snapshot, previousText, nextText);
+ return;
+ }
+ const precedingContentLength = getPrecedingContentTextLength(context, output, contentIndex, nextText);
+ const offset = context.outputTextIndex.prefixSum(outputIndex) + precedingContentLength;
+ if (offset + previousText.length === snapshot.output_text.length) {
+ replaceOutputTextSuffix(snapshot, previousText, nextText);
+ return;
+ }
+ snapshot.output_text = snapshot.output_text.slice(0, offset) + nextText + snapshot.output_text.slice(offset + previousText.length);
+}
+var init_canonical_output_text = __esm({
+ "node_modules/openai/internal/responses/canonical-output-text.mjs"() {
+ init_output_text_index();
+ }
+});
+
+// node_modules/openai/internal/responses/response-accumulator.mjs
+function validateArrayIndex(collection, index3, kind, allowAppend = false) {
+ if (!Array.isArray(collection) || !Number.isSafeInteger(index3) || index3 < 0 || index3 > collection.length || (index3 === collection.length ? !allowAppend || index3 in collection : !hasOwn(collection, index3))) {
+ throw new OpenAIError(`missing ${kind} at index ${index3}`);
+ }
+}
+function validateArrayAppend(collection, index3, kind) {
+ if (index3 !== collection.length) {
+ throw new OpenAIError(`missing ${kind} at index ${index3}`);
+ }
+ validateArrayIndex(collection, index3, kind, true);
+}
+function getOutput(snapshot, outputIndex) {
+ validateArrayIndex(snapshot.output, outputIndex, "output");
+ const output = snapshot.output[outputIndex];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${outputIndex}`);
+ }
+ return output;
+}
+function hasRoutedOutputCallIdentity(output) {
+ return output.type === "function_call" || output.type === "custom_tool_call" || output.type === "shell_call" || output.type === "shell_call_output";
+}
+function getOutputItemIdentityKeys(output, eventType) {
+ if (!hasOwn(output, "type") || typeof output.type !== "string") {
+ throw new OpenAIError(`expected an own output item type for ${eventType}`);
+ }
+ const optionalPlatformID = output.type === "function_call" || output.type === "custom_tool_call";
+ const identities = [];
+ if (hasOwn(output, "id")) {
+ if (typeof output.id !== "string" || output.id.length === 0) {
+ throw new OpenAIError(`expected a non-empty output item id for ${eventType}`);
+ }
+ identities.push(`id:${output.id}`);
+ } else if (!optionalPlatformID) {
+ throw new OpenAIError(`expected a non-empty output item id for ${eventType}`);
+ }
+ if (hasRoutedOutputCallIdentity(output)) {
+ if (!hasOwn(output, "call_id") || typeof output.call_id !== "string" || output.call_id.length === 0) {
+ throw new OpenAIError(`expected a non-empty output item call_id for ${eventType}`);
+ }
+ identities.push(`call:${output.type}:${output.call_id}`);
+ }
+ return identities;
+}
+function assertOutputItemIdentitiesAvailable(identities, keys) {
+ for (const key of keys) {
+ if (identities.has(key)) {
+ throw new OpenAIError(`duplicate output item identity '${key}'`);
+ }
+ }
+}
+function addOutputItemIdentities(identities, keys) {
+ assertOutputItemIdentitiesAvailable(identities, keys);
+ for (const key of keys) {
+ identities.add(key);
+ }
+}
+function createResponseOutputIdentityIndex(snapshot) {
+ const identityIndex = {
+ snapshot,
+ output: snapshot.output,
+ length: snapshot.output.length,
+ identities: /* @__PURE__ */ new Set()
+ };
+ for (let index3 = 0; index3 < snapshot.output.length; index3 += 1) {
+ const output = getOutput(snapshot, index3);
+ addOutputItemIdentities(identityIndex.identities, getOutputItemIdentityKeys(output, "response snapshot"));
+ }
+ return identityIndex;
+}
+function getResponseOutputIdentityIndex(context, snapshot) {
+ const cached = responseOutputIdentityIndexes.get(context);
+ if (cached && cached.snapshot === snapshot && cached.output === snapshot.output && cached.length === snapshot.output.length) {
+ return cached;
+ }
+ const identityIndex = createResponseOutputIdentityIndex(snapshot);
+ responseOutputIdentityIndexes.set(context, identityIndex);
+ return identityIndex;
+}
+function cloneValidatedResponse(context, response) {
+ const nextContext = createCanonicalResponseContext();
+ const snapshot = cloneResponse(nextContext, response);
+ const identityIndex = createResponseOutputIdentityIndex(snapshot);
+ context.canonicalSnapshot = nextContext.canonicalSnapshot;
+ context.outputTextLengths = nextContext.outputTextLengths;
+ context.outputTextIndex = nextContext.outputTextIndex;
+ responseOutputIdentityIndexes.set(context, identityIndex);
+ return snapshot;
+}
+function getExpectedOutputItemType(event) {
+ if (event.type === "response.content_part.added" || event.type === "response.content_part.done") {
+ return event.part.type === "reasoning_text" ? "reasoning" : "message";
+ }
+ return expectedOutputItemTypes[event.type];
+}
+function validateCompletedOutputItemIdentity(event, snapshot) {
+ const output = getOutput(snapshot, event.output_index);
+ const replacement = event.item;
+ getOutputItemIdentityKeys(output, event.type);
+ getOutputItemIdentityKeys(replacement, event.type);
+ if (!hasOwn(replacement, "type") || output.type !== replacement.type) {
+ throw new OpenAIError(`expected output item type '${output.type}', got '${replacement.type}'`);
+ }
+ const outputID = hasOwn(output, "id") ? output.id : void 0;
+ const replacementID = hasOwn(replacement, "id") ? replacement.id : void 0;
+ if (outputID !== replacementID) {
+ throw new OpenAIError(`expected output item id '${outputID}', got '${replacementID}'`);
+ }
+ if (hasRoutedOutputCallIdentity(output) && hasRoutedOutputCallIdentity(replacement) && output.call_id !== replacement.call_id) {
+ throw new OpenAIError(`expected output item call_id '${output.call_id}', got '${replacement.call_id}'`);
+ }
+}
+function validateOutputItemIdentity(event, snapshot, rejectInvalidShellTargets) {
+ if (event.type === "response.output_item.done") {
+ validateCompletedOutputItemIdentity(event, snapshot);
+ return;
+ }
+ if (rejectInvalidShellTargets && (event.type === "response.shell_call_command.added" || event.type === "response.shell_call_command.delta" || event.type === "response.shell_call_command.done")) {
+ const output2 = getOutput(snapshot, event.output_index);
+ if (!hasOwn(output2, "type") || output2.type !== "shell_call") {
+ throw new OpenAIError(`expected output item type 'shell_call', got '${output2.type}'`);
+ }
+ return;
+ }
+ if (event.type !== "response.content_part.added" && event.type !== "response.content_part.done" && !hasOwn(expectedOutputItemTypes, event.type)) {
+ return;
+ }
+ const itemEvent = event;
+ if (!hasOwn(event, "item_id") || typeof itemEvent.item_id !== "string" || itemEvent.item_id.length === 0) {
+ throw new OpenAIError(`expected a non-empty item_id for ${event.type}`);
+ }
+ const output = getOutput(snapshot, itemEvent.output_index);
+ const outputID = hasOwn(output, "id") ? output.id : void 0;
+ if (outputID !== itemEvent.item_id) {
+ throw new OpenAIError(`expected item_id '${outputID}', got '${itemEvent.item_id}'`);
+ }
+ const expectedType = getExpectedOutputItemType(itemEvent);
+ if (output.type !== expectedType) {
+ throw new OpenAIError(`expected output item type '${expectedType}', got '${output.type}'`);
+ }
+}
+function getContent(content, contentIndex) {
+ validateArrayIndex(content, contentIndex, "content");
+ const part = content[contentIndex];
+ if (!part) {
+ throw new OpenAIError(`missing content at index ${contentIndex}`);
+ }
+ return part;
+}
+function getShellOutputContent(snapshot, output, commandIndex) {
+ const shellCall = snapshot.output.find((item) => item.type === "shell_call" && item.call_id === output.call_id);
+ if (shellCall) {
+ validateArrayIndex(shellCall.action.commands, commandIndex, "command");
+ } else {
+ validateArrayIndex(output.output, commandIndex, "content", true);
+ }
+ while (output.output.length <= commandIndex) {
+ output.output.push({
+ stdout: "",
+ stderr: "",
+ outcome: { type: "exit", exit_code: 0 }
+ });
+ }
+ return getContent(output.output, commandIndex);
+}
+function createSupportedResponseEventTypes(eventTypes) {
+ return new Set(eventTypes);
+}
+function assertNever3(_value) {
+ throw new OpenAIError("Unhandled response stream event: unknown");
+}
+function sanitizeResponseEvent(event) {
+ let descriptor;
+ try {
+ descriptor = Object.getOwnPropertyDescriptor(event, "type");
+ } catch {
+ return assertNever3(event);
+ }
+ const type = descriptor?.value;
+ if (
+ // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate untrusted streamed item identifiers and discriminators before mutating the response snapshot.
+ typeof type !== "string" || !supportedResponseEventTypes.has(type)
+ ) {
+ return assertNever3(event);
+ }
+ const stableValues = /* @__PURE__ */ new Map([["type", type]]);
+ const itemScoped = type === "response.output_item.added" || type === "response.output_item.done" || type === "response.content_part.added" || type === "response.content_part.done" || type === "response.shell_call_command.added" || type === "response.shell_call_command.delta" || type === "response.shell_call_command.done" || hasOwn(expectedOutputItemTypes, type);
+ if (itemScoped) {
+ try {
+ for (const field of responseEventRoutingFields) {
+ const routingDescriptor = Object.getOwnPropertyDescriptor(event, field);
+ stableValues.set(field, routingDescriptor ? event[field] : void 0);
+ }
+ if (type === "response.output_item.done") {
+ stableValues.set("item", structuredClone(event.item));
+ } else if (type === "response.content_part.added" || type === "response.content_part.done") {
+ stableValues.set("part", structuredClone(event.part));
+ }
+ } catch {
+ return assertNever3(event);
+ }
+ }
+ return new Proxy(event, {
+ get(target, property) {
+ return stableValues.has(property) ? stableValues.get(property) : Reflect.get(target, property, target);
+ }
+ });
+}
+function accumulateOutputItemEvent(event, snapshot, context) {
+ switch (event.type) {
+ case "response.output_item.added": {
+ validateArrayAppend(snapshot.output, event.output_index, "output");
+ const identityIndex = getResponseOutputIdentityIndex(context, snapshot);
+ const output = structuredClone(event.item);
+ const identities = getOutputItemIdentityKeys(output, event.type);
+ assertOutputItemIdentitiesAvailable(identityIndex.identities, identities);
+ if (output.type === "message") {
+ ensureCanonicalOutputText(context, snapshot);
+ }
+ snapshot.output.push(output);
+ addOutputItemIdentities(identityIndex.identities, identities);
+ identityIndex.length = snapshot.output.length;
+ const text = getOutputText(context, output);
+ if (context.canonicalSnapshot === snapshot) {
+ context.outputTextIndex.append(text.length);
+ }
+ if (text) {
+ snapshot.output_text += text;
+ }
+ return true;
+ }
+ case "response.output_item.done": {
+ const output = getOutput(snapshot, event.output_index);
+ const previousText = getOutputText(context, output);
+ const replacement = event.item;
+ if (output.type === "message" || replacement.type === "message") {
+ ensureCanonicalOutputText(context, snapshot);
+ }
+ snapshot.output[event.output_index] = replacement;
+ const nextText = getOutputText(context, replacement);
+ if (context.canonicalSnapshot === snapshot) {
+ context.outputTextIndex.update(event.output_index, nextText.length);
+ }
+ updateOutputText(context, snapshot, event.output_index, previousText, nextText);
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateContentPartAddedEvent(event, snapshot, context) {
+ switch (event.type) {
+ case "response.content_part.added": {
+ const output = getOutput(snapshot, event.output_index);
+ const { type } = output;
+ const { part } = event;
+ if (type === "message" && part.type !== "reasoning_text") {
+ validateArrayAppend(output.content, event.content_index, "content");
+ const content = part;
+ if (content.type === "output_text") {
+ ensureCanonicalOutputText(context, snapshot);
+ }
+ output.content.push(content);
+ if (content.type === "output_text") {
+ updateCachedOutputTextLength(context, output, event.output_index, "", content.text);
+ updateOutputText(context, snapshot, event.output_index, "", content.text, event.content_index);
+ }
+ } else if (type === "reasoning" && part.type === "reasoning_text") {
+ const content = output.content ?? [];
+ validateArrayAppend(content, event.content_index, "content");
+ if (!output.content) {
+ output.content = content;
+ }
+ content.push(part);
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateContentPartDoneEvent(event, snapshot, context) {
+ switch (event.type) {
+ case "response.content_part.done": {
+ const output = getOutput(snapshot, event.output_index);
+ const { part } = event;
+ if (output.type === "message" && part.type !== "reasoning_text") {
+ const content = getContent(output.content, event.content_index);
+ const previousText = content.type === "output_text" ? content.text : "";
+ const replacement = part;
+ if (content.type === "output_text" || replacement.type === "output_text") {
+ ensureCanonicalOutputText(context, snapshot);
+ }
+ output.content[event.content_index] = replacement;
+ const nextText = replacement.type === "output_text" ? replacement.text : "";
+ updateCachedOutputTextLength(context, output, event.output_index, previousText, nextText);
+ updateOutputText(context, snapshot, event.output_index, previousText, nextText, event.content_index);
+ } else if (output.type === "reasoning" && part.type === "reasoning_text") {
+ const { content } = output;
+ if (!content) {
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
+ }
+ getContent(content, event.content_index);
+ content[event.content_index] = part;
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateOutputTextEvent(event, snapshot, context) {
+ switch (event.type) {
+ case "response.output_text.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "message") {
+ const content = getContent(output.content, event.content_index);
+ if (content.type !== "output_text") {
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
+ }
+ const previousText = content.text;
+ ensureCanonicalOutputText(context, snapshot);
+ content.text = previousText + event.delta;
+ updateCachedOutputTextLength(context, output, event.output_index, previousText, content.text);
+ if (event.output_index === snapshot.output.length - 1 && event.content_index === output.content.length - 1) {
+ snapshot.output_text += event.delta;
+ } else {
+ updateOutputText(context, snapshot, event.output_index, previousText, content.text, event.content_index);
+ }
+ }
+ return true;
+ }
+ case "response.output_text.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "message") {
+ const content = getContent(output.content, event.content_index);
+ if (content.type !== "output_text") {
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
+ }
+ const previousText = content.text;
+ ensureCanonicalOutputText(context, snapshot);
+ content.text = event.text;
+ updateCachedOutputTextLength(context, output, event.output_index, previousText, event.text);
+ updateOutputText(context, snapshot, event.output_index, previousText, event.text, event.content_index);
+ }
+ return true;
+ }
+ case "response.output_text.annotation.added": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "message") {
+ const content = getContent(output.content, event.content_index);
+ if (content.type !== "output_text") {
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
+ }
+ validateArrayIndex(content.annotations, event.annotation_index, "annotation", true);
+ content.annotations[event.annotation_index] = structuredClone(event.annotation);
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateRefusalAndArgumentsEvent(event, snapshot) {
+ switch (event.type) {
+ case "response.refusal.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "message") {
+ const content = getContent(output.content, event.content_index);
+ if (content.type !== "refusal") {
+ throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
+ }
+ content.refusal += event.delta;
+ }
+ return true;
+ }
+ case "response.refusal.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "message") {
+ const content = getContent(output.content, event.content_index);
+ if (content.type !== "refusal") {
+ throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
+ }
+ content.refusal = event.refusal;
+ }
+ return true;
+ }
+ case "response.function_call_arguments.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "function_call") {
+ output.arguments += event.delta;
+ }
+ return true;
+ }
+ case "response.function_call_arguments.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "function_call") {
+ output.arguments = event.arguments;
+ }
+ return true;
+ }
+ case "response.custom_tool_call_input.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "custom_tool_call") {
+ output.input += event.delta;
+ }
+ return true;
+ }
+ case "response.custom_tool_call_input.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "custom_tool_call") {
+ output.input = event.input;
+ }
+ return true;
+ }
+ case "response.mcp_call_arguments.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "mcp_call") {
+ output.arguments += event.delta;
+ }
+ return true;
+ }
+ case "response.mcp_call_arguments.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "mcp_call") {
+ output.arguments = event.arguments;
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateShellEvent(event, snapshot) {
+ switch (event.type) {
+ case "response.shell_call_command.added":
+ case "response.shell_call_command.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "shell_call") {
+ const allowAppend = event.type === "response.shell_call_command.added";
+ validateArrayIndex(output.action.commands, event.command_index, "command", allowAppend);
+ output.action.commands[event.command_index] = event.command;
+ }
+ return true;
+ }
+ case "response.shell_call_command.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "shell_call") {
+ validateArrayIndex(output.action.commands, event.command_index, "command");
+ output.action.commands[event.command_index] += event.delta;
+ }
+ return true;
+ }
+ case "response.shell_call_output_content.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "shell_call_output") {
+ const content = getShellOutputContent(snapshot, output, event.command_index);
+ content.stdout += event.delta.stdout ?? "";
+ content.stderr += event.delta.stderr ?? "";
+ }
+ return true;
+ }
+ case "response.shell_call_output_content.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "shell_call_output") {
+ const content = getContent(event.output, 0);
+ getShellOutputContent(snapshot, output, event.command_index);
+ output.output[event.command_index] = structuredClone(content);
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateReasoningEvent(event, snapshot) {
+ switch (event.type) {
+ case "response.reasoning_text.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "reasoning") {
+ if (!output.content) {
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
+ }
+ const content = getContent(output.content, event.content_index);
+ if (content.type !== "reasoning_text") {
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
+ }
+ content.text += event.delta;
+ }
+ return true;
+ }
+ case "response.reasoning_text.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "reasoning") {
+ if (!output.content) {
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
+ }
+ const content = getContent(output.content, event.content_index);
+ if (content.type !== "reasoning_text") {
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
+ }
+ content.text = event.text;
+ }
+ return true;
+ }
+ case "response.reasoning_summary_part.added": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "reasoning") {
+ validateArrayAppend(output.summary, event.summary_index, "content");
+ output.summary.push(structuredClone(event.part));
+ }
+ return true;
+ }
+ case "response.reasoning_summary_part.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "reasoning") {
+ getContent(output.summary, event.summary_index);
+ output.summary[event.summary_index] = structuredClone(event.part);
+ }
+ return true;
+ }
+ case "response.reasoning_summary_text.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "reasoning") {
+ const part = getContent(output.summary, event.summary_index);
+ part.text += event.delta;
+ }
+ return true;
+ }
+ case "response.reasoning_summary_text.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "reasoning") {
+ const part = getContent(output.summary, event.summary_index);
+ part.text = event.text;
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateCodeInterpreterEvent(event, snapshot) {
+ switch (event.type) {
+ case "response.code_interpreter_call_code.delta": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "code_interpreter_call") {
+ output.code = (output.code ?? "") + event.delta;
+ }
+ return true;
+ }
+ case "response.code_interpreter_call_code.done": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "code_interpreter_call") {
+ output.code = event.code;
+ }
+ return true;
+ }
+ case "response.code_interpreter_call.in_progress": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "code_interpreter_call") {
+ output.status = "in_progress";
+ }
+ return true;
+ }
+ case "response.code_interpreter_call.interpreting": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "code_interpreter_call") {
+ output.status = "interpreting";
+ }
+ return true;
+ }
+ case "response.code_interpreter_call.completed": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "code_interpreter_call") {
+ output.status = "completed";
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateSearchStatusEvent(event, snapshot) {
+ switch (event.type) {
+ case "response.file_search_call.in_progress": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "file_search_call") {
+ output.status = "in_progress";
+ }
+ return true;
+ }
+ case "response.file_search_call.searching": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "file_search_call") {
+ output.status = "searching";
+ }
+ return true;
+ }
+ case "response.file_search_call.completed": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "file_search_call") {
+ output.status = "completed";
+ }
+ return true;
+ }
+ case "response.web_search_call.in_progress": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "web_search_call") {
+ output.status = "in_progress";
+ }
+ return true;
+ }
+ case "response.web_search_call.searching": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "web_search_call") {
+ output.status = "searching";
+ }
+ return true;
+ }
+ case "response.web_search_call.completed": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "web_search_call") {
+ output.status = "completed";
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function accumulateImageAndMcpStatusEvent(event, snapshot) {
+ switch (event.type) {
+ case "response.image_generation_call.in_progress": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "image_generation_call") {
+ output.status = "in_progress";
+ }
+ return true;
+ }
+ case "response.image_generation_call.generating": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "image_generation_call") {
+ output.status = "generating";
+ }
+ return true;
+ }
+ case "response.image_generation_call.completed": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "image_generation_call") {
+ output.status = "completed";
+ }
+ return true;
+ }
+ case "response.mcp_call.in_progress": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "mcp_call") {
+ output.status = "in_progress";
+ }
+ return true;
+ }
+ case "response.mcp_call.completed": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "mcp_call") {
+ output.status = "completed";
+ }
+ return true;
+ }
+ case "response.mcp_call.failed": {
+ const output = getOutput(snapshot, event.output_index);
+ if (output.type === "mcp_call") {
+ output.status = "failed";
+ }
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function isResponseLifecycleEvent(event) {
+ switch (event.type) {
+ case "response.created":
+ case "response.queued":
+ case "response.in_progress":
+ case "response.completed":
+ case "response.failed":
+ case "response.incomplete": {
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function isIgnoredResponseEvent(event) {
+ switch (event.type) {
+ case "response.audio.delta":
+ case "response.audio.done":
+ case "response.audio.transcript.delta":
+ case "response.audio.transcript.done":
+ case "response.compaction.compacting":
+ case "response.image_generation_call.partial_image":
+ case "response.mcp_list_tools.in_progress":
+ case "response.mcp_list_tools.completed":
+ case "response.mcp_list_tools.failed":
+ case "keepalive":
+ case "error": {
+ return true;
+ }
+ default: {
+ return false;
+ }
+ }
+}
+function createResponseContext() {
+ return createCanonicalResponseContext();
+}
+function accumulateResponseWithContext(event, snapshot, context, rejectInvalidShellTargets = false, onSanitizedEvent) {
+ const dispatchEvent = sanitizeResponseEvent(event);
+ if (onSanitizedEvent && dispatchEvent.type !== "keepalive") {
+ onSanitizedEvent(dispatchEvent);
+ }
+ if (!snapshot) {
+ if (dispatchEvent.type !== "response.created") {
+ throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${dispatchEvent.type}`);
+ }
+ return cloneValidatedResponse(context, dispatchEvent.response);
+ }
+ validateOutputItemIdentity(dispatchEvent, snapshot, rejectInvalidShellTargets);
+ if (accumulateOutputItemEvent(dispatchEvent, snapshot, context)) {
+ return snapshot;
+ }
+ if (accumulateContentPartAddedEvent(dispatchEvent, snapshot, context)) {
+ return snapshot;
+ }
+ if (accumulateContentPartDoneEvent(dispatchEvent, snapshot, context)) {
+ return snapshot;
+ }
+ if (accumulateOutputTextEvent(dispatchEvent, snapshot, context)) {
+ return snapshot;
+ }
+ if (accumulateRefusalAndArgumentsEvent(dispatchEvent, snapshot)) {
+ return snapshot;
+ }
+ if (accumulateShellEvent(dispatchEvent, snapshot)) {
+ return snapshot;
+ }
+ if (accumulateReasoningEvent(dispatchEvent, snapshot)) {
+ return snapshot;
+ }
+ if (accumulateCodeInterpreterEvent(dispatchEvent, snapshot)) {
+ return snapshot;
+ }
+ if (accumulateSearchStatusEvent(dispatchEvent, snapshot)) {
+ return snapshot;
+ }
+ if (accumulateImageAndMcpStatusEvent(dispatchEvent, snapshot)) {
+ return snapshot;
+ }
+ if (isResponseLifecycleEvent(dispatchEvent)) {
+ return cloneValidatedResponse(context, dispatchEvent.response);
+ }
+ if (isIgnoredResponseEvent(dispatchEvent)) {
+ return snapshot;
+ }
+ return assertNever3(dispatchEvent);
+}
+var responseOutputIdentityIndexes, expectedOutputItemTypes, supportedResponseEventTypes, responseEventRoutingFields;
+var init_response_accumulator = __esm({
+ "node_modules/openai/internal/responses/response-accumulator.mjs"() {
+ init_error2();
+ init_utils2();
+ init_canonical_output_text();
+ responseOutputIdentityIndexes = /* @__PURE__ */ new WeakMap();
+ expectedOutputItemTypes = {
+ "response.output_text.delta": "message",
+ "response.output_text.done": "message",
+ "response.output_text.annotation.added": "message",
+ "response.refusal.delta": "message",
+ "response.refusal.done": "message",
+ "response.function_call_arguments.delta": "function_call",
+ "response.function_call_arguments.done": "function_call",
+ "response.custom_tool_call_input.delta": "custom_tool_call",
+ "response.custom_tool_call_input.done": "custom_tool_call",
+ "response.mcp_call_arguments.delta": "mcp_call",
+ "response.mcp_call_arguments.done": "mcp_call",
+ "response.mcp_call.in_progress": "mcp_call",
+ "response.mcp_call.completed": "mcp_call",
+ "response.mcp_call.failed": "mcp_call",
+ "response.shell_call_output_content.delta": "shell_call_output",
+ "response.shell_call_output_content.done": "shell_call_output",
+ "response.reasoning_text.delta": "reasoning",
+ "response.reasoning_text.done": "reasoning",
+ "response.reasoning_summary_part.added": "reasoning",
+ "response.reasoning_summary_part.done": "reasoning",
+ "response.reasoning_summary_text.delta": "reasoning",
+ "response.reasoning_summary_text.done": "reasoning",
+ "response.code_interpreter_call_code.delta": "code_interpreter_call",
+ "response.code_interpreter_call_code.done": "code_interpreter_call",
+ "response.code_interpreter_call.in_progress": "code_interpreter_call",
+ "response.code_interpreter_call.interpreting": "code_interpreter_call",
+ "response.code_interpreter_call.completed": "code_interpreter_call",
+ "response.file_search_call.in_progress": "file_search_call",
+ "response.file_search_call.searching": "file_search_call",
+ "response.file_search_call.completed": "file_search_call",
+ "response.web_search_call.in_progress": "web_search_call",
+ "response.web_search_call.searching": "web_search_call",
+ "response.web_search_call.completed": "web_search_call",
+ "response.image_generation_call.in_progress": "image_generation_call",
+ "response.image_generation_call.generating": "image_generation_call",
+ "response.image_generation_call.completed": "image_generation_call",
+ "response.image_generation_call.partial_image": "image_generation_call",
+ "response.mcp_list_tools.in_progress": "mcp_list_tools",
+ "response.mcp_list_tools.completed": "mcp_list_tools",
+ "response.mcp_list_tools.failed": "mcp_list_tools",
+ "response.compaction.compacting": "compaction"
+ };
+ supportedResponseEventTypes = createSupportedResponseEventTypes([
+ "response.output_item.added",
+ "response.output_item.done",
+ "response.content_part.added",
+ "response.content_part.done",
+ "response.output_text.delta",
+ "response.output_text.done",
+ "response.output_text.annotation.added",
+ "response.refusal.delta",
+ "response.refusal.done",
+ "response.function_call_arguments.delta",
+ "response.function_call_arguments.done",
+ "response.custom_tool_call_input.delta",
+ "response.custom_tool_call_input.done",
+ "response.mcp_call_arguments.delta",
+ "response.mcp_call_arguments.done",
+ "response.shell_call_command.added",
+ "response.shell_call_command.done",
+ "response.shell_call_command.delta",
+ "response.shell_call_output_content.delta",
+ "response.shell_call_output_content.done",
+ "response.reasoning_text.delta",
+ "response.reasoning_text.done",
+ "response.reasoning_summary_part.added",
+ "response.reasoning_summary_part.done",
+ "response.reasoning_summary_text.delta",
+ "response.reasoning_summary_text.done",
+ "response.code_interpreter_call_code.delta",
+ "response.code_interpreter_call_code.done",
+ "response.code_interpreter_call.in_progress",
+ "response.code_interpreter_call.interpreting",
+ "response.code_interpreter_call.completed",
+ "response.file_search_call.in_progress",
+ "response.file_search_call.searching",
+ "response.file_search_call.completed",
+ "response.web_search_call.in_progress",
+ "response.web_search_call.searching",
+ "response.web_search_call.completed",
+ "response.image_generation_call.in_progress",
+ "response.image_generation_call.generating",
+ "response.image_generation_call.completed",
+ "response.mcp_call.in_progress",
+ "response.mcp_call.completed",
+ "response.mcp_call.failed",
+ "response.created",
+ "response.queued",
+ "response.in_progress",
+ "response.completed",
+ "response.failed",
+ "response.incomplete",
+ "response.audio.delta",
+ "response.audio.done",
+ "response.audio.transcript.delta",
+ "response.audio.transcript.done",
+ "response.compaction.compacting",
+ "response.image_generation_call.partial_image",
+ "response.mcp_list_tools.in_progress",
+ "response.mcp_list_tools.completed",
+ "response.mcp_list_tools.failed",
+ "keepalive",
+ "error"
+ ]);
+ responseEventRoutingFields = [
+ "item_id",
+ "output_index",
+ "content_index",
+ "annotation_index",
+ "command_index",
+ "summary_index"
+ ];
+ }
+});
+
+// node_modules/openai/lib/responses/ResponseStream.mjs
+function finalizeResponse(snapshot, params) {
+ return maybeParseResponse(snapshot, params);
+}
+var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_accumulatorContext, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, ResponseStream;
+var init_ResponseStream = __esm({
+ "node_modules/openai/lib/responses/ResponseStream.mjs"() {
+ init_tslib();
+ init_error2();
+ init_EventStream();
+ init_response_accumulator();
+ init_ResponsesParser();
+ init_streaming2();
+ ResponseStream = class _ResponseStream extends EventStream2 {
+ /** Creates an unstarted stream, retaining request parameters for structured-output parsing. */
+ constructor(params) {
+ super();
+ _ResponseStream_instances.add(this);
+ _ResponseStream_params.set(this, void 0);
+ _ResponseStream_currentResponseSnapshot.set(this, void 0);
+ _ResponseStream_finalResponse.set(this, void 0);
+ _ResponseStream_accumulatorContext.set(this, createResponseContext());
+ __classPrivateFieldSet(this, _ResponseStream_params, params, "f");
+ }
+ /** Starts a new response stream or replays an existing response by its identifier. */
+ static createResponse(client, params, options) {
+ const runner = new _ResponseStream(params);
+ runner._run(() => runner._createOrRetrieveResponse(client, params, {
+ ...options,
+ __metadata: { ...options?.__metadata, helperMethod: "stream" }
+ }));
+ return runner;
+ }
+ /** Consumes serialized response events from a readable stream in another runtime. */
+ static fromReadableStream(stream3) {
+ const runner = new _ResponseStream(null);
+ runner._run(() => runner._fromReadableStream(stream3));
+ return runner;
+ }
+ async _createOrRetrieveResponse(client, params, options) {
+ this._listenForAbort(options?.signal);
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
+ let stream3;
+ let starting_after = null;
+ if ("response_id" in params) {
+ stream3 = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true });
+ starting_after = params.starting_after ?? null;
+ } else {
+ stream3 = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
+ }
+ this._connected();
+ for await (const event of stream3) {
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after);
+ }
+ if (stream3.controller.signal?.aborted) {
+ throw this._userAbortError();
+ }
+ return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
+ }
+ async _fromReadableStream(readableStream, options) {
+ this._listenForAbort(options?.signal);
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
+ this._connected();
+ const stream3 = Stream.fromReadableStream(readableStream, this.controller);
+ for await (const event of stream3) {
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, null);
+ }
+ if (stream3.controller.signal?.aborted) {
+ throw this._userAbortError();
+ }
+ return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
+ }
+ /** Iterates over response events; stopping iteration early aborts the underlying request. */
+ [(_ResponseStream_params = /* @__PURE__ */ new WeakMap(), _ResponseStream_currentResponseSnapshot = /* @__PURE__ */ new WeakMap(), _ResponseStream_finalResponse = /* @__PURE__ */ new WeakMap(), _ResponseStream_accumulatorContext = /* @__PURE__ */ new WeakMap(), _ResponseStream_instances = /* @__PURE__ */ new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest2() {
+ if (this.ended) {
+ return;
+ }
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
+ __classPrivateFieldSet(this, _ResponseStream_accumulatorContext, createResponseContext(), "f");
+ }, _ResponseStream_addEvent = function _ResponseStream_addEvent2(event, starting_after) {
+ if (this.ended) {
+ return;
+ }
+ const maybeEmit = (name, event2) => {
+ if (starting_after == null || event2.sequence_number > starting_after) {
+ this._emit(name, event2);
+ }
+ };
+ if (event.type === "error") {
+ const error = (
+ // oxlint-disable-next-line anti-slop/no-runtime-typeof -- An error event can contain malformed server data; validate its container before extracting error details.
+ "error" in event && typeof event.error === "object" && event.error !== null ? event.error : event
+ );
+ throw new APIError(void 0, error, event.message, void 0);
+ }
+ let dispatchEvent = event;
+ const response = accumulateResponseWithContext(event, __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"), __classPrivateFieldGet(this, _ResponseStream_accumulatorContext, "f"), true, (sanitizedEvent) => {
+ dispatchEvent = sanitizedEvent;
+ });
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, response, "f");
+ maybeEmit("event", event);
+ switch (dispatchEvent.type) {
+ case "response.output_text.delta": {
+ const output = response.output[dispatchEvent.output_index];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${dispatchEvent.output_index}`);
+ }
+ if (output.type === "message") {
+ const content = output.content[dispatchEvent.content_index];
+ if (!content) {
+ throw new OpenAIError(`missing content at index ${dispatchEvent.content_index}`);
+ }
+ if (content.type !== "output_text") {
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
+ }
+ maybeEmit("response.output_text.delta", {
+ ...dispatchEvent,
+ type: dispatchEvent.type,
+ item_id: dispatchEvent.item_id,
+ output_index: dispatchEvent.output_index,
+ content_index: dispatchEvent.content_index,
+ snapshot: content.text
+ });
+ }
+ break;
+ }
+ case "response.function_call_arguments.delta": {
+ const output = response.output[dispatchEvent.output_index];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${dispatchEvent.output_index}`);
+ }
+ if (output.type === "function_call") {
+ maybeEmit("response.function_call_arguments.delta", {
+ ...dispatchEvent,
+ type: dispatchEvent.type,
+ item_id: dispatchEvent.item_id,
+ output_index: dispatchEvent.output_index,
+ snapshot: output.arguments
+ });
+ }
+ break;
+ }
+ default: {
+ maybeEmit(dispatchEvent.type, event);
+ break;
+ }
+ }
+ }, _ResponseStream_endRequest = function _ResponseStream_endRequest2() {
+ if (this.ended) {
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
+ }
+ const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
+ if (!snapshot) {
+ throw new OpenAIError(`request ended without sending any events`);
+ }
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
+ __classPrivateFieldSet(this, _ResponseStream_accumulatorContext, createResponseContext(), "f");
+ const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f"));
+ __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
+ return parsedResponse;
+ }, Symbol.asyncIterator)]() {
+ return this._createIterator((push) => {
+ const onEvent = (event) => push(event);
+ this.on("event", onEvent);
+ return () => this.off("event", onEvent);
+ }, { onReturn: () => this.abort() });
+ }
+ /**
+ * Waits for the stream to end and returns its latest accumulated response.
+ *
+ * A clean end after at least one response event resolves even when the response is
+ * incomplete. Network errors, cancellation, and streams without a response reject.
+ */
+ async finalResponse() {
+ await this.done();
+ const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f");
+ if (!response) {
+ throw new OpenAIError("stream ended without producing a Response");
+ }
+ return response;
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/responses/input-items.mjs
+var InputItems2;
+var init_input_items2 = __esm({
+ "node_modules/openai/resources/responses/input-items.mjs"() {
+ init_resource();
+ init_pagination();
+ init_path();
+ InputItems2 = class extends APIResource {
+ /**
+ * Returns a list of input items for a given response.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const responseItem of client.responses.inputItems.list(
+ * 'response_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(responseID, query = {}, options) {
+ return this._client.getAPIList(path`/responses/${responseID}/input_items`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/responses/input-tokens.mjs
+var InputTokens2;
+var init_input_tokens2 = __esm({
+ "node_modules/openai/resources/responses/input-tokens.mjs"() {
+ init_resource();
+ InputTokens2 = class extends APIResource {
+ /**
+ * Returns input token counts of the request.
+ *
+ * Returns an object with `object` set to `response.input_tokens` and an
+ * `input_tokens` count.
+ *
+ * @example
+ * ```ts
+ * const response = await client.responses.inputTokens.count();
+ * ```
+ */
+ count(body = {}, options) {
+ return this._client.post("/responses/input_tokens", {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/responses/responses.mjs
+var Responses2;
+var init_responses2 = __esm({
+ "node_modules/openai/resources/responses/responses.mjs"() {
+ init_ResponsesParser();
+ init_ResponseStream();
+ init_resource();
+ init_input_items2();
+ init_input_items2();
+ init_input_tokens2();
+ init_input_tokens2();
+ init_headers();
+ init_path();
+ Responses2 = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.inputItems = new InputItems2(this._client);
+ this.inputTokens = new InputTokens2(this._client);
+ }
+ create(body, options) {
+ return this._client.post("/responses", {
+ body,
+ ...options,
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ })._thenUnwrap((rsp) => {
+ if ("object" in rsp && rsp.object === "response") {
+ addOutputText(rsp);
+ }
+ return rsp;
+ });
+ }
+ retrieve(responseID, query = {}, options) {
+ return this._client.get(path`/responses/${responseID}`, {
+ query,
+ ...options,
+ stream: query?.stream ?? false,
+ __security: { bearerAuth: true }
+ })._thenUnwrap((rsp) => {
+ if ("object" in rsp && rsp.object === "response") {
+ addOutputText(rsp);
+ }
+ return rsp;
+ });
+ }
+ /**
+ * Deletes a model response with the given ID.
+ *
+ * @example
+ * ```ts
+ * await client.responses.delete(
+ * 'resp_677efb5139a88190b512bc3fef8e535d',
+ * );
+ * ```
+ */
+ delete(responseID, options) {
+ return this._client.delete(path`/responses/${responseID}`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ parse(body, options) {
+ return this._client.responses.create(body, options)._thenUnwrap((response) => parseResponse(response, body));
+ }
+ /**
+ * Creates a model response stream
+ */
+ stream(body, options) {
+ return ResponseStream.createResponse(this._client, body, options);
+ }
+ /**
+ * Cancels a model response with the given ID. Only responses created with the
+ * `background` parameter set to `true` can be cancelled.
+ * [Learn more](https://developers.openai.com/api/docs/guides/background).
+ *
+ * @example
+ * ```ts
+ * const response = await client.responses.cancel(
+ * 'resp_677efb5139a88190b512bc3fef8e535d',
+ * );
+ * ```
+ */
+ cancel(responseID, options) {
+ return this._client.post(path`/responses/${responseID}/cancel`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Compact a conversation. Returns a compacted response object.
+ *
+ * Learn when and how to compact long-running conversations in the
+ * [conversation state guide](https://developers.openai.com/api/docs/guides/conversation-state#managing-the-context-window).
+ * For ZDR-compatible compaction details, see
+ * [Compaction (advanced)](https://developers.openai.com/api/docs/guides/conversation-state#compaction-advanced).
+ *
+ * @example
+ * ```ts
+ * const compactedResponse = await client.responses.compact({
+ * model: 'gpt-6-astra',
+ * });
+ * ```
+ */
+ compact(body, options) {
+ return this._client.post("/responses/compact", { body, ...options, __security: { bearerAuth: true } });
+ }
+ };
+ Responses2.InputItems = InputItems2;
+ Responses2.InputTokens = InputTokens2;
+ }
+});
+
+// node_modules/openai/resources/safety/alerts.mjs
+var Alerts;
+var init_alerts = __esm({
+ "node_modules/openai/resources/safety/alerts.mjs"() {
+ init_resource();
+ init_path();
+ Alerts = class extends APIResource {
+ /**
+ * Get a safety alert belonging to the authenticated API project.
+ */
+ retrieve(id, options) {
+ return this._client.get(path`/safety/alerts/${id}`, { ...options, __security: { bearerAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/safety/safety.mjs
+var Safety;
+var init_safety = __esm({
+ "node_modules/openai/resources/safety/safety.mjs"() {
+ init_resource();
+ init_alerts();
+ init_alerts();
+ Safety = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.alerts = new Alerts(this._client);
+ }
+ };
+ Safety.Alerts = Alerts;
+ }
+});
+
+// node_modules/openai/resources/skills/content.mjs
+var Content2;
+var init_content2 = __esm({
+ "node_modules/openai/resources/skills/content.mjs"() {
+ init_resource();
+ init_headers();
+ init_path();
+ Content2 = class extends APIResource {
+ /**
+ * Download a skill zip bundle by its ID.
+ */
+ retrieve(skillID, options) {
+ return this._client.get(path`/skills/${skillID}/content`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/skills/versions/content.mjs
+var Content3;
+var init_content3 = __esm({
+ "node_modules/openai/resources/skills/versions/content.mjs"() {
+ init_resource();
+ init_headers();
+ init_path();
+ Content3 = class extends APIResource {
+ /**
+ * Download a skill version zip bundle.
+ */
+ retrieve(version, params, options) {
+ const { skill_id } = params;
+ return this._client.get(path`/skills/${skill_id}/versions/${version}/content`, {
+ ...options,
+ headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/skills/versions/versions.mjs
+var Versions;
+var init_versions = __esm({
+ "node_modules/openai/resources/skills/versions/versions.mjs"() {
+ init_resource();
+ init_content3();
+ init_content3();
+ init_pagination();
+ init_uploads();
+ init_path();
+ Versions = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.content = new Content3(this._client);
+ }
+ /**
+ * Create a new immutable skill version.
+ */
+ create(skillID, body = {}, options) {
+ return this._client.post(path`/skills/${skillID}/versions`, maybeMultipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client, {
+ stripFilenames: false
+ }));
+ }
+ /**
+ * Get a specific skill version.
+ */
+ retrieve(version, params, options) {
+ const { skill_id } = params;
+ return this._client.get(path`/skills/${skill_id}/versions/${version}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List skill versions for a skill.
+ */
+ list(skillID, query = {}, options) {
+ return this._client.getAPIList(path`/skills/${skillID}/versions`, CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a skill version.
+ */
+ delete(version, params, options) {
+ const { skill_id } = params;
+ return this._client.delete(path`/skills/${skill_id}/versions/${version}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Versions.Content = Content3;
+ }
+});
+
+// node_modules/openai/resources/skills/skills.mjs
+var Skills;
+var init_skills = __esm({
+ "node_modules/openai/resources/skills/skills.mjs"() {
+ init_resource();
+ init_content2();
+ init_content2();
+ init_versions();
+ init_versions();
+ init_pagination();
+ init_uploads();
+ init_path();
+ Skills = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.content = new Content2(this._client);
+ this.versions = new Versions(this._client);
+ }
+ /**
+ * Create a new skill.
+ */
+ create(body = {}, options) {
+ return this._client.post("/skills", maybeMultipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client, {
+ stripFilenames: false
+ }));
+ }
+ /**
+ * Get a skill by its ID.
+ */
+ retrieve(skillID, options) {
+ return this._client.get(path`/skills/${skillID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Update the default version pointer for a skill.
+ */
+ update(skillID, body, options) {
+ return this._client.post(path`/skills/${skillID}`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List all skills for the current project.
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/skills", CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a skill by its ID.
+ */
+ delete(skillID, options) {
+ return this._client.delete(path`/skills/${skillID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ };
+ Skills.Content = Content2;
+ Skills.Versions = Versions;
+ }
+});
+
+// node_modules/openai/resources/uploads/parts.mjs
+var Parts;
+var init_parts = __esm({
+ "node_modules/openai/resources/uploads/parts.mjs"() {
+ init_resource();
+ init_uploads();
+ init_path();
+ Parts = class extends APIResource {
+ /**
+ * Adds a
+ * [Part](https://developers.openai.com/api/reference/resources/uploads/subresources/parts)
+ * to an [Upload](https://developers.openai.com/api/reference/resources/uploads)
+ * object. A Part represents a chunk of bytes from the file you are trying to
+ * upload.
+ *
+ * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
+ * maximum of 8 GB.
+ *
+ * It is possible to add multiple Parts in parallel. You can decide the intended
+ * order of the Parts when you
+ * [complete the Upload](https://developers.openai.com/api/reference/resources/uploads/methods/complete).
+ */
+ create(uploadID, body, options) {
+ return this._client.post(path`/uploads/${uploadID}/parts`, multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/uploads/uploads.mjs
+var Uploads;
+var init_uploads3 = __esm({
+ "node_modules/openai/resources/uploads/uploads.mjs"() {
+ init_resource();
+ init_parts();
+ init_parts();
+ init_path();
+ Uploads = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.parts = new Parts(this._client);
+ }
+ /**
+ * Creates an intermediate
+ * [Upload](https://developers.openai.com/api/reference/resources/uploads) object
+ * that you can add
+ * [Parts](https://developers.openai.com/api/reference/resources/uploads/subresources/parts)
+ * to. Currently, an Upload can accept at most 8 GB in total and expires after an
+ * hour after you create it.
+ *
+ * Once you complete the Upload, we will create a
+ * [File](https://developers.openai.com/api/reference/resources/files) object that
+ * contains all the parts you uploaded. This File is usable in the rest of our
+ * platform as a regular File object.
+ *
+ * For certain `purpose` values, the correct `mime_type` must be specified. Please
+ * refer to documentation for the
+ * [supported MIME types for your use case](https://developers.openai.com/api/docs/guides/tools-file-search#supported-files).
+ *
+ * For guidance on the proper filename extensions for each purpose, please follow
+ * the documentation on
+ * [creating a File](https://developers.openai.com/api/reference/resources/files/methods/create).
+ *
+ * Returns the Upload object with status `pending`.
+ */
+ create(body, options) {
+ return this._client.post("/uploads", { body, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Cancels the Upload. No Parts may be added after an Upload is cancelled.
+ *
+ * Returns the Upload object with status `cancelled`.
+ */
+ cancel(uploadID, options) {
+ return this._client.post(path`/uploads/${uploadID}/cancel`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Completes the
+ * [Upload](https://developers.openai.com/api/reference/resources/uploads).
+ *
+ * Within the returned Upload object, there is a nested
+ * [File](https://developers.openai.com/api/reference/resources/files) object that
+ * is ready to use in the rest of the platform.
+ *
+ * You can specify the order of the Parts by passing in an ordered list of the Part
+ * IDs.
+ *
+ * The number of bytes uploaded upon completion must match the number of bytes
+ * initially specified when creating the Upload object. No Parts may be added after
+ * an Upload is completed. Returns the Upload object with status `completed`,
+ * including an additional `file` property containing the created usable File
+ * object.
+ */
+ complete(uploadID, body, options) {
+ return this._client.post(path`/uploads/${uploadID}/complete`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ Uploads.Parts = Parts;
+ }
+});
+
+// node_modules/openai/lib/vector-store-polling.mjs
+function pollVectorStoreFile(resource, vectorStoreID, fileID, options) {
+ return pollWithResponse((headers) => resource.retrieve(fileID, { vector_store_id: vectorStoreID }, { ...options, headers }), ["in_progress"], ["failed", "cancelled", "completed"], options);
+}
+function pollVectorStoreFileBatch(resource, vectorStoreID, batchID, options) {
+ return pollWithResponse((headers) => resource.retrieve(batchID, { vector_store_id: vectorStoreID }, { ...options, headers }), ["in_progress"], ["failed", "cancelled", "completed"], options);
+}
+var init_vector_store_polling = __esm({
+ "node_modules/openai/lib/vector-store-polling.mjs"() {
+ init_polling();
+ }
+});
+
+// node_modules/openai/lib/Util.mjs
+var allSettledWithThrow;
+var init_Util = __esm({
+ "node_modules/openai/lib/Util.mjs"() {
+ allSettledWithThrow = async (promises) => {
+ const results = await Promise.allSettled(promises);
+ const rejected = results.filter((result) => result.status === "rejected");
+ if (rejected.length) {
+ throw Object.defineProperty(new Error(`${rejected.length} promise(s) failed`), "rejections", {
+ configurable: true,
+ value: rejected.map(({ reason }) => reason),
+ writable: true
+ });
+ }
+ const values = [];
+ for (const result of results) {
+ if (result.status === "fulfilled") {
+ values.push(result.value);
+ }
+ }
+ return values;
+ };
+ }
+});
+
+// node_modules/openai/lib/vector-store-upload.mjs
+async function uploadAndPollVectorStoreFileBatch(resource, client, vectorStoreId, files, fileIds, options) {
+ if (files === null || files === void 0 || files.length === 0) {
+ throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");
+ }
+ const configuredConcurrency = options?.maxConcurrency ?? 5;
+ const concurrencyLimit = Math.min(configuredConcurrency, files.length);
+ if (concurrencyLimit === 0) {
+ throw new RangeError("maxConcurrency must be greater than 0");
+ }
+ const fileIterator = files.values();
+ const allFileIds = [...fileIds];
+ async function processFiles(iterator) {
+ for (const item of iterator) {
+ const fileObj = await client.files.create({ file: item, purpose: "assistants" }, options);
+ allFileIds.push(fileObj.id);
+ }
+ }
+ const workers = [];
+ workers.length = concurrencyLimit;
+ for (let index3 = 0; index3 < workers.length; index3 += 1) {
+ workers[index3] = processFiles(fileIterator);
+ }
+ await allSettledWithThrow(workers);
+ return await resource.createAndPoll(vectorStoreId, { file_ids: allFileIds }, options);
+}
+var init_vector_store_upload = __esm({
+ "node_modules/openai/lib/vector-store-upload.mjs"() {
+ init_Util();
+ }
+});
+
+// node_modules/openai/resources/vector-stores/file-batches.mjs
+var FileBatches;
+var init_file_batches = __esm({
+ "node_modules/openai/resources/vector-stores/file-batches.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_vector_store_polling();
+ init_vector_store_upload();
+ init_path();
+ FileBatches = class extends APIResource {
+ /**
+ * Create a vector store file batch.
+ */
+ create(vectorStoreID, body, options) {
+ return this._client.post(path`/vector_stores/${vectorStoreID}/file_batches`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a vector store file batch.
+ */
+ retrieve(batchID, params, options) {
+ const { vector_store_id } = params;
+ return this._client.get(path`/vector_stores/${vector_store_id}/file_batches/${batchID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancel a vector store file batch. This attempts to cancel the processing of
+ * files in this batch as soon as possible.
+ */
+ cancel(batchID, params, options) {
+ const { vector_store_id } = params;
+ return this._client.post(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Create a vector store batch and poll until all files have been processed.
+ */
+ async createAndPoll(vectorStoreId, body, options) {
+ const batch = await this.create(vectorStoreId, body, options);
+ return await this.poll(vectorStoreId, batch.id, options);
+ }
+ /**
+ * Returns a list of vector store files in a batch.
+ */
+ listFiles(batchID, params, options) {
+ const { vector_store_id, ...query } = params;
+ return this._client.getAPIList(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Wait for the given file batch to be processed.
+ *
+ * Note: this will return even if one of the files failed to process, you need to
+ * check batch.file_counts.failed_count to handle this case.
+ */
+ async poll(vectorStoreID, batchID, options) {
+ return await pollVectorStoreFileBatch(this, vectorStoreID, batchID, options);
+ }
+ /**
+ * Uploads the given files concurrently and then creates a vector store file batch.
+ *
+ * The concurrency limit is configurable using the `maxConcurrency` parameter.
+ */
+ async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
+ return await uploadAndPollVectorStoreFileBatch(this, this._client, vectorStoreId, files, fileIds, options);
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/vector-stores/files.mjs
+var Files4;
+var init_files4 = __esm({
+ "node_modules/openai/resources/vector-stores/files.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_vector_store_polling();
+ init_path();
+ Files4 = class extends APIResource {
+ /**
+ * Create a vector store file by attaching a
+ * [File](https://developers.openai.com/api/reference/resources/files) to a
+ * [vector store](https://developers.openai.com/api/reference/resources/vector_stores).
+ */
+ create(vectorStoreID, body, options) {
+ return this._client.post(path`/vector_stores/${vectorStoreID}/files`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a vector store file.
+ */
+ retrieve(fileID, params, options) {
+ const { vector_store_id } = params;
+ return this._client.get(path`/vector_stores/${vector_store_id}/files/${fileID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Update attributes on a vector store file.
+ */
+ update(fileID, params, options) {
+ const { vector_store_id, ...body } = params;
+ return this._client.post(path`/vector_stores/${vector_store_id}/files/${fileID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of vector store files.
+ */
+ list(vectorStoreID, query = {}, options) {
+ return this._client.getAPIList(path`/vector_stores/${vectorStoreID}/files`, CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a vector store file. This will remove the file from the vector store but
+ * the file itself will not be deleted. To delete the file, use the
+ * [delete file](https://developers.openai.com/api/reference/resources/files/methods/delete)
+ * endpoint.
+ */
+ delete(fileID, params, options) {
+ const { vector_store_id } = params;
+ return this._client.delete(path`/vector_stores/${vector_store_id}/files/${fileID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Attach a file to the given vector store and wait for it to be processed.
+ */
+ async createAndPoll(vectorStoreId, body, options) {
+ const file = await this.create(vectorStoreId, body, options);
+ return await this.poll(vectorStoreId, file.id, options);
+ }
+ /**
+ * Wait for the vector store file to finish processing.
+ *
+ * Note: this will return even if the file failed to process, you need to check
+ * file.last_error and file.status to handle these cases
+ */
+ async poll(vectorStoreID, fileID, options) {
+ return await pollVectorStoreFile(this, vectorStoreID, fileID, options);
+ }
+ /**
+ * Upload a file to the `files` API and then attach it to the given vector store.
+ *
+ * Note the file will be asynchronously processed (you can use the alternative
+ * polling helper method to wait for processing to complete).
+ */
+ async upload(vectorStoreId, file, options) {
+ const fileInfo = await this._client.files.create({ file, purpose: "assistants" }, options);
+ return this.create(vectorStoreId, { file_id: fileInfo.id }, options);
+ }
+ /**
+ * Add a file to a vector store and poll until processing is complete.
+ */
+ async uploadAndPoll(vectorStoreId, file, options) {
+ const fileInfo = await this.upload(vectorStoreId, file, options);
+ return await this.poll(vectorStoreId, fileInfo.id, options);
+ }
+ /**
+ * Retrieve the parsed contents of a vector store file.
+ */
+ content(fileID, params, options) {
+ const { vector_store_id } = params;
+ return this._client.getAPIList(path`/vector_stores/${vector_store_id}/files/${fileID}/content`, Page, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/vector-stores/vector-stores.mjs
+var VectorStores;
+var init_vector_stores = __esm({
+ "node_modules/openai/resources/vector-stores/vector-stores.mjs"() {
+ init_resource();
+ init_file_batches();
+ init_file_batches();
+ init_files4();
+ init_files4();
+ init_pagination();
+ init_headers();
+ init_path();
+ VectorStores = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ this.files = new Files4(this._client);
+ this.fileBatches = new FileBatches(this._client);
+ }
+ /**
+ * Create a vector store.
+ */
+ create(body, options) {
+ return this._client.post("/vector_stores", {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a vector store.
+ */
+ retrieve(vectorStoreID, options) {
+ return this._client.get(path`/vector_stores/${vectorStoreID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies a vector store.
+ */
+ update(vectorStoreID, body, options) {
+ return this._client.post(path`/vector_stores/${vectorStoreID}`, {
+ body,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of vector stores.
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/vector_stores", CursorPage, {
+ query,
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a vector store.
+ */
+ delete(vectorStoreID, options) {
+ return this._client.delete(path`/vector_stores/${vectorStoreID}`, {
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Search a vector store for relevant chunks based on a query and file attributes
+ * filter.
+ */
+ search(vectorStoreID, body, options) {
+ return this._client.getAPIList(path`/vector_stores/${vectorStoreID}/search`, Page, {
+ body,
+ method: "post",
+ ...options,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ };
+ VectorStores.Files = Files4;
+ VectorStores.FileBatches = FileBatches;
+ }
+});
+
+// node_modules/openai/resources/videos.mjs
+var Videos;
+var init_videos = __esm({
+ "node_modules/openai/resources/videos.mjs"() {
+ init_resource();
+ init_pagination();
+ init_headers();
+ init_uploads();
+ init_path();
+ Videos = class extends APIResource {
+ /**
+ * Create a new video generation job from a prompt and optional reference assets.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ create(body, options) {
+ return this._client.post("/videos", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Fetch the latest metadata for a generated video.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ retrieve(videoID, options) {
+ return this._client.get(path`/videos/${videoID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * List recently generated videos for the current project.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/videos", ConversationCursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Permanently delete a completed or failed video and its stored assets.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ delete(videoID, options) {
+ return this._client.delete(path`/videos/${videoID}`, { ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Create a character from an uploaded video.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ createCharacter(body, options) {
+ return this._client.post("/videos/characters", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Download the generated video bytes or a derived preview asset.
+ *
+ * Streams the rendered video content for the specified video job.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ downloadContent(videoID, query = {}, options) {
+ return this._client.get(path`/videos/${videoID}/content`, {
+ query,
+ ...options,
+ headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ /**
+ * Create a new video generation job by editing a source video or existing
+ * generated video.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ edit(body, options) {
+ return this._client.post("/videos/edits", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Create an extension of a completed video.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ extend(body, options) {
+ return this._client.post("/videos/extensions", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Fetch a character.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ getCharacter(characterID, options) {
+ return this._client.get(path`/videos/characters/${characterID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Create a remix of a completed video using a refreshed prompt.
+ *
+ * @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
+ */
+ remix(videoID, body, options) {
+ return this._client.post(path`/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
+ }
+ };
+ }
+});
+
+// node_modules/openai/lib/webhook-signature.mjs
+function webhookSignatureRequiresSigning(signatureHeader) {
+ return signatureHeader.split(" ", MAX_DIRECT_WEBHOOK_VERIFICATIONS + 1).length > MAX_DIRECT_WEBHOOK_VERIFICATIONS;
+}
+function* signatureCandidates(signatureHeader) {
+ let start = 0;
+ while (start <= signatureHeader.length) {
+ const separator = signatureHeader.indexOf(" ", start);
+ const candidate = signatureHeader.slice(start, separator === -1 ? void 0 : separator);
+ yield candidate.startsWith("v1,") ? candidate.slice(3) : candidate;
+ if (separator === -1) {
+ break;
+ }
+ start = separator + 1;
+ }
+}
+function decodeSignature(signature) {
+ try {
+ const signatureBytes = fromBase64(signature);
+ return signatureBytes.byteLength === SHA256_SIGNATURE_LENGTH ? signatureBytes : void 0;
+ } catch {
+ return void 0;
+ }
+}
+function firstValidLengthSignature(signatureHeader) {
+ for (const signature of signatureCandidates(signatureHeader)) {
+ const signatureBytes = decodeSignature(signature);
+ if (signatureBytes) {
+ return signatureBytes;
+ }
+ }
+ return void 0;
+}
+function selectMatchingSignature(signatureHeader, expectedSignature, firstSignature) {
+ let matchingSignature = firstSignature;
+ for (const signature of signatureCandidates(signatureHeader)) {
+ const signatureBytes = decodeSignature(signature);
+ if (!signatureBytes) {
+ continue;
+ }
+ let difference = 0;
+ for (const [index3, byte] of signatureBytes.entries()) {
+ difference |= byte ^ (expectedSignature[index3] ?? 0);
+ }
+ if (difference === 0) {
+ matchingSignature = signatureBytes;
+ }
+ }
+ return matchingSignature;
+}
+async function verifyWebhookSignature(payload, signatureHeader, timestamp, webhookId, secret, tolerance) {
+ const timestampSeconds = Number.parseInt(timestamp, 10);
+ if (Number.isNaN(timestampSeconds)) {
+ throw new InvalidWebhookSignatureError("Invalid webhook timestamp format");
+ }
+ const nowSeconds = Math.floor(Date.now() / 1e3);
+ if (nowSeconds - timestampSeconds > tolerance) {
+ throw new InvalidWebhookSignatureError("Webhook timestamp is too old");
+ }
+ if (timestampSeconds > nowSeconds + tolerance) {
+ throw new InvalidWebhookSignatureError("Webhook timestamp is too new");
+ }
+ const useBoundedVerification = webhookSignatureRequiresSigning(signatureHeader);
+ const firstSignature = useBoundedVerification ? firstValidLengthSignature(signatureHeader) : void 0;
+ if (useBoundedVerification && !firstSignature) {
+ throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
+ }
+ const decodedSecret = Uint8Array.from(secret.startsWith("whsec_") ? fromBase64(secret.slice("whsec_".length)) : encodeUTF8(secret));
+ const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`;
+ const signedPayloadBytes = Uint8Array.from(encodeUTF8(signedPayload));
+ const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, useBoundedVerification ? ["sign", "verify"] : ["verify"]);
+ if (useBoundedVerification && firstSignature) {
+ const expectedSignature = new Uint8Array(await crypto.subtle.sign("HMAC", key, signedPayloadBytes));
+ const signatureToVerify = selectMatchingSignature(signatureHeader, expectedSignature, firstSignature);
+ try {
+ if (await crypto.subtle.verify("HMAC", key, Uint8Array.from(signatureToVerify), signedPayloadBytes)) {
+ return;
+ }
+ } catch {
+ }
+ throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
+ }
+ for (const signature of signatureCandidates(signatureHeader)) {
+ try {
+ const signatureBytes = Uint8Array.from(fromBase64(signature));
+ const isValid = await crypto.subtle.verify("HMAC", key, signatureBytes, signedPayloadBytes);
+ if (isValid) {
+ return;
+ }
+ } catch {
+ }
+ }
+ throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
+}
+var MAX_DIRECT_WEBHOOK_VERIFICATIONS, SHA256_SIGNATURE_LENGTH;
+var init_webhook_signature = __esm({
+ "node_modules/openai/lib/webhook-signature.mjs"() {
+ init_error2();
+ init_base64();
+ init_bytes();
+ MAX_DIRECT_WEBHOOK_VERIFICATIONS = 32;
+ SHA256_SIGNATURE_LENGTH = 32;
+ }
+});
+
+// node_modules/openai/resources/webhooks/event-types.mjs
+var EventTypes;
+var init_event_types = __esm({
+ "node_modules/openai/resources/webhooks/event-types.mjs"() {
+ init_resource();
+ EventTypes = class extends APIResource {
+ /**
+ * Returns webhook event types visible to the authenticated project.
+ *
+ * @example
+ * ```ts
+ * const webhookEventTypeList =
+ * await client.webhooks.eventTypes.list();
+ * ```
+ */
+ list(options) {
+ return this._client.get("/webhook_event_types", { ...options, __security: { bearerAuth: true } });
+ }
+ };
+ }
+});
+
+// node_modules/openai/resources/webhooks/webhooks.mjs
+var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader, Webhooks;
+var init_webhooks = __esm({
+ "node_modules/openai/resources/webhooks/webhooks.mjs"() {
+ init_tslib();
+ init_resource();
+ init_headers();
+ init_webhook_signature();
+ init_event_types();
+ init_event_types();
+ init_pagination();
+ init_path();
+ Webhooks = class extends APIResource {
+ constructor() {
+ super(...arguments);
+ _Webhooks_instances.add(this);
+ this.eventTypes = new EventTypes(this._client);
+ }
+ /**
+ * Creates a webhook endpoint for the authenticated project.
+ *
+ * @example
+ * ```ts
+ * const webhookEndpointWithSecret =
+ * await client.webhooks.create({
+ * event_types: ['batch.completed'],
+ * name: 'x',
+ * url: 'https://',
+ * });
+ * ```
+ */
+ create(body, options) {
+ return this._client.post("/webhook_endpoints", { body, ...options, __security: { bearerAuth: true } });
+ }
+ /**
+ * Retrieves a webhook endpoint for the authenticated project.
+ *
+ * @example
+ * ```ts
+ * const webhookEndpoint = await client.webhooks.retrieve(
+ * 'whe_123',
+ * );
+ * ```
+ */
+ retrieve(webhookEndpointID, options) {
+ return this._client.get(path`/webhook_endpoints/${webhookEndpointID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Updates a webhook endpoint for the authenticated project.
+ *
+ * @example
+ * ```ts
+ * const webhookEndpoint = await client.webhooks.update('whe_123');
+ * ```
+ */
+ update(webhookEndpointID, body = {}, options) {
+ return this._client.post(path`/webhook_endpoints/${webhookEndpointID}`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns webhook endpoints for the authenticated project in newest-first order.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const webhookEndpoint of client.webhooks.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options) {
+ return this._client.getAPIList("/webhook_endpoints", CursorPage, {
+ query,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes a webhook endpoint for the authenticated project.
+ *
+ * @example
+ * ```ts
+ * const deletedWebhookEndpoint = await client.webhooks.delete(
+ * 'whe_123',
+ * );
+ * ```
+ */
+ delete(webhookEndpointID, options) {
+ return this._client.delete(path`/webhook_endpoints/${webhookEndpointID}`, {
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Rotates the signing secret for a webhook endpoint in the authenticated project.
+ *
+ * @example
+ * ```ts
+ * const webhookEndpointWithSecret =
+ * await client.webhooks.rotateSecret('whe_123');
+ * ```
+ */
+ rotateSecret(webhookEndpointID, body = {}, options) {
+ return this._client.post(path`/webhook_endpoints/${webhookEndpointID}/rotate_secret`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Sends a sample event to a webhook endpoint for the authenticated project.
+ *
+ * @example
+ * ```ts
+ * const webhookEndpointTestResult =
+ * await client.webhooks.test('whe_123', {
+ * event_type: 'batch.completed',
+ * });
+ * ```
+ */
+ test(webhookEndpointID, body, options) {
+ return this._client.post(path`/webhook_endpoints/${webhookEndpointID}/test`, {
+ body,
+ ...options,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Validates that the given payload was sent by OpenAI and parses the payload.
+ */
+ async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
+ await this.verifySignature(payload, headers, secret, tolerance);
+ return JSON.parse(payload);
+ }
+ /**
+ * Validates whether or not the webhook payload was sent by OpenAI.
+ *
+ * An error will be raised if the webhook payload was not sent by OpenAI.
+ *
+ * @param payload - The webhook payload
+ * @param headers - The webhook headers
+ * @param secret - The webhook secret (optional, will use client secret if not provided)
+ * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes)
+ */
+ async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
+ if (typeof crypto === "undefined" || typeof crypto.subtle?.importKey !== "function" || typeof crypto.subtle.verify !== "function") {
+ throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
+ }
+ __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret);
+ const headersObj = buildHeaders([headers]).values;
+ const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature");
+ const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp");
+ const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id");
+ if (webhookSignatureRequiresSigning(signatureHeader) && typeof crypto.subtle.sign !== "function") {
+ throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
+ }
+ return await verifyWebhookSignature(payload, signatureHeader, timestamp, webhookId, secret, tolerance);
+ }
+ };
+ _Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret2(secret) {
+ if (typeof secret !== "string" || secret.length === 0) {
+ throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`);
+ }
+ }, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader2(headers, name) {
+ if (!headers) {
+ throw new Error(`Headers are required`);
+ }
+ const value = headers.get(name);
+ if (value === null || value === void 0) {
+ throw new Error(`Missing required header: ${name}`);
+ }
+ return value;
+ };
+ Webhooks.EventTypes = EventTypes;
+ }
+});
+
+// node_modules/openai/resources/index.mjs
+var init_resources = __esm({
+ "node_modules/openai/resources/index.mjs"() {
+ init_chat2();
+ init_shared();
+ init_admin();
+ init_audio();
+ init_batches();
+ init_beta();
+ init_completions3();
+ init_containers();
+ init_content_provenance_checks();
+ init_conversations();
+ init_embeddings2();
+ init_evals();
+ init_files3();
+ init_fine_tuning();
+ init_graders2();
+ init_images();
+ init_live();
+ init_models2();
+ init_moderations();
+ init_realtime2();
+ init_responses2();
+ init_safety();
+ init_skills();
+ init_uploads3();
+ init_vector_stores();
+ init_videos();
+ init_webhooks();
+ }
+});
+
+// node_modules/openai/internal/realtime-credentials.mjs
+async function resolveRealtimeAPIKey(client) {
+ let apiKey;
+ const isProvider = await client._callApiKey((resolved) => {
+ apiKey = resolved;
+ });
+ return { apiKey: apiKey === void 0 ? client.apiKey : apiKey, isProvider };
+}
+var init_realtime_credentials = __esm({
+ "node_modules/openai/internal/realtime-credentials.mjs"() {
+ }
+});
+
+// node_modules/openai/internal/provider.mjs
+function configureProvider(provider) {
+ const definition = providerDefinitions.get(provider);
+ if (!definition) {
+ throw new Error("Invalid provider. Providers must be created with createProvider().");
+ }
+ return definition.configure();
+}
+var providerDefinitionsKey, providerGlobal, existingProviderDefinitions, providerDefinitions;
+var init_provider = __esm({
+ "node_modules/openai/internal/provider.mjs"() {
+ providerDefinitionsKey = Symbol.for("openai.node.providerDefinitions.v1");
+ providerGlobal = globalThis;
+ existingProviderDefinitions = providerGlobal[providerDefinitionsKey];
+ providerDefinitions = existingProviderDefinitions ?? /* @__PURE__ */ new WeakMap();
+ if (!existingProviderDefinitions) {
+ Object.defineProperty(providerGlobal, providerDefinitionsKey, { value: providerDefinitions });
+ }
+ }
+});
+
+// node_modules/openai/client.mjs
+function isRunningInBrowserOrBrowserWorker() {
+ if (isRunningInBrowser())
+ return true;
+ const scope = globalThis;
+ return typeof scope.WorkerGlobalScope === "function" && scope instanceof scope.WorkerGlobalScope && typeof scope.WorkerNavigator === "function" && scope.navigator instanceof scope.WorkerNavigator && typeof scope.navigator?.userAgent === "string" && scope.navigator.userAgent !== "Cloudflare-Workers" && scope.process?.versions?.node === void 0 && scope.Deno === void 0 && scope.Bun === void 0 && scope.EdgeRuntime === void 0 && scope.WebSocketPair === void 0;
+}
+function createRequestController(callerSignal, originalSignal) {
+ const controller = new AbortController();
+ if (!callerSignal)
+ return controller;
+ const nativeAbortSignal = globalThis.AbortSignal;
+ if (typeof nativeAbortSignal?.any !== "function" || !(callerSignal instanceof nativeAbortSignal)) {
+ return controller;
+ }
+ try {
+ const signals = [controller.signal, callerSignal];
+ if (originalSignal && originalSignal !== callerSignal) {
+ signals.push(originalSignal);
+ }
+ const composed = nativeAbortSignal.any(signals);
+ Object.defineProperty(controller, "signal", { value: composed, configurable: true });
+ composedCallerSignals.set(controller, callerSignal);
+ } catch {
+ }
+ return controller;
+}
+function getConnectionErrorMessage(error) {
+ if (isUndiciDispatcherVersionMismatchError(error)) {
+ return `Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`;
+ }
+ return void 0;
+}
+function isUndiciDispatcherVersionMismatchError(error) {
+ let current = error;
+ for (let i = 0; i < 8 && current && typeof current === "object"; i++) {
+ const err2 = current;
+ if (err2.code === "UND_ERR_INVALID_ARG" && typeof err2.message === "string" && err2.message.includes("invalid onRequestStart method")) {
+ return true;
+ }
+ current = err2.cause;
+ }
+ return false;
+}
+var _OpenAI_instances, _a3, _OpenAI_encoder, _OpenAI_x509Authentication, _OpenAI_x509Credential, _OpenAI_x509Fetch, _OpenAI_explicitDataResidency, _OpenAI_responseAttempts, _OpenAI_baseURLOverridden, WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER, inheritedDataResidencySelection, OpenAI, composedCallerSignals;
+var init_client = __esm({
+ "node_modules/openai/client.mjs"() {
+ init_tslib();
+ init_uuid();
+ init_values();
+ init_sleep();
+ init_abort2();
+ init_errors();
+ init_parse();
+ init_detect_platform();
+ init_shims();
+ init_request_options();
+ init_query();
+ init_version();
+ init_data_residency();
+ init_error();
+ init_pagination();
+ init_workload_identity_auth();
+ init_x509_api_origin();
+ init_x509_workload_identity_auth();
+ init_x509_credential_options();
+ init_x509_transport_state();
+ init_error();
+ init_uploads2();
+ init_resources();
+ init_api_promise();
+ init_realtime_credentials();
+ init_batches();
+ init_completions3();
+ init_content_provenance_checks();
+ init_embeddings2();
+ init_files3();
+ init_images();
+ init_models2();
+ init_moderations();
+ init_videos();
+ init_admin();
+ init_audio();
+ init_beta();
+ init_chat();
+ init_containers();
+ init_conversations();
+ init_evals();
+ init_fine_tuning();
+ init_graders2();
+ init_live();
+ init_realtime2();
+ init_responses2();
+ init_safety();
+ init_skills();
+ init_uploads3();
+ init_vector_stores();
+ init_webhooks();
+ init_detect_platform();
+ init_headers();
+ init_provider();
+ init_env();
+ init_log();
+ init_values();
+ WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER = "workload-identity-auth";
+ inheritedDataResidencySelection = Symbol("inheritedDataResidencySelection");
+ OpenAI = class {
+ /**
+ * API Client for interfacing with the OpenAI API.
+ *
+ * @param {string | null | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? null]
+ * @param {string | null | undefined} [opts.adminAPIKey=process.env['OPENAI_ADMIN_KEY'] ?? null]
+ * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
+ * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
+ * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null]
+ * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
+ * @param {Provider} [opts.provider] - Configure a third-party API provider. Mutually exclusive with top-level authentication and base URL options.
+ * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
+ * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API.
+ * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
+ */
+ constructor(clientOptions = {}) {
+ _OpenAI_instances.add(this);
+ _OpenAI_encoder.set(this, void 0);
+ _OpenAI_x509Authentication.set(this, void 0);
+ _OpenAI_x509Credential.set(this, void 0);
+ _OpenAI_x509Fetch.set(this, void 0);
+ _OpenAI_explicitDataResidency.set(this, false);
+ _OpenAI_responseAttempts.set(this, /* @__PURE__ */ new WeakMap());
+ this.completions = new Completions2(this);
+ this.chat = new Chat(this);
+ this.embeddings = new Embeddings(this);
+ this.files = new Files3(this);
+ this.images = new Images(this);
+ this.contentProvenanceChecks = new ContentProvenanceChecks(this);
+ this.audio = new Audio(this);
+ this.moderations = new Moderations(this);
+ this.models = new Models(this);
+ this.fineTuning = new FineTuning(this);
+ this.graders = new Graders2(this);
+ this.vectorStores = new VectorStores(this);
+ this.safety = new Safety(this);
+ this.webhooks = new Webhooks(this);
+ this.beta = new Beta(this);
+ this.batches = new Batches(this);
+ this.uploads = new Uploads(this);
+ this.admin = new Admin(this);
+ this.responses = new Responses2(this);
+ this.live = new Live(this);
+ this.realtime = new Realtime2(this);
+ this.conversations = new Conversations(this);
+ this.evals = new Evals(this);
+ this.containers = new Containers(this);
+ this.skills = new Skills(this);
+ this.videos = new Videos(this);
+ const { credential, options: normalizedOptions } = normalizeX509CredentialOptions(clientOptions);
+ clientOptions = normalizedOptions;
+ const residencyBaseURL = resolveDataResidency(clientOptions);
+ const provider = clientOptions.provider;
+ const { baseURL = provider ? null : readEnv("OPENAI_BASE_URL"), dataResidency: _dataResidency, [inheritedDataResidencySelection]: inheritedResidencySelection = false, apiKey = provider ? null : readEnv("OPENAI_API_KEY") ?? null, adminAPIKey = provider ? null : readEnv("OPENAI_ADMIN_KEY") ?? null, organization = provider ? null : readEnv("OPENAI_ORG_ID") ?? null, project = provider ? null : readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, workloadIdentity, x509Transport, credential: _credential, ...opts } = clientOptions;
+ if (provider) {
+ const conflictingOptions = ["apiKey", "adminAPIKey", "workloadIdentity", "x509Transport", "baseURL", "dataResidency"].filter((key) => (key === "workloadIdentity" ? workloadIdentity : clientOptions[key]) != null);
+ if (conflictingOptions.length) {
+ throw new OpenAIError(`The \`provider\` option cannot be used with ${conflictingOptions.map((key) => `\`${key}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`);
+ }
+ }
+ const identity = isX509WorkloadIdentity(workloadIdentity) ? { x509: workloadIdentity, legacy: void 0 } : { x509: void 0, legacy: workloadIdentity };
+ const x509Identity = identity.x509;
+ const usesX509Identity = x509Identity !== void 0;
+ const providerRuntime = provider ? configureProvider(provider) : void 0;
+ const options = {
+ apiKey,
+ adminAPIKey,
+ organization,
+ project,
+ webhookSecret,
+ workloadIdentity,
+ x509Transport,
+ provider,
+ ...opts,
+ baseURL: providerRuntime?.baseURL ?? residencyBaseURL ?? (baseURL || (usesX509Identity ? X509_API_BASE_URL : `https://api.openai.com/v1`))
+ };
+ if (x509Transport && !usesX509Identity) {
+ throw new OpenAIError("An X.509 transport requires an X.509 workload identity.");
+ }
+ if (usesX509Identity) {
+ if (residencyBaseURL !== void 0 || inheritedResidencySelection) {
+ throw new OpenAIError("X.509 workload identity does not support data residency selection.");
+ }
+ if (clientOptions.fetch !== void 0) {
+ throw new OpenAIError("X.509 workload identity does not support a custom fetch implementation.");
+ }
+ assertX509APIOrigin(options.baseURL);
+ assertX509RequestOptions(options.fetchOptions);
+ if (this.fetchWithAuth !== _a3.prototype.fetchWithAuth || this.fetchWithTimeout !== _a3.prototype.fetchWithTimeout) {
+ throw new OpenAIError("X.509 workload identity does not support overridden fetch dispatch hooks.");
+ }
+ }
+ if (apiKey && workloadIdentity) {
+ throw new OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive");
+ }
+ if (!providerRuntime && !apiKey && !adminAPIKey && !workloadIdentity) {
+ throw new OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");
+ }
+ if (!options.dangerouslyAllowBrowser && isRunningInBrowserOrBrowserWorker()) {
+ throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
+ }
+ this.baseURL = options.baseURL;
+ __classPrivateFieldSet(this, _OpenAI_explicitDataResidency, residencyBaseURL !== void 0 || inheritedResidencySelection, "f");
+ this.timeout = options.timeout ?? _a3.DEFAULT_TIMEOUT;
+ this.logger = options.logger ?? console;
+ const defaultLogLevel = "warn";
+ this.logLevel = defaultLogLevel;
+ this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel;
+ this.fetchOptions = options.fetchOptions;
+ this.maxRetries = options.maxRetries ?? 2;
+ this.fetch = options.fetch ?? getDefaultFetch();
+ __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f");
+ const customHeadersEnv = provider || credential ? void 0 : readEnv("OPENAI_CUSTOM_HEADERS");
+ if (customHeadersEnv) {
+ const parsed = {};
+ for (const line of customHeadersEnv.split("\n")) {
+ const colon = line.indexOf(":");
+ if (colon >= 0) {
+ parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
+ }
+ }
+ options.defaultHeaders = buildHeaders([parsed, options.defaultHeaders]);
+ }
+ this._options = options;
+ this._provider = providerRuntime;
+ if (x509Identity) {
+ const authentication = new X509WorkloadIdentityAuth(x509Identity, x509Transport, organization, project);
+ this._workloadIdentityAuth = authentication;
+ __classPrivateFieldSet(this, _OpenAI_x509Authentication, authentication, "f");
+ __classPrivateFieldSet(this, _OpenAI_x509Credential, credential, "f");
+ __classPrivateFieldSet(this, _OpenAI_x509Fetch, authentication.fetch(), "f");
+ this.fetch = __classPrivateFieldGet(this, _OpenAI_x509Fetch, "f");
+ markApprovedX509Client2(this);
+ } else if (identity.legacy) {
+ this._workloadIdentityAuth = new WorkloadIdentityAuth(identity.legacy, this.fetch);
+ }
+ this.apiKey = typeof apiKey === "string" ? apiKey : null;
+ this.adminAPIKey = adminAPIKey;
+ this.organization = organization;
+ this.project = project;
+ this.webhookSecret = webhookSecret;
+ }
+ /**
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
+ */
+ withOptions(options) {
+ const residencyBaseURL = resolveDataResidency(options);
+ const x509Authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
+ const inheritedOptions = {
+ ...this._options,
+ baseURL: this.baseURL,
+ maxRetries: this.maxRetries,
+ timeout: this.timeout,
+ logger: this.logger,
+ logLevel: this.logLevel,
+ fetch: __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ? void 0 : this.fetch,
+ fetchOptions: this.fetchOptions,
+ apiKey: this._options.apiKey,
+ adminAPIKey: this.adminAPIKey,
+ workloadIdentity: x509Authentication?.identitySnapshot() ?? this._options.workloadIdentity,
+ x509Transport: this._options.x509Transport,
+ organization: this.organization,
+ project: this.project,
+ webhookSecret: this.webhookSecret
+ };
+ const { credential, provider } = prepareX509ClientClone(inheritedOptions, options, __classPrivateFieldGet(this, _OpenAI_x509Credential, "f"), x509Authentication !== void 0);
+ if (residencyBaseURL !== void 0) {
+ delete inheritedOptions.baseURL;
+ }
+ const clientOptions = {
+ ...inheritedOptions,
+ ...options,
+ credential,
+ provider,
+ [inheritedDataResidencySelection]: __classPrivateFieldGet(this, _OpenAI_explicitDataResidency, "f") && residencyBaseURL === void 0 && !hasOwn(options, "baseURL") && options.credential === void 0 && !provider
+ };
+ const client = new this.constructor(clientOptions);
+ if (provider && new URL(client.baseURL).origin !== new URL(this.baseURL).origin) {
+ Object.assign(client._options, {
+ defaultHeaders: options.defaultHeaders,
+ defaultQuery: options.defaultQuery,
+ fetchOptions: options.fetchOptions,
+ fetch: options.fetch
+ });
+ client.fetchOptions = options.fetchOptions;
+ client.fetch = options.fetch ?? getDefaultFetch();
+ client.organization = options.organization ?? null;
+ client.project = options.project ?? null;
+ }
+ if (__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") && __classPrivateFieldGet(client, _OpenAI_x509Authentication, "f") && this.baseURL === client.baseURL && __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f").matches(__classPrivateFieldGet(client, _OpenAI_x509Authentication, "f"))) {
+ client._workloadIdentityAuth = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
+ __classPrivateFieldSet(client, _OpenAI_x509Authentication, __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f"), "f");
+ __classPrivateFieldSet(client, _OpenAI_x509Fetch, __classPrivateFieldGet(this, _OpenAI_x509Fetch, "f"), "f");
+ }
+ return client;
+ }
+ defaultQuery() {
+ return this._options.defaultQuery;
+ }
+ /** @internal Client request headers for each new WebSocket handshake. */
+ _buildWebSocketHeaders(authHeaders) {
+ return Object.fromEntries(buildHeaders([
+ {
+ "User-Agent": this.getUserAgent(),
+ "OpenAI-Organization": this.organization,
+ "OpenAI-Project": this.project
+ },
+ authHeaders,
+ this._options.defaultHeaders
+ ]).values);
+ }
+ validateHeaders({ values, nulls }, schemes = {
+ bearerAuth: true,
+ adminAPIKeyAuth: true
+ }) {
+ if (values.get("authorization") || values.get("api-key")) {
+ return;
+ }
+ if (nulls.has("authorization") || nulls.has("api-key")) {
+ return;
+ }
+ if (this._workloadIdentityAuth && schemes.bearerAuth) {
+ return;
+ }
+ throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted');
+ }
+ async authHeaders(opts, schemes = {
+ bearerAuth: true,
+ adminAPIKeyAuth: true
+ }) {
+ const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ?? this._workloadIdentityAuth;
+ if (authentication instanceof X509WorkloadIdentityAuth && schemes.adminAPIKeyAuth && this.adminAPIKey !== null) {
+ return await this.adminAPIKeyAuth(opts);
+ }
+ return buildHeaders([
+ schemes.bearerAuth ? await this.bearerAuth(opts) : null,
+ schemes.adminAPIKeyAuth ? await this.adminAPIKeyAuth(opts) : null
+ ]);
+ }
+ async bearerAuth(opts) {
+ const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ?? this._workloadIdentityAuth;
+ if (authentication) {
+ if (authentication instanceof X509WorkloadIdentityAuth) {
+ if (authentication === this._workloadIdentityAuth && (this.fetchWithAuth !== _a3.prototype.fetchWithAuth || this.fetchWithTimeout !== _a3.prototype.fetchWithTimeout)) {
+ throw new OpenAIError("X.509 workload identity does not support overridden fetch dispatch hooks.");
+ }
+ const snapshots = authentication.headerSnapshots();
+ if (!X509WorkloadIdentityAuth.shouldAuthenticate(opts, snapshots.defaultHeaders, snapshots.requestHeaders)) {
+ return void 0;
+ }
+ }
+ const token = authentication instanceof X509WorkloadIdentityAuth ? await authentication.getToken(opts, {
+ apiURL: authentication.requestAPIURL(),
+ ...authentication.headerSnapshots(),
+ ...authentication.requestSnapshot(),
+ signal: authentication.effectiveSignal(),
+ ...authentication.tenantSnapshot()
+ }) : await authentication.getToken();
+ return buildHeaders([{ Authorization: `Bearer ${token}` }]);
+ }
+ const { apiKey } = await resolveRealtimeAPIKey(this);
+ if (apiKey == null) {
+ return void 0;
+ }
+ return buildHeaders([{ Authorization: `Bearer ${apiKey}` }]);
+ }
+ async adminAPIKeyAuth(opts) {
+ if (this.adminAPIKey == null) {
+ return void 0;
+ }
+ return buildHeaders([{ Authorization: `Bearer ${this.adminAPIKey}` }]);
+ }
+ stringifyQuery(query) {
+ return stringifyQuery(query);
+ }
+ getUserAgent() {
+ return `${this.constructor.name}/JS ${VERSION}`;
+ }
+ defaultIdempotencyKey() {
+ return `stainless-node-retry-${uuid4()}`;
+ }
+ makeStatusError(status, error, message, headers) {
+ const normalizedError = error && typeof error === "object" && error.error == null ? { error } : error;
+ return APIError.generate(status, normalizedError, message, headers);
+ }
+ _hasApiKeyProvider() {
+ return typeof this._options.apiKey === "function";
+ }
+ /**
+ * Resolves a function-based API key and retains the resolved value on this client.
+ * Returns whether a provider was invoked. Internal callers can capture this
+ * invocation's key before another request updates the shared `apiKey` property.
+ * Overrides should forward `capture` or invoke it with their own resolved key
+ * to preserve invocation-local credentials in concurrent requests and Realtime factories.
+ * @internal
+ */
+ async _callApiKey(capture) {
+ if (this._provider) {
+ capture?.(this.apiKey);
+ return false;
+ }
+ const apiKey = this._options.apiKey;
+ if (typeof apiKey !== "function") {
+ capture?.(this.apiKey);
+ return false;
+ }
+ let token;
+ try {
+ token = await apiKey();
+ } catch (err2) {
+ if (err2 instanceof OpenAIError)
+ throw err2;
+ throw new OpenAIError(
+ `Failed to get token from 'apiKey' function: ${err2.message}`,
+ // @ts-ignore
+ { cause: err2 }
+ );
+ }
+ if (typeof token !== "string" || !token) {
+ throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);
+ }
+ this.apiKey = token;
+ capture?.(this.apiKey);
+ return true;
+ }
+ buildURL(path5, query, defaultBaseURL) {
+ const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
+ const url = isAbsoluteURL(path5) ? new URL(path5) : new URL(baseURL + (baseURL.endsWith("/") && path5.startsWith("/") ? path5.slice(1) : path5));
+ const defaultQuery = this.defaultQuery();
+ const pathQuery = Object.fromEntries(url.searchParams);
+ if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
+ query = { ...pathQuery, ...defaultQuery, ...query };
+ }
+ if (typeof query === "object" && query && !Array.isArray(query)) {
+ url.search = this.stringifyQuery(query);
+ }
+ return url.toString();
+ }
+ /**
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
+ * Function-based credentials are resolved later, when building authentication
+ * headers, including for direct `buildRequest()` calls. Overriding this hook
+ * does not bypass that resolution.
+ */
+ async prepareOptions(options) {
+ }
+ /**
+ * Used as a callback for mutating the given `RequestInit` object.
+ *
+ * This is useful for cases where you want to add certain headers based off of
+ * the request properties, e.g. `method` or `url`.
+ */
+ async prepareRequest(request, { url, options }) {
+ }
+ get(path5, opts) {
+ return this.methodRequest("get", path5, opts);
+ }
+ post(path5, opts) {
+ return this.methodRequest("post", path5, opts);
+ }
+ patch(path5, opts) {
+ return this.methodRequest("patch", path5, opts);
+ }
+ put(path5, opts) {
+ return this.methodRequest("put", path5, opts);
+ }
+ delete(path5, opts) {
+ return this.methodRequest("delete", path5, opts);
+ }
+ methodRequest(method, path5, opts) {
+ return this.request(Promise.resolve(opts).then((opts2) => {
+ return { method, path: path5, ...opts2 };
+ }));
+ }
+ request(options, remainingRetries = null) {
+ const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ?? this._workloadIdentityAuth;
+ const request = authentication instanceof X509WorkloadIdentityAuth ? Promise.resolve(options).then((resolved) => authentication.runRequest(() => this.makeRequest(resolved, remainingRetries, void 0), this)) : this.makeRequest(options, remainingRetries, void 0);
+ return this.responsePromise(request);
+ }
+ responsePromise(request, parse = (client, props) => this.parseResponseWithTimeout(client, props)) {
+ const promise = new APIPromise(this, request, (client, props) => {
+ const resume = __classPrivateFieldGet(this, _OpenAI_responseAttempts, "f").get(props.controller)?.continueRequest;
+ return resume ? resume(() => parse(client, props)) : parse(client, props);
+ });
+ promise.withResponse = async () => {
+ const data = await promise;
+ const { response } = await request;
+ return { data, response, request_id: response.headers.get("x-request-id") };
+ };
+ promise._thenUnwrap = (transform) => this.responsePromise(request, async (client, props) => addRequestID(transform(await parse(client, props), props), props.response));
+ return promise;
+ }
+ async parseResponseWithTimeout(client, props) {
+ if (props.options.stream || props.options.__binaryResponse || props.response.status === 204 || props.response.headers.get("content-length") === "0") {
+ return defaultParseResponse(client, props);
+ }
+ while (true) {
+ const attempt = __classPrivateFieldGet(this, _OpenAI_responseAttempts, "f").get(props.controller);
+ const timeout = attempt?.timeout ?? props.options.timeout ?? this.timeout;
+ const x509Authentication = attempt?.authentication;
+ const callerSignal = x509Authentication ? props.controller.signal : props.options.signal;
+ const abortError2 = () => x509Authentication && callerSignal ? this._makeUserAbortError(callerSignal) : new APIUserAbortError();
+ let remaining;
+ try {
+ remaining = x509Authentication?.remainingTimeout(props.options, timeout) ?? Math.max(0, props.startTime + timeout - Date.now());
+ } catch (error) {
+ const cancellation = callerSignal?.aborted ? abortError2() : void 0;
+ props.controller.abort();
+ void CancelReadableStream(props.response.body).catch(() => void 0);
+ throw cancellation ?? error;
+ }
+ let timer;
+ let abortListener;
+ let timedOut = false;
+ try {
+ if (callerSignal?.aborted && attempt?.helperMethod !== "runTools") {
+ throw abortError2();
+ }
+ const timeoutPromise = new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ timedOut = true;
+ props.controller.abort();
+ reject(new APIConnectionTimeoutError());
+ }, remaining);
+ if (callerSignal) {
+ abortListener = () => {
+ if (!timedOut)
+ reject(abortError2());
+ };
+ callerSignal.addEventListener("abort", abortListener, { once: true });
+ }
+ });
+ return await Promise.race([defaultParseResponse(client, props), timeoutPromise]);
+ } catch (error) {
+ if (callerSignal?.aborted && !timedOut) {
+ throw abortError2();
+ }
+ if (!timedOut) {
+ if (x509Authentication && error instanceof SyntaxError) {
+ throw new SyntaxError("X.509 workload identity API response contains invalid JSON.");
+ }
+ if (x509Authentication && !(error instanceof OpenAIError)) {
+ throw new APIConnectionError({
+ message: "X.509 workload identity API response body could not be read."
+ });
+ }
+ throw error;
+ }
+ const retriesRemaining = attempt?.retriesRemaining ?? 0;
+ if (!retriesRemaining || attempt?.hasStreamingBody || props.options.__metadata?.["hasStreamingBody"] || globalThis.ReadableStream && props.options.body instanceof globalThis.ReadableStream || typeof props.options.body === "object" && props.options.body !== null && (Symbol.asyncIterator in props.options.body || Symbol.iterator in props.options.body && "next" in props.options.body && typeof props.options.body.next === "function")) {
+ throw new APIConnectionTimeoutError();
+ }
+ if (timer !== void 0)
+ clearTimeout(timer);
+ if (abortListener)
+ callerSignal?.removeEventListener("abort", abortListener);
+ abortListener = void 0;
+ const next = await this.retryRequest(props.options, retriesRemaining, props.retryOfRequestLogID ?? props.requestLogID, void 0, props.requestSignal);
+ Object.assign(props, next);
+ } finally {
+ if (timer !== void 0)
+ clearTimeout(timer);
+ if (abortListener)
+ callerSignal?.removeEventListener("abort", abortListener);
+ }
+ }
+ }
+ /** Keeps terminal X.509 error-body consumption inside the original logical request deadline. */
+ async readX509ResponseError(response, options, timeout, controller, authentication) {
+ const deadline = new AbortController();
+ const callerSignal = controller.signal;
+ let timedOut = false;
+ const cancel = () => deadline.abort(callerSignal.reason);
+ callerSignal.addEventListener("abort", cancel, { once: true });
+ if (callerSignal.aborted) {
+ cancel();
+ }
+ try {
+ const remaining = authentication.remainingTimeout(options, timeout);
+ const expiration = authentication.waitForRetry(remaining, deadline.signal).then(() => {
+ throw new APIConnectionTimeoutError();
+ });
+ const body = await Promise.race([
+ response.text().catch(() => "X.509 workload identity API response body could not be read."),
+ expiration
+ ]);
+ if (callerSignal.aborted) {
+ throw this._makeUserAbortError(callerSignal);
+ }
+ return body;
+ } catch (error) {
+ if (error instanceof APIConnectionTimeoutError) {
+ timedOut = !callerSignal.aborted;
+ controller.abort();
+ void CancelReadableStream(response.body).catch(() => void 0);
+ }
+ if (callerSignal.aborted && !timedOut) {
+ throw this._makeUserAbortError(callerSignal);
+ }
+ throw error;
+ } finally {
+ callerSignal.removeEventListener("abort", cancel);
+ deadline.abort();
+ }
+ }
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
+ const options = await optionsInput;
+ const maxRetries = options.maxRetries ?? this.maxRetries;
+ if (retriesRemaining == null) {
+ retriesRemaining = maxRetries;
+ }
+ const x509Authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
+ x509Authentication?.beginRequestPreparation();
+ await this.prepareOptions(options);
+ x509Authentication?.beginRequestPlanning();
+ let built;
+ try {
+ const candidate = await this.buildRequest(options, {
+ retryCount: maxRetries - retriesRemaining
+ });
+ built = { req: candidate.req, url: candidate.url, timeout: candidate.timeout };
+ if (x509Authentication) {
+ validatePositiveInteger("timeout", built.timeout);
+ x509Authentication.authorizePlannedRequest(built.url, built.req, built.timeout);
+ if (X509WorkloadIdentityAuth.isStreamingRequestBody(built.req.body)) {
+ options.__metadata = { ...options.__metadata, hasStreamingBody: true };
+ }
+ await this.prepareRequest(built.req, { url: built.url, options });
+ await this._provider?.prepareRequest?.(built.req, { url: built.url, options });
+ x509Authentication.beginRequestPlanning();
+ x509Authentication.authorizePlannedRequest(built.url, built.req, built.timeout, true);
+ if (X509WorkloadIdentityAuth.isStreamingRequestBody(built.req.body)) {
+ options.__metadata = { ...options.__metadata, hasStreamingBody: true };
+ }
+ const callerSignal2 = x509Authentication.requestSnapshot().signal;
+ if (callerSignal2?.aborted || built.req.signal?.aborted) {
+ throw this._makeUserAbortError(callerSignal2?.aborted ? callerSignal2 : built.req.signal);
+ }
+ x509Authentication.setEffectiveSignal(built.req.signal || callerSignal2 ? createRequestController(built.req.signal ?? callerSignal2, callerSignal2).signal : void 0);
+ x509Authentication.beginRequestNetwork();
+ const security2 = options.__security ?? { bearerAuth: true };
+ const authenticationHeaders = await this.authHeaders(options, security2);
+ const suppliedHeaders = x509Authentication.headerSnapshots();
+ const supplied = buildHeaders([suppliedHeaders.defaultHeaders, suppliedHeaders.requestHeaders]);
+ for (const [name, value] of authenticationHeaders?.values ?? []) {
+ if (!supplied.nulls.has(name) && !built.req.headers.has(name)) {
+ built.req.headers.set(name, value);
+ }
+ }
+ this.validateHeaders(buildHeaders([supplied, built.req.headers]), security2);
+ }
+ } catch (error) {
+ x509Authentication?.retireRequestBody();
+ if (x509Authentication && retriesRemaining && !options.__metadata?.["hasStreamingBody"] && X509WorkloadIdentityAuth.isRetryableFailure(error)) {
+ return await this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? "x509-token-exchange", X509WorkloadIdentityAuth.retryHeaders(error));
+ }
+ throw error;
+ }
+ const { req, url } = built;
+ const timeout = x509Authentication ? Math.min(built.timeout, x509Authentication.requestSnapshot().timeout) : built.timeout;
+ x509Authentication?.bindRequest(options, req, this.adminAPIKey);
+ let hasStreamingBody = options.__metadata?.["hasStreamingBody"] === true;
+ if (!x509Authentication) {
+ await this.prepareRequest(req, { url, options });
+ await this._provider?.prepareRequest?.(req, { url, options });
+ }
+ x509Authentication?.adoptRequestHeaders(req);
+ if (x509Authentication && X509WorkloadIdentityAuth.isStreamingRequestBody(req.body)) {
+ hasStreamingBody = true;
+ }
+ const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
+ const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
+ const startTime = x509Authentication?.requestStartedAt(options) ?? Date.now();
+ if (this.logLevel === "debug") {
+ const body = typeof req.body === "string" ? { type: "string", length: req.body.length } : req.body;
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
+ retryOfRequestLogID,
+ method: options.method,
+ url,
+ options: x509Authentication ? { body, ...x509Authentication.requestSnapshot() } : { ...options, body },
+ headers: req.headers
+ }));
+ }
+ const callerSignal = x509Authentication ? x509Authentication.requestSnapshot().signal : options.signal;
+ if (callerSignal?.aborted || req.signal?.aborted) {
+ throw this._makeUserAbortError(callerSignal?.aborted ? callerSignal : req.signal);
+ }
+ const security = options.__security ?? { bearerAuth: true };
+ const controller = x509Authentication || this.fetchWithTimeout === _a3.prototype.fetchWithTimeout ? createRequestController(req.signal ?? (x509Authentication ? callerSignal : void 0), x509Authentication ? callerSignal : void 0) : new AbortController();
+ const remainingTimeout = x509Authentication?.remainingTimeout(options, timeout) ?? timeout;
+ const fetchWithAuth = x509Authentication ? _a3.prototype.fetchWithAuth : this.fetchWithAuth;
+ x509Authentication?.releaseRequestBody(req.body);
+ const response = await fetchWithAuth.call(this, url, req, remainingTimeout, controller, security).catch(castToError);
+ const headersTime = Date.now();
+ if (response instanceof globalThis.Error) {
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
+ if (callerSignal?.aborted || req.signal?.aborted) {
+ throw this._makeUserAbortError(callerSignal?.aborted ? callerSignal : req.signal);
+ }
+ const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
+ if (retriesRemaining && !hasStreamingBody && (!x509Authentication || isTransientX509ConnectionError2(response))) {
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
+ retryOfRequestLogID,
+ url,
+ durationMs: headersTime - startTime,
+ message: x509Authentication ? "X.509 workload identity API connection failed." : response.message
+ }));
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, void 0, req.signal);
+ }
+ const terminalMessage = hasStreamingBody ? "error; streaming body cannot be retried" : "error; no more retries left";
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${terminalMessage}`);
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${terminalMessage})`, formatRequestDetails({
+ retryOfRequestLogID,
+ url,
+ durationMs: headersTime - startTime,
+ message: x509Authentication ? "X.509 workload identity API connection failed." : response.message
+ }));
+ if (response instanceof OAuthError || response instanceof SubjectTokenProviderError) {
+ throw response;
+ }
+ if (isTimeout) {
+ const transportCause = "cause" in response ? response.cause : void 0;
+ const isHeadersTimeout = typeof transportCause === "object" && transportCause !== null && "code" in transportCause && transportCause.code === "UND_ERR_HEADERS_TIMEOUT";
+ const timeoutError = isHeadersTimeout ? new APIConnectionTimeoutError({
+ message: "Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."
+ }) : new APIConnectionTimeoutError();
+ if (x509Authentication) {
+ throw new APIConnectionTimeoutError();
+ }
+ throw Object.assign(timeoutError, { cause: response });
+ }
+ if (x509Authentication) {
+ throw new APIConnectionError({ message: "X.509 workload identity API connection failed." });
+ }
+ throw new APIConnectionError({
+ message: getConnectionErrorMessage(response),
+ cause: response
+ });
+ }
+ const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "x-request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
+ const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${redactURL(url)} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
+ if (!response.ok) {
+ const rejectedX509Credential = response.status === 401 && x509Authentication && security.bearerAuth && x509Authentication.usedWorkloadToken(options);
+ if (rejectedX509Credential) {
+ x509Authentication.invalidateToken();
+ }
+ if (response.status === 401 && (x509Authentication || this._workloadIdentityAuth) && security.bearerAuth && (!x509Authentication || x509Authentication.usedWorkloadToken(options)) && (!x509Authentication || retriesRemaining > 0) && !hasStreamingBody && !options.__metadata?.["workloadIdentityTokenRefreshed"]) {
+ if (x509Authentication) {
+ void CancelReadableStream(response.body).catch(() => void 0);
+ } else {
+ await CancelReadableStream(response.body);
+ this._workloadIdentityAuth?.invalidateToken();
+ }
+ const replayOptions = {
+ ...options,
+ __metadata: {
+ ...options.__metadata,
+ workloadIdentityTokenRefreshed: true
+ }
+ };
+ return this.makeRequest(replayOptions, x509Authentication ? retriesRemaining - 1 : retriesRemaining, retryOfRequestLogID ?? requestLogID);
+ }
+ const shouldRetry = rejectedX509Credential && options.__metadata?.["workloadIdentityTokenRefreshed"] ? false : await this.shouldRetry(response);
+ if (retriesRemaining && shouldRetry && !hasStreamingBody) {
+ const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
+ if (x509Authentication) {
+ void CancelReadableStream(response.body).catch(() => void 0);
+ } else {
+ await CancelReadableStream(response.body);
+ }
+ loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: response.url,
+ status: response.status,
+ headers: response.headers,
+ durationMs: headersTime - startTime
+ }));
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers, req.signal);
+ }
+ const retryMessage = shouldRetry ? hasStreamingBody ? `error; streaming body cannot be retried` : `error; no more retries left` : `error; not retryable`;
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
+ const errText = x509Authentication ? await this.readX509ResponseError(response, options, timeout, controller, x509Authentication) : await response.text().catch((err3) => castToError(err3).message);
+ const errJSON = safeJSON(errText);
+ const errMessage = errJSON ? void 0 : errText;
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: response.url,
+ status: response.status,
+ headers: response.headers,
+ message: errMessage,
+ durationMs: Date.now() - startTime
+ }));
+ const err2 = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
+ throw err2;
+ }
+ loggerFor(this).info(responseInfo);
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: response.url,
+ status: response.status,
+ headers: response.headers,
+ durationMs: headersTime - startTime
+ }));
+ const continueRequest = x509Authentication?.continuation();
+ x509Authentication?.releaseRequestCredentials();
+ __classPrivateFieldGet(this, _OpenAI_responseAttempts, "f").set(controller, {
+ timeout,
+ retriesRemaining,
+ hasStreamingBody,
+ ...x509Authentication ? { authentication: x509Authentication } : {},
+ helperMethod: options.__metadata?.["helperMethod"],
+ ...continueRequest ? { continueRequest } : {}
+ });
+ return {
+ response,
+ options,
+ controller,
+ requestSignal: req.signal,
+ requestLogID,
+ retryOfRequestLogID,
+ startTime
+ };
+ }
+ getAPIList(path5, Page2, opts) {
+ return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path5, ...opts2 })) : { method: "get", path: path5, ...opts });
+ }
+ requestAPIList(Page2, options) {
+ const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ?? this._workloadIdentityAuth;
+ const request = authentication instanceof X509WorkloadIdentityAuth ? Promise.resolve(options).then((resolved) => authentication.runRequest(() => this.makeRequest(resolved, null, void 0), this)) : this.makeRequest(options, null, void 0);
+ const page2 = new PagePromise(this, request, Page2);
+ const guarded = this.responsePromise(request, async (client, props) => {
+ const body = await this.parseResponseWithTimeout(client, props);
+ return new Page2(client, props.response, body, props.options);
+ });
+ page2.then = guarded.then.bind(guarded);
+ page2.catch = guarded.catch.bind(guarded);
+ page2.finally = guarded.finally.bind(guarded);
+ page2.withResponse = guarded.withResponse.bind(guarded);
+ page2._thenUnwrap = guarded._thenUnwrap.bind(guarded);
+ return page2;
+ }
+ async fetchWithAuth(url, init, timeout, controller, schemes = {
+ bearerAuth: true,
+ adminAPIKeyAuth: true
+ }) {
+ if (this._workloadIdentityAuth && !__classPrivateFieldGet(this, _OpenAI_x509Fetch, "f") && schemes.bearerAuth) {
+ const headers = init.headers;
+ const authHeader = headers.get("Authorization");
+ if (authHeader === `Bearer ${WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER}`) {
+ const token = await this._workloadIdentityAuth.getToken();
+ headers.set("Authorization", `Bearer ${token}`);
+ }
+ }
+ const fetchWithTimeout = __classPrivateFieldGet(this, _OpenAI_x509Fetch, "f") ? _a3.prototype.fetchWithTimeout : this.fetchWithTimeout;
+ const response = await fetchWithTimeout.call(this, url, init, timeout, controller);
+ return response;
+ }
+ async fetchWithTimeout(url, init, ms, controller) {
+ const { signal, method, ...options } = init || {};
+ const abort = this._makeAbort(controller);
+ const composed = !!signal && composedCallerSignals.get(controller) === signal;
+ const cleanup = signal && !composed ? addRequestAbortListener(signal, abort, controller.signal) : void 0;
+ const timeout = setTimeout(abort, ms);
+ const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
+ const fetchOptions = {
+ signal: controller.signal,
+ ...isReadableBody ? { duplex: "half" } : {},
+ method: "GET",
+ ...options
+ };
+ if (method) {
+ fetchOptions.method = method.toUpperCase();
+ }
+ try {
+ const response = await (__classPrivateFieldGet(this, _OpenAI_x509Fetch, "f") ?? this.fetch).call(void 0, url, fetchOptions);
+ if (cleanup) {
+ retainRequestAbortCallback(response.body ?? response, abort, controller.signal);
+ }
+ return response;
+ } catch (err2) {
+ cleanup?.();
+ throw err2;
+ } finally {
+ clearTimeout(timeout);
+ }
+ }
+ async shouldRetry(response) {
+ const shouldRetryHeader = response.headers.get("x-should-retry");
+ if (shouldRetryHeader === "true")
+ return true;
+ if (shouldRetryHeader === "false")
+ return false;
+ if (response.status === 408)
+ return true;
+ if (response.status === 409)
+ return true;
+ if (response.status === 429)
+ return true;
+ if (response.status >= 500)
+ return true;
+ return false;
+ }
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders, requestSignal = options.signal) {
+ let timeoutMillis;
+ const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
+ if (retryAfterMillisHeader) {
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
+ if (!Number.isNaN(timeoutMs)) {
+ timeoutMillis = timeoutMs;
+ }
+ }
+ const retryAfterHeader = responseHeaders?.get("retry-after");
+ if (retryAfterHeader && timeoutMillis === void 0) {
+ const timeoutSeconds = parseFloat(retryAfterHeader);
+ if (!Number.isNaN(timeoutSeconds)) {
+ timeoutMillis = timeoutSeconds * 1e3;
+ } else {
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
+ }
+ }
+ if (timeoutMillis === void 0 || !Number.isFinite(timeoutMillis) || timeoutMillis < 0 || timeoutMillis > 60 * 1e3) {
+ const maxRetries = options.maxRetries ?? this.maxRetries;
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
+ }
+ const x509Authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
+ if (x509Authentication) {
+ const remaining = x509Authentication.remainingTimeout(options, x509Authentication.requestSnapshot().timeout);
+ if (timeoutMillis >= remaining) {
+ throw new APIConnectionTimeoutError();
+ }
+ }
+ if (x509Authentication) {
+ await x509Authentication.waitForRetry(timeoutMillis, x509Authentication.effectiveSignal());
+ } else {
+ const retrySignals = requestSignal === options.signal ? [requestSignal] : [requestSignal, options.signal];
+ try {
+ await sleep(timeoutMillis, ...retrySignals);
+ } catch (error) {
+ const abortedSignal = retrySignals.find((signal) => signal?.aborted);
+ if (abortedSignal) {
+ throw this._makeUserAbortError(abortedSignal);
+ }
+ throw error;
+ }
+ }
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
+ }
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
+ const initialRetryDelay = 0.5;
+ const maxRetryDelay = 8;
+ const numRetries = maxRetries - retriesRemaining;
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
+ const jitter = 1 - Math.random() * 0.25;
+ return sleepSeconds * jitter * 1e3;
+ }
+ /**
+ * Builds a request, resolving callback credentials when constructing authentication
+ * headers, after any subclass request-option rewrites. Calling this method directly
+ * also resolves credentials. Complete replacement builders own authentication and
+ * can call `this.authHeaders()` to resolve headers with request-local credentials.
+ */
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
+ if (__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") && !__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f").inRequest(this)) {
+ const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
+ return await authentication.runRequest(async () => {
+ const built = await _a3.prototype.buildRequest.call(this, inputOptions, { retryCount });
+ authentication.releaseRequestBody(built.req.body);
+ return built;
+ }, this);
+ }
+ const options = { ...inputOptions };
+ const x509Authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
+ const x509Tenant = x509Authentication?.snapshotTenant(this.organization, this.project);
+ const x509Headers = x509Authentication?.snapshotHeaders(this._options.defaultHeaders, options.headers);
+ if (x509Headers) {
+ options.headers = x509Headers.requestHeaders;
+ }
+ const x509ClientFetchOptions = x509Authentication ? snapshotX509RequestOptions(this.fetchOptions) : void 0;
+ const x509RequestFetchOptions = x509Authentication ? snapshotX509RequestOptions(options.fetchOptions) : void 0;
+ const { method, path: path5, query, defaultBaseURL } = options;
+ const url = this.buildURL(path5, query, defaultBaseURL);
+ x509Authentication?.snapshotAPIURL(url);
+ const explicitTimeout = "timeout" in options;
+ if (explicitTimeout)
+ validatePositiveInteger("timeout", options.timeout);
+ options.timeout = options.timeout ?? this.timeout;
+ if (x509Authentication && x509RequestFetchOptions) {
+ x509Authentication.snapshotRequest(options.signal, options.timeout, x509RequestFetchOptions);
+ }
+ if (x509Authentication) {
+ const snapshot = x509Authentication.requestSnapshot();
+ options.timeout = snapshot.timeout;
+ if (snapshot.signal === void 0) {
+ delete options.signal;
+ } else {
+ options.signal = snapshot.signal;
+ }
+ }
+ const authenticationHeaders = this._provider || x509Authentication ? void 0 : await this.authHeaders(inputOptions, inputOptions.__security ?? { bearerAuth: true });
+ const { bodyHeaders, body, isStreamingBody } = this.buildBody({ options });
+ if (isStreamingBody) {
+ inputOptions.__metadata = {
+ ...inputOptions.__metadata,
+ hasStreamingBody: true
+ };
+ x509Authentication?.ownRequestBody(body, options.body);
+ }
+ const reqHeaders = await this.buildHeaders({
+ options: inputOptions,
+ method,
+ bodyHeaders,
+ authenticationHeaders,
+ retryCount,
+ x509Headers,
+ x509Timeout: explicitTimeout ? options.timeout : void 0,
+ x509Tenant
+ });
+ const req = {
+ method,
+ headers: reqHeaders,
+ ...options.signal && { signal: options.signal },
+ ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
+ ...body && { body },
+ ...(x509Authentication ? x509ClientFetchOptions : this.fetchOptions) ?? {},
+ ...(x509Authentication ? x509RequestFetchOptions : options.fetchOptions) ?? {}
+ };
+ return { req, url, timeout: options.timeout };
+ }
+ async buildHeaders({ options, method, bodyHeaders, authenticationHeaders, retryCount, x509Headers, x509Timeout, x509Tenant }) {
+ let idempotencyHeaders = {};
+ if (this.idempotencyHeader && method !== "get") {
+ if (!options.idempotencyKey)
+ options.idempotencyKey = this.defaultIdempotencyKey();
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
+ }
+ const helperMethod = options.__metadata?.["helperMethod"];
+ const timeout = x509Headers ? x509Timeout : options.timeout;
+ const headers = buildHeaders([
+ idempotencyHeaders,
+ {
+ Accept: "application/json",
+ ...!isRunningInBrowserOrBrowserWorker() ? { "User-Agent": this.getUserAgent() } : void 0,
+ "X-Stainless-Retry-Count": String(retryCount),
+ ...timeout ? { "X-Stainless-Timeout": String(Math.trunc(timeout / 1e3)) } : {},
+ ...getPlatformHeaders(),
+ ...typeof helperMethod === "string" ? { "X-Stainless-Helper-Method": helperMethod } : {},
+ "OpenAI-Organization": x509Tenant ? x509Tenant.organization : this.organization,
+ "OpenAI-Project": x509Tenant ? x509Tenant.project : this.project
+ },
+ // X.509 owns streaming uploads before authentication so it can retire them on failure.
+ __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") && !__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f").isPlanningRequest() ? await this.authHeaders(options, options.__security ?? { bearerAuth: true }) : authenticationHeaders,
+ x509Headers?.defaultHeaders ?? this._options.defaultHeaders,
+ bodyHeaders,
+ x509Headers?.requestHeaders ?? options.headers
+ ]);
+ if (!this._provider && !__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f")?.isPlanningRequest()) {
+ this.validateHeaders(headers, options.__security ?? { bearerAuth: true });
+ }
+ return headers.values;
+ }
+ _makeAbort(controller) {
+ return () => controller.abort();
+ }
+ _makeUserAbortError(signal) {
+ const error = new APIUserAbortError();
+ Object.defineProperty(error, "cause", { value: signal.reason, writable: true, configurable: true });
+ return error;
+ }
+ buildBody({ options }) {
+ const { body, headers: rawHeaders } = options;
+ if (!body) {
+ if (body === void 0 && "body" in options) {
+ return { ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers: buildHeaders([rawHeaders]) }), isStreamingBody: false };
+ }
+ return { bodyHeaders: void 0, body: void 0, isStreamingBody: false };
+ }
+ const headers = buildHeaders([rawHeaders]);
+ const isReadableStream2 = typeof globalThis.ReadableStream !== "undefined" && body instanceof globalThis.ReadableStream;
+ const isRetryableBody = !isReadableStream2 && (typeof body === "string" || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof globalThis.Blob !== "undefined" && body instanceof globalThis.Blob || body instanceof URLSearchParams || body instanceof FormData);
+ if (
+ // Pass raw type verbatim
+ ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
+ headers.values.has("content-type") || // `Blob` is superset of `File`
+ globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`
+ body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
+ body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
+ isReadableStream2
+ ) {
+ return { bodyHeaders: void 0, body, isStreamingBody: !isRetryableBody };
+ } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
+ return {
+ bodyHeaders: void 0,
+ body: ReadableStreamFrom(body),
+ isStreamingBody: true
+ };
+ } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
+ return {
+ bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
+ body: this.stringifyQuery(body),
+ isStreamingBody: false
+ };
+ } else {
+ return { ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers }), isStreamingBody: false };
+ }
+ }
+ };
+ _a3 = OpenAI, _OpenAI_encoder = /* @__PURE__ */ new WeakMap(), _OpenAI_x509Authentication = /* @__PURE__ */ new WeakMap(), _OpenAI_x509Credential = /* @__PURE__ */ new WeakMap(), _OpenAI_x509Fetch = /* @__PURE__ */ new WeakMap(), _OpenAI_explicitDataResidency = /* @__PURE__ */ new WeakMap(), _OpenAI_responseAttempts = /* @__PURE__ */ new WeakMap(), _OpenAI_instances = /* @__PURE__ */ new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden2() {
+ return __classPrivateFieldGet(this, _OpenAI_explicitDataResidency, "f") || this._provider !== void 0 || this.baseURL !== "https://api.openai.com/v1";
+ };
+ OpenAI.OpenAI = _a3;
+ OpenAI.DEFAULT_TIMEOUT = 6e5;
+ OpenAI.OpenAIError = OpenAIError;
+ OpenAI.APIError = APIError;
+ OpenAI.APIConnectionError = APIConnectionError;
+ OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError;
+ OpenAI.APIUserAbortError = APIUserAbortError;
+ OpenAI.NotFoundError = NotFoundError;
+ OpenAI.ConflictError = ConflictError;
+ OpenAI.RateLimitError = RateLimitError;
+ OpenAI.BadRequestError = BadRequestError;
+ OpenAI.AuthenticationError = AuthenticationError;
+ OpenAI.InternalServerError = InternalServerError;
+ OpenAI.PermissionDeniedError = PermissionDeniedError;
+ OpenAI.UnprocessableEntityError = UnprocessableEntityError;
+ OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
+ OpenAI.toFile = toFile;
+ OpenAI.toStreamingFile = toStreamingFile;
+ OpenAI.Completions = Completions2;
+ OpenAI.Chat = Chat;
+ OpenAI.Embeddings = Embeddings;
+ OpenAI.Files = Files3;
+ OpenAI.Images = Images;
+ OpenAI.ContentProvenanceChecks = ContentProvenanceChecks;
+ OpenAI.Audio = Audio;
+ OpenAI.Moderations = Moderations;
+ OpenAI.Models = Models;
+ OpenAI.FineTuning = FineTuning;
+ OpenAI.Graders = Graders2;
+ OpenAI.VectorStores = VectorStores;
+ OpenAI.Safety = Safety;
+ OpenAI.Webhooks = Webhooks;
+ OpenAI.Beta = Beta;
+ OpenAI.Batches = Batches;
+ OpenAI.Uploads = Uploads;
+ OpenAI.Admin = Admin;
+ OpenAI.Responses = Responses2;
+ OpenAI.Live = Live;
+ OpenAI.Realtime = Realtime2;
+ OpenAI.Conversations = Conversations;
+ OpenAI.Evals = Evals;
+ OpenAI.Containers = Containers;
+ OpenAI.Skills = Skills;
+ OpenAI.Videos = Videos;
+ OpenAI.ConversationCursorPage = ConversationCursorPage;
+ OpenAI.CursorPage = CursorPage;
+ OpenAI.NextCursorPage = NextCursorPage;
+ OpenAI.Page = Page;
+ OpenAI.TokenPage = TokenPage;
+ composedCallerSignals = /* @__PURE__ */ new WeakMap();
+ }
+});
+
+// node_modules/openai/azure.mjs
+var init_azure = __esm({
+ "node_modules/openai/azure.mjs"() {
+ init_headers();
+ init_error2();
+ init_utils2();
+ init_path();
+ init_client();
+ init_data_residency();
+ }
+});
+
+// node_modules/openai/internal/bedrock.mjs
+var brand_privateBedrockClient;
+var init_bedrock = __esm({
+ "node_modules/openai/internal/bedrock.mjs"() {
+ init_error2();
+ init_utils2();
+ brand_privateBedrockClient = Symbol.for("openai.privateBedrockClient");
+ }
+});
+
+// node_modules/openai/bedrock.mjs
+var _a4;
+var init_bedrock2 = __esm({
+ "node_modules/openai/bedrock.mjs"() {
+ init_error2();
+ init_client();
+ init_realtime_credentials();
+ init_data_residency();
+ init_bedrock();
+ init_headers();
+ init_utils2();
+ init_ResponsesParser();
+ init_resources();
+ _a4 = brand_privateBedrockClient;
+ }
+});
+
+// node_modules/openai/index.mjs
+var init_openai = __esm({
+ "node_modules/openai/index.mjs"() {
+ init_client();
+ init_uploads2();
+ init_api_promise();
+ init_client();
+ init_pagination();
+ init_error();
+ init_azure();
+ init_bedrock2();
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/error-body.js
+function normalizeProviderError(error) {
+ if (!(error instanceof Error)) {
+ return { message: safeJsonStringify(error), messageCarriesBody: false };
+ }
+ const sdkError = error;
+ const status = extractStatus(sdkError);
+ const body = extractBody(sdkError);
+ const messageCarriesBody = body === void 0 || error.message.includes(body);
+ return {
+ status,
+ body,
+ message: error.message,
+ messageCarriesBody
+ };
+}
+function extractStatus(error) {
+ if (typeof error.statusCode === "number")
+ return error.statusCode;
+ if (typeof error.status === "number")
+ return error.status;
+ if (typeof error.$metadata?.httpStatusCode === "number")
+ return error.$metadata.httpStatusCode;
+ if (typeof error.$response?.statusCode === "number")
+ return error.$response.statusCode;
+ return void 0;
+}
+function extractBody(error) {
+ const bodyText = pickBodyText(error);
+ if (bodyText === void 0)
+ return void 0;
+ const trimmed = bodyText.trim();
+ if (trimmed.length === 0)
+ return void 0;
+ return truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);
+}
+function pickBodyText(error) {
+ if (typeof error.body === "string")
+ return error.body;
+ if (isPlainNonEmptyObject(error.error))
+ return safeJsonStringify(error.error);
+ const responseBody = error.$response?.body;
+ if (typeof responseBody === "string")
+ return responseBody;
+ if (isReadableStreamLike(responseBody))
+ return void 0;
+ if (isPlainNonEmptyObject(responseBody))
+ return safeJsonStringify(responseBody);
+ return void 0;
+}
+function isReadableStreamLike(value) {
+ return typeof value === "object" && value !== null && "pipe" in value && typeof value.pipe === "function";
+}
+function isPlainNonEmptyObject(value) {
+ if (typeof value !== "object" || value === null)
+ return false;
+ const proto = Object.getPrototypeOf(value);
+ if (proto !== Object.prototype && proto !== null)
+ return false;
+ return Object.keys(value).length > 0;
+}
+function formatProviderError(norm, prefix) {
+ if (norm.messageCarriesBody || norm.status === void 0 || norm.body === void 0) {
+ return prefix !== void 0 && norm.status !== void 0 ? `${prefix} (${norm.status}): ${norm.message}` : norm.message;
+ }
+ return prefix !== void 0 ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;
+}
+function truncateErrorText(text, maxChars) {
+ if (text.length <= maxChars)
+ return text;
+ return `${text.slice(0, maxChars)}... [truncated ${text.length - maxChars} chars]`;
+}
+function safeJsonStringify(value) {
+ try {
+ const serialized = JSON.stringify(value);
+ return serialized === void 0 ? String(value) : serialized;
+ } catch {
+ return String(value);
+ }
+}
+var MAX_PROVIDER_ERROR_BODY_CHARS;
+var init_error_body = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/error-body.js"() {
+ MAX_PROVIDER_ERROR_BODY_CHARS = 4e3;
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/hash.js
+function shortHash(str) {
+ let h1 = 3735928559;
+ let h2 = 1103547991;
+ for (let i = 0; i < str.length; i++) {
+ const ch = str.charCodeAt(i);
+ h1 = Math.imul(h1 ^ ch, 2654435761);
+ h2 = Math.imul(h2 ^ ch, 1597334677);
+ }
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
+ return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);
+}
+var init_hash = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/hash.js"() {
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/headers.js
+function headersToRecord(headers) {
+ const result = {};
+ for (const [key, value] of headers.entries()) {
+ result[key] = value;
+ }
+ return result;
+}
+var init_headers2 = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/headers.js"() {
+ }
+});
+
+// node_modules/partial-json/dist/options.js
+var require_options = __commonJS({
+ "node_modules/partial-json/dist/options.js"(exports) {
+ "use strict";
+ Object.defineProperty(exports, "__esModule", { value: true });
+ exports.Allow = exports.ALL = exports.COLLECTION = exports.ATOM = exports.SPECIAL = exports.INF = exports._INFINITY = exports.INFINITY = exports.NAN = exports.BOOL = exports.NULL = exports.OBJ = exports.ARR = exports.NUM = exports.STR = void 0;
+ exports.STR = 1;
+ exports.NUM = 2;
+ exports.ARR = 4;
+ exports.OBJ = 8;
+ exports.NULL = 16;
+ exports.BOOL = 32;
+ exports.NAN = 64;
+ exports.INFINITY = 128;
+ exports._INFINITY = 256;
+ exports.INF = exports.INFINITY | exports._INFINITY;
+ exports.SPECIAL = exports.NULL | exports.BOOL | exports.INF | exports.NAN;
+ exports.ATOM = exports.STR | exports.NUM | exports.SPECIAL;
+ exports.COLLECTION = exports.ARR | exports.OBJ;
+ exports.ALL = exports.ATOM | exports.COLLECTION;
+ exports.Allow = { STR: exports.STR, NUM: exports.NUM, ARR: exports.ARR, OBJ: exports.OBJ, NULL: exports.NULL, BOOL: exports.BOOL, NAN: exports.NAN, INFINITY: exports.INFINITY, _INFINITY: exports._INFINITY, INF: exports.INF, SPECIAL: exports.SPECIAL, ATOM: exports.ATOM, COLLECTION: exports.COLLECTION, ALL: exports.ALL };
+ exports.default = exports.Allow;
+ }
+});
+
+// node_modules/partial-json/dist/index.js
+var require_dist = __commonJS({
+ "node_modules/partial-json/dist/index.js"(exports) {
+ "use strict";
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === void 0) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() {
+ return m[k];
+ } };
+ }
+ Object.defineProperty(o, k2, desc);
+ }) : (function(o, m, k, k2) {
+ if (k2 === void 0) k2 = k;
+ o[k2] = m[k];
+ }));
+ var __exportStar = exports && exports.__exportStar || function(m, exports2) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
+ };
+ Object.defineProperty(exports, "__esModule", { value: true });
+ exports.Allow = exports.MalformedJSON = exports.PartialJSON = exports.parseJSON = exports.parse = void 0;
+ var options_1 = require_options();
+ Object.defineProperty(exports, "Allow", { enumerable: true, get: function() {
+ return options_1.Allow;
+ } });
+ __exportStar(require_options(), exports);
+ var PartialJSON2 = class extends Error {
+ };
+ exports.PartialJSON = PartialJSON2;
+ var MalformedJSON2 = class extends Error {
+ };
+ exports.MalformedJSON = MalformedJSON2;
+ function parseJSON2(jsonString, allowPartial = options_1.Allow.ALL) {
+ if (typeof jsonString !== "string") {
+ throw new TypeError(`expecting str, got ${typeof jsonString}`);
+ }
+ if (!jsonString.trim()) {
+ throw new Error(`${jsonString} is empty`);
+ }
+ return _parseJSON2(jsonString.trim(), allowPartial);
+ }
+ exports.parseJSON = parseJSON2;
+ var _parseJSON2 = (jsonString, allow) => {
+ const length = jsonString.length;
+ let index3 = 0;
+ const markPartialJSON = (msg) => {
+ throw new PartialJSON2(`${msg} at position ${index3}`);
+ };
+ const throwMalformedError = (msg) => {
+ throw new MalformedJSON2(`${msg} at position ${index3}`);
+ };
+ const parseAny = () => {
+ skipBlank();
+ if (index3 >= length)
+ markPartialJSON("Unexpected end of input");
+ if (jsonString[index3] === '"')
+ return parseStr();
+ if (jsonString[index3] === "{")
+ return parseObj();
+ if (jsonString[index3] === "[")
+ return parseArr();
+ if (jsonString.substring(index3, index3 + 4) === "null" || options_1.Allow.NULL & allow && length - index3 < 4 && "null".startsWith(jsonString.substring(index3))) {
+ index3 += 4;
+ return null;
+ }
+ if (jsonString.substring(index3, index3 + 4) === "true" || options_1.Allow.BOOL & allow && length - index3 < 4 && "true".startsWith(jsonString.substring(index3))) {
+ index3 += 4;
+ return true;
+ }
+ if (jsonString.substring(index3, index3 + 5) === "false" || options_1.Allow.BOOL & allow && length - index3 < 5 && "false".startsWith(jsonString.substring(index3))) {
+ index3 += 5;
+ return false;
+ }
+ if (jsonString.substring(index3, index3 + 8) === "Infinity" || options_1.Allow.INFINITY & allow && length - index3 < 8 && "Infinity".startsWith(jsonString.substring(index3))) {
+ index3 += 8;
+ return Infinity;
+ }
+ if (jsonString.substring(index3, index3 + 9) === "-Infinity" || options_1.Allow._INFINITY & allow && 1 < length - index3 && length - index3 < 9 && "-Infinity".startsWith(jsonString.substring(index3))) {
+ index3 += 9;
+ return -Infinity;
+ }
+ if (jsonString.substring(index3, index3 + 3) === "NaN" || options_1.Allow.NAN & allow && length - index3 < 3 && "NaN".startsWith(jsonString.substring(index3))) {
+ index3 += 3;
+ return NaN;
+ }
+ return parseNum();
+ };
+ const parseStr = () => {
+ const start = index3;
+ let escape2 = false;
+ index3++;
+ while (index3 < length && (jsonString[index3] !== '"' || escape2 && jsonString[index3 - 1] === "\\")) {
+ escape2 = jsonString[index3] === "\\" ? !escape2 : false;
+ index3++;
+ }
+ if (jsonString.charAt(index3) == '"') {
+ try {
+ return JSON.parse(jsonString.substring(start, ++index3 - Number(escape2)));
+ } catch (e) {
+ throwMalformedError(String(e));
+ }
+ } else if (options_1.Allow.STR & allow) {
+ try {
+ return JSON.parse(jsonString.substring(start, index3 - Number(escape2)) + '"');
+ } catch (e) {
+ return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
+ }
+ }
+ markPartialJSON("Unterminated string literal");
+ };
+ const parseObj = () => {
+ index3++;
+ skipBlank();
+ const obj = {};
+ try {
+ while (jsonString[index3] !== "}") {
+ skipBlank();
+ if (index3 >= length && options_1.Allow.OBJ & allow)
+ return obj;
+ const key = parseStr();
+ skipBlank();
+ index3++;
+ try {
+ const value = parseAny();
+ obj[key] = value;
+ } catch (e) {
+ if (options_1.Allow.OBJ & allow)
+ return obj;
+ else
+ throw e;
+ }
+ skipBlank();
+ if (jsonString[index3] === ",")
+ index3++;
+ }
+ } catch (e) {
+ if (options_1.Allow.OBJ & allow)
+ return obj;
+ else
+ markPartialJSON("Expected '}' at end of object");
+ }
+ index3++;
+ return obj;
+ };
+ const parseArr = () => {
+ index3++;
+ const arr = [];
+ try {
+ while (jsonString[index3] !== "]") {
+ arr.push(parseAny());
+ skipBlank();
+ if (jsonString[index3] === ",") {
+ index3++;
+ }
+ }
+ } catch (e) {
+ if (options_1.Allow.ARR & allow) {
+ return arr;
+ }
+ markPartialJSON("Expected ']' at end of array");
+ }
+ index3++;
+ return arr;
+ };
+ const parseNum = () => {
+ if (index3 === 0) {
+ if (jsonString === "-")
+ throwMalformedError("Not sure what '-' is");
+ try {
+ return JSON.parse(jsonString);
+ } catch (e) {
+ if (options_1.Allow.NUM & allow)
+ try {
+ return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
+ } catch (e2) {
+ }
+ throwMalformedError(String(e));
+ }
+ }
+ const start = index3;
+ if (jsonString[index3] === "-")
+ index3++;
+ while (jsonString[index3] && ",]}".indexOf(jsonString[index3]) === -1)
+ index3++;
+ if (index3 == length && !(options_1.Allow.NUM & allow))
+ markPartialJSON("Unterminated number literal");
+ try {
+ return JSON.parse(jsonString.substring(start, index3));
+ } catch (e) {
+ if (jsonString.substring(start, index3) === "-")
+ markPartialJSON("Not sure what '-' is");
+ try {
+ return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
+ } catch (e2) {
+ throwMalformedError(String(e2));
+ }
+ }
+ };
+ const skipBlank = () => {
+ while (index3 < length && " \n\r ".includes(jsonString[index3])) {
+ index3++;
+ }
+ };
+ return parseAny();
+ };
+ var parse = parseJSON2;
+ exports.parse = parse;
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/json-parse.js
+function isControlCharacter(char) {
+ const codePoint = char.codePointAt(0);
+ return codePoint !== void 0 && codePoint >= 0 && codePoint <= 31;
+}
+function escapeControlCharacter(char) {
+ switch (char) {
+ case "\b":
+ return "\\b";
+ case "\f":
+ return "\\f";
+ case "\n":
+ return "\\n";
+ case "\r":
+ return "\\r";
+ case " ":
+ return "\\t";
+ default:
+ return `\\u${char.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000"}`;
+ }
+}
+function repairJson(json) {
+ let repaired = "";
+ let inString = false;
+ for (let index3 = 0; index3 < json.length; index3++) {
+ const char = json[index3];
+ if (!inString) {
+ repaired += char;
+ if (char === '"') {
+ inString = true;
+ }
+ continue;
+ }
+ if (char === '"') {
+ repaired += char;
+ inString = false;
+ continue;
+ }
+ if (char === "\\") {
+ const nextChar = json[index3 + 1];
+ if (nextChar === void 0) {
+ repaired += "\\\\";
+ continue;
+ }
+ if (nextChar === "u") {
+ const unicodeDigits = json.slice(index3 + 2, index3 + 6);
+ if (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) {
+ repaired += `\\u${unicodeDigits}`;
+ index3 += 5;
+ continue;
+ }
+ }
+ if (VALID_JSON_ESCAPES.has(nextChar)) {
+ repaired += `\\${nextChar}`;
+ index3 += 1;
+ continue;
+ }
+ repaired += "\\\\";
+ continue;
+ }
+ repaired += isControlCharacter(char) ? escapeControlCharacter(char) : char;
+ }
+ return repaired;
+}
+function parseJsonWithRepair(json) {
+ try {
+ return JSON.parse(json);
+ } catch (error) {
+ const repairedJson = repairJson(json);
+ if (repairedJson !== json) {
+ return JSON.parse(repairedJson);
+ }
+ throw error;
+ }
+}
+function parseStreamingJson(partialJson) {
+ if (!partialJson || partialJson.trim() === "") {
+ return {};
+ }
+ try {
+ return parseJsonWithRepair(partialJson);
+ } catch {
+ try {
+ const result = (0, import_partial_json.parse)(partialJson);
+ return result ?? {};
+ } catch {
+ try {
+ const result = (0, import_partial_json.parse)(repairJson(partialJson));
+ return result ?? {};
+ } catch {
+ return {};
+ }
+ }
+ }
+}
+var import_partial_json, VALID_JSON_ESCAPES;
+var init_json_parse = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/json-parse.js"() {
+ import_partial_json = __toESM(require_dist(), 1);
+ VALID_JSON_ESCAPES = /* @__PURE__ */ new Set(['"', "\\", "/", "b", "f", "n", "r", "t", "u"]);
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js
+function loadNodeOs() {
+ if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) {
+ return null;
+ }
+ return process.getBuiltinModule?.("node:os") ?? null;
+}
+function getPiUserAgent() {
+ return nodeOs ? `pi (${nodeOs.platform()} ${nodeOs.release()}; ${nodeOs.arch()})` : "pi (browser)";
+}
+var nodeOs;
+var init_pi_user_agent = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js"() {
+ nodeOs = loadNodeOs();
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/provider-env.js
+function getBunSandboxEnvValue(name) {
+ if (typeof process === "undefined" || !process.versions?.bun || Object.keys(process.env).length > 0) {
+ return void 0;
+ }
+ if (procEnvCache === null) {
+ procEnvCache = /* @__PURE__ */ new Map();
+ try {
+ const { readFileSync } = __require("node:fs");
+ const data = readFileSync("/proc/self/environ", "utf-8");
+ for (const entry of data.split("\0")) {
+ const idx = entry.indexOf("=");
+ if (idx > 0) {
+ procEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1));
+ }
+ }
+ } catch {
+ }
+ }
+ return procEnvCache.get(name);
+}
+function getProviderEnvValue(name, env) {
+ return env?.[name] || (typeof process !== "undefined" ? process.env[name] : void 0) || getBunSandboxEnvValue(name) || void 0;
+}
+var procEnvCache;
+var init_provider_env = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/provider-env.js"() {
+ procEnvCache = null;
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js
+function isProviderError(error) {
+ if (!(error instanceof Error) || !("status" in error) || !("headers" in error))
+ return false;
+ return (error.status === void 0 || typeof error.status === "number") && (error.headers === void 0 || error.headers instanceof Headers);
+}
+function isRetryableProviderError(error) {
+ const shouldRetry = error.headers?.get("x-should-retry");
+ if (shouldRetry === "true")
+ return true;
+ if (shouldRetry === "false")
+ return false;
+ if (error.status === void 0)
+ return true;
+ return error.status === 408 || error.status === 409 || error.status === 429 || typeof error.status === "number" && error.status >= 500;
+}
+function validateServerRetryDelayMs(delayMs, maxRetryDelayMs, providerErrorMessage) {
+ const maxDelayMs = maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;
+ if (maxDelayMs > 0 && delayMs > maxDelayMs) {
+ throw new Error(`Server requested ${Math.ceil(delayMs / 1e3)}s retry delay (max: ${Math.ceil(maxDelayMs / 1e3)}s). ${providerErrorMessage}`);
+ }
+ return delayMs;
+}
+function getRetryDelayMs(error, retryIndex, maxRetryDelayMs) {
+ const retryAfterMs = error.headers?.get("retry-after-ms");
+ if (retryAfterMs) {
+ const value = Number.parseFloat(retryAfterMs);
+ if (Number.isFinite(value))
+ return validateServerRetryDelayMs(value, maxRetryDelayMs, error.message);
+ }
+ const retryAfter = error.headers?.get("retry-after");
+ if (retryAfter) {
+ const seconds = Number.parseFloat(retryAfter);
+ const delayMs = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1e3;
+ if (Number.isFinite(delayMs))
+ return validateServerRetryDelayMs(delayMs, maxRetryDelayMs, error.message);
+ }
+ const exponentialDelay = Math.min(0.5 * 2 ** retryIndex, 8) * 1e3;
+ return exponentialDelay * (1 - Math.random() * 0.25);
+}
+function createAbortError() {
+ const error = new Error("Request aborted");
+ error.name = "AbortError";
+ return error;
+}
+function abortableSleep(ms, signal) {
+ return new Promise((resolve3, reject) => {
+ if (signal?.aborted) {
+ reject(createAbortError());
+ return;
+ }
+ const onAbort = () => {
+ clearTimeout(timeout);
+ reject(createAbortError());
+ };
+ const timeout = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve3();
+ }, Math.max(0, ms));
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
+async function retryProviderRequest(request, options = {}) {
+ const maxRetries = options.maxRetries ?? 0;
+ let retriesRemaining = maxRetries;
+ for (; ; ) {
+ try {
+ return await request();
+ } catch (error) {
+ if (options.signal?.aborted)
+ throw createAbortError();
+ if (retriesRemaining <= 0 || !isProviderError(error) || !isRetryableProviderError(error))
+ throw error;
+ const retryIndex = maxRetries - retriesRemaining;
+ retriesRemaining--;
+ await abortableSleep(getRetryDelayMs(error, retryIndex, options.maxRetryDelayMs), options.signal);
+ }
+ }
+}
+var DEFAULT_MAX_RETRY_DELAY_MS;
+var init_provider_retry = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js"() {
+ DEFAULT_MAX_RETRY_DELAY_MS = 6e4;
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/sanitize-unicode.js
+function sanitizeSurrogates(text) {
+ return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? schemaAllowsNull(variant));
+}
+function makeJsonSchemaNodeStrict(schema, isUnsupportedKeyword) {
+ if (!isJsonSchemaObject(schema)) {
+ throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");
+ }
+ for (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) {
+ if (schema[key] !== void 0) {
+ throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);
+ }
+ }
+ if (isUnsupportedKeyword) {
+ for (const [key, value] of Object.entries(schema)) {
+ if (isUnsupportedKeyword(key, value)) {
+ throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`);
+ }
+ }
+ }
+ if (schema.anyOf !== void 0) {
+ if (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) {
+ throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");
+ }
+ for (const variant of schema.anyOf) {
+ if (isStructuredSchema(variant)) {
+ throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");
+ }
+ makeJsonSchemaNodeStrict(variant, isUnsupportedKeyword);
+ }
+ }
+ if (schema.items !== void 0) {
+ if (Array.isArray(schema.items)) {
+ throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");
+ }
+ makeJsonSchemaNodeStrict(schema.items, isUnsupportedKeyword);
+ }
+ const isObjectSchema = schema.type === "object";
+ if (schema.properties !== void 0 && !isObjectSchema) {
+ throw new UnsupportedStrictJsonSchemaError("properties require type object");
+ }
+ if (!isObjectSchema)
+ return;
+ if (schema.additionalProperties !== void 0 && schema.additionalProperties !== false) {
+ throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");
+ }
+ if (schema.properties !== void 0 && !isJsonSchemaObject(schema.properties)) {
+ throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");
+ }
+ if (schema.required !== void 0 && (!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== "string"))) {
+ throw new UnsupportedStrictJsonSchemaError("object required must be a string array");
+ }
+ const properties = schema.properties ?? {};
+ const propertyNames = Object.keys(properties);
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
+ if ([...required].some((key) => !propertyNames.includes(key))) {
+ throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");
+ }
+ for (const [key, property] of Object.entries(properties)) {
+ makeJsonSchemaNodeStrict(property, isUnsupportedKeyword);
+ if (!required.has(key) && !schemaAllowsNull(property)) {
+ properties[key] = { anyOf: [property, { type: "null" }] };
+ }
+ }
+ schema.required = propertyNames;
+ schema.additionalProperties = false;
+}
+function makeStrictJsonSchema(schema, isUnsupportedKeyword) {
+ const cloned = structuredClone(schema);
+ if (!isJsonSchemaObject(cloned)) {
+ throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
+ }
+ makeJsonSchemaNodeStrict(cloned, isUnsupportedKeyword);
+ if (cloned.type !== "object") {
+ throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
+ }
+ return cloned;
+}
+function getJsonSchemaToolParameters(tool, strict) {
+ return strict === true ? makeStrictJsonSchema(tool.parameters) : tool.parameters;
+}
+function getGrammarToolInput(toolName, arguments_, inputProperty) {
+ const input = arguments_[inputProperty];
+ if (typeof input !== "string") {
+ throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);
+ }
+ return input;
+}
+function appendGrammarToolInputJsonDelta(buffer, inputProperty, nextInput, close) {
+ if (buffer.closed) {
+ if (close && nextInput === buffer.input)
+ return void 0;
+ throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);
+ }
+ if (!nextInput.startsWith(buffer.input)) {
+ throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);
+ }
+ const inputDelta = nextInput.slice(buffer.input.length);
+ if (!close && inputDelta.length === 0)
+ return void 0;
+ let delta = "";
+ if (!buffer.started) {
+ delta += `{${JSON.stringify(inputProperty)}:"`;
+ buffer.started = true;
+ }
+ delta += JSON.stringify(inputDelta).slice(1, -1);
+ buffer.input = nextInput;
+ if (close) {
+ delta += '"}';
+ buffer.closed = true;
+ }
+ return delta;
+}
+function inferGrammarInputProperty(tool) {
+ const schema = tool.parameters;
+ if (schema.type !== "object") {
+ throw new Error("grammar constrained sampling requires an object parameter schema");
+ }
+ if (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== "string") {
+ throw new Error("grammar constrained sampling requires exactly one required string property");
+ }
+ const inputProperty = schema.required[0];
+ if (!schema.properties?.[inputProperty]) {
+ throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);
+ }
+ if (schema.properties[inputProperty]?.type !== "string") {
+ throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);
+ }
+ return inputProperty;
+}
+function resolveJsonSchemaStrictSampling(tool, supportsStrictMode, isUnsupportedKeyword) {
+ const config = tool.constrainedSampling;
+ if (!config || config.type !== "json_schema")
+ return void 0;
+ if (supportsStrictMode) {
+ try {
+ makeStrictJsonSchema(tool.parameters, isUnsupportedKeyword);
+ return true;
+ } catch (error) {
+ if (!(error instanceof UnsupportedStrictJsonSchemaError))
+ throw error;
+ if (config.strict !== "require")
+ return void 0;
+ throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`);
+ }
+ }
+ if (config.strict === "require") {
+ throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);
+ }
+ return void 0;
+}
+function resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools) {
+ const config = tool.constrainedSampling;
+ if (!config || config.type !== "grammar") {
+ return void 0;
+ }
+ if (!supportsOpenAIGrammarTools) {
+ return void 0;
+ }
+ const larkDefinition = config.variants.openai_lark;
+ const regexDefinition = config.variants.openai_regex;
+ const hasLarkDefinition = typeof larkDefinition === "string" && larkDefinition.trim().length > 0;
+ const hasRegexDefinition = typeof regexDefinition === "string" && regexDefinition.trim().length > 0;
+ if (!hasLarkDefinition && !hasRegexDefinition) {
+ throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);
+ }
+ try {
+ return {
+ format: hasLarkDefinition ? "lark" : "regex",
+ definition: hasLarkDefinition ? larkDefinition : regexDefinition,
+ inputProperty: inferGrammarInputProperty(tool)
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`);
+ }
+}
+function createGrammarToolInputProperties(tools, supportsOpenAIGrammarTools) {
+ const properties = /* @__PURE__ */ new Map();
+ for (const tool of tools ?? []) {
+ const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
+ if (grammar) {
+ properties.set(tool.name, grammar.inputProperty);
+ }
+ }
+ return properties;
+}
+var UnsupportedStrictJsonSchemaError, UNSUPPORTED_STRICT_SCHEMA_KEYS;
+var init_constrained_sampling = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.js"() {
+ UnsupportedStrictJsonSchemaError = class extends Error {
+ };
+ UNSUPPORTED_STRICT_SCHEMA_KEYS = [
+ "$ref",
+ "$defs",
+ "definitions",
+ "allOf",
+ "oneOf",
+ "patternProperties",
+ "dependentSchemas",
+ "dependencies",
+ "unevaluatedProperties",
+ "propertyNames",
+ "contains",
+ "prefixItems",
+ "not",
+ "if",
+ "then",
+ "else"
+ ];
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/api/github-copilot-headers.js
+function inferCopilotInitiator(messages) {
+ const last = messages[messages.length - 1];
+ return last && last.role !== "user" ? "agent" : "user";
+}
+function hasCopilotVisionInput(messages) {
+ return messages.some((msg) => {
+ if (msg.role === "user" && Array.isArray(msg.content)) {
+ return msg.content.some((c) => c.type === "image");
+ }
+ if (msg.role === "toolResult" && Array.isArray(msg.content)) {
+ return msg.content.some((c) => c.type === "image");
+ }
+ return false;
+ });
+}
+function buildCopilotDynamicHeaders(params) {
+ const headers = {
+ "X-Initiator": inferCopilotInitiator(params.messages),
+ "Openai-Intent": "conversation-edits"
+ };
+ if (params.hasImages) {
+ headers["Copilot-Vision-Request"] = "true";
+ }
+ return headers;
+}
+var init_github_copilot_headers = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/github-copilot-headers.js"() {
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.js
+function clampOpenAIPromptCacheKey(key) {
+ if (key === void 0)
+ return void 0;
+ const chars = Array.from(key);
+ if (chars.length <= OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH)
+ return key;
+ return chars.slice(0, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH).join("");
+}
+var OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH;
+var init_openai_prompt_cache = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.js"() {
+ OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/utils/estimate.js
+function calculateContextTokens(usage) {
+ return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
+}
+function safeJsonStringify2(value) {
+ try {
+ return JSON.stringify(value) ?? "undefined";
+ } catch {
+ return "[unserializable]";
+ }
+}
+function estimateTextAndImageContentChars(content) {
+ if (typeof content === "string")
+ return content.length;
+ let chars = 0;
+ for (const block of content)
+ chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;
+ return chars;
+}
+function estimateTextTokens(text) {
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
+}
+function estimateTextAndImageContentTokens(content) {
+ return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
+}
+function estimateMessageTokens(message) {
+ let chars = 0;
+ if (message.role === "system") {
+ return estimateTextTokens(getSystemMessageText(message)) + estimateToolsTokens(message.toolsAdded) + estimateToolsTokens(message.toolsRemoved);
+ }
+ if (message.role === "user")
+ return estimateTextAndImageContentTokens(message.content);
+ if (message.role === "toolResult")
+ return estimateTextAndImageContentTokens(message.content);
+ for (const block of message.content) {
+ if (block.type === "text") {
+ chars += block.text.length;
+ } else if (block.type === "thinking") {
+ chars += block.thinking.length;
+ } else {
+ chars += block.name.length + safeJsonStringify2(block.arguments).length;
+ }
+ }
+ return Math.ceil(chars / CHARS_PER_TOKEN);
+}
+function getLastAssistantUsageInfo(messages) {
+ let latestPrefixTimestamp = Number.NEGATIVE_INFINITY;
+ let usageInfo;
+ for (let i = 0; i < messages.length; i++) {
+ const message = messages[i];
+ if (message.role === "assistant") {
+ const assistant = message;
+ const usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp;
+ if (usageAppliesToPrefix && assistant.stopReason !== "aborted" && assistant.stopReason !== "error" && calculateContextTokens(assistant.usage) > 0) {
+ usageInfo = { usage: assistant.usage, index: i };
+ }
+ }
+ latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);
+ }
+ return usageInfo;
+}
+function estimateContextTokens(context) {
+ const messages = "messages" in context ? context.messages : context;
+ const usageInfo = getLastAssistantUsageInfo(messages);
+ if (usageInfo) {
+ const usageTokens = calculateContextTokens(usageInfo.usage);
+ let trailingTokens = 0;
+ for (let i = usageInfo.index + 1; i < messages.length; i++) {
+ trailingTokens += estimateMessageTokens(messages[i]);
+ }
+ return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };
+ }
+ let tokens = 0;
+ for (const message of messages)
+ tokens += estimateMessageTokens(message);
+ return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };
+}
+function estimateToolsTokens(tools) {
+ if (!tools || tools.length === 0)
+ return 0;
+ return estimateTextTokens(safeJsonStringify2(tools));
+}
+var CHARS_PER_TOKEN, ESTIMATED_IMAGE_CHARS;
+var init_estimate = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/utils/estimate.js"() {
+ init_text();
+ CHARS_PER_TOKEN = 4;
+ ESTIMATED_IMAGE_CHARS = 4800;
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/api/simple-options.js
+function clampMaxTokensToContext(model, context, maxTokens) {
+ if (model.contextWindow <= 0)
+ return Math.max(MIN_MAX_TOKENS, maxTokens);
+ const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;
+ return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));
+}
+function resolveSamplingParams(model, thinkingLevel, requestParams) {
+ const effectiveThinkingLevel = clampThinkingLevel(model, thinkingLevel);
+ const thinkingLevelParams = model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];
+ return model.samplingParams || thinkingLevelParams || requestParams ? { ...model.samplingParams, ...thinkingLevelParams, ...requestParams } : void 0;
+}
+function buildBaseOptions(model, context, options, apiKey) {
+ const samplingParams = resolveSamplingParams(model, options?.reasoning ?? "off", options?.samplingParams);
+ return {
+ temperature: options?.temperature,
+ samplingParams,
+ maxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens),
+ signal: options?.signal,
+ telemetryContext: options?.telemetryContext,
+ apiKey: apiKey || options?.apiKey,
+ fetch: options?.fetch,
+ transport: options?.transport,
+ cacheRetention: options?.cacheRetention,
+ sessionId: options?.sessionId,
+ headers: options?.headers,
+ onPayload: options?.onPayload,
+ onResponse: options?.onResponse,
+ onProviderStreamEvent: options?.onProviderStreamEvent,
+ timeoutMs: options?.timeoutMs,
+ websocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,
+ maxRetries: options?.maxRetries,
+ maxRetryDelayMs: options?.maxRetryDelayMs,
+ metadata: options?.metadata,
+ env: options?.env
+ };
+}
+function clampReasoning(effort) {
+ return effort === "xhigh" || effort === "max" ? "high" : effort;
+}
+function thinkingBudgetForLevel(reasoningLevel, customBudgets) {
+ const budgets = { ...DEFAULT_THINKING_BUDGETS, ...customBudgets };
+ const level = clampReasoning(reasoningLevel);
+ return budgets[level];
+}
+function clampThinkingBudgetToAnswerRoom(thinkingBudget, ceiling) {
+ return Math.min(thinkingBudget, Math.max(0, ceiling - MIN_ANSWER_TOKENS));
+}
+var CONTEXT_SAFETY_TOKENS, MIN_MAX_TOKENS, MIN_ANSWER_TOKENS, DEFAULT_THINKING_BUDGETS;
+var init_simple_options = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/simple-options.js"() {
+ init_models();
+ init_estimate();
+ CONTEXT_SAFETY_TOKENS = 4096;
+ MIN_MAX_TOKENS = 1;
+ MIN_ANSWER_TOKENS = 1024;
+ DEFAULT_THINKING_BUDGETS = {
+ minimal: 1024,
+ low: 2048,
+ medium: 8192,
+ high: 16384
+ };
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js
+function replaceImagesWithPlaceholder(content, placeholder) {
+ const result = [];
+ let previousWasPlaceholder = false;
+ for (const block of content) {
+ if (block.type === "image") {
+ if (!previousWasPlaceholder) {
+ result.push({ type: "text", text: placeholder });
+ }
+ previousWasPlaceholder = true;
+ continue;
+ }
+ result.push(block);
+ previousWasPlaceholder = block.text === placeholder;
+ }
+ return result;
+}
+function downgradeUnsupportedImages(messages, model) {
+ if (model.input.includes("image")) {
+ return messages;
+ }
+ return messages.map((msg) => {
+ if (msg.role === "user" && Array.isArray(msg.content)) {
+ return {
+ ...msg,
+ content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER)
+ };
+ }
+ if (msg.role === "toolResult") {
+ return {
+ ...msg,
+ content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER)
+ };
+ }
+ return msg;
+ });
+}
+function transformMessages(messages, model, normalizeToolCallId) {
+ const toolCallIdMap = /* @__PURE__ */ new Map();
+ const normalizedMessages = messages.map((msg) => msg.content == null ? { ...msg, content: [] } : msg);
+ const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);
+ const transformed = imageAwareMessages.map((msg) => {
+ if (msg.role === "system" || msg.role === "user") {
+ return msg;
+ }
+ if (msg.role === "toolResult") {
+ const normalizedId = toolCallIdMap.get(msg.toolCallId);
+ if (normalizedId && normalizedId !== msg.toolCallId) {
+ return { ...msg, toolCallId: normalizedId };
+ }
+ return msg;
+ }
+ if (msg.role === "assistant") {
+ const assistantMsg = msg;
+ const isSameModel = assistantMsg.provider === model.provider && assistantMsg.api === model.api && assistantMsg.model === model.id;
+ const transformedContent = assistantMsg.content.flatMap((block) => {
+ if (block.type === "thinking") {
+ if (block.redacted) {
+ return isSameModel ? block : [];
+ }
+ if (isSameModel && block.thinkingSignature)
+ return block;
+ if (!block.thinking || block.thinking.trim() === "")
+ return [];
+ if (isSameModel)
+ return block;
+ return {
+ type: "text",
+ text: block.thinking
+ };
+ }
+ if (block.type === "text") {
+ if (isSameModel)
+ return block;
+ return {
+ type: "text",
+ text: block.text
+ };
+ }
+ if (block.type === "toolCall") {
+ const toolCall = block;
+ let normalizedToolCall = toolCall;
+ if (!isSameModel && toolCall.thoughtSignature) {
+ normalizedToolCall = { ...toolCall };
+ delete normalizedToolCall.thoughtSignature;
+ }
+ if (!isSameModel && normalizeToolCallId) {
+ const normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);
+ if (normalizedId !== toolCall.id) {
+ toolCallIdMap.set(toolCall.id, normalizedId);
+ normalizedToolCall = { ...normalizedToolCall, id: normalizedId };
+ }
+ }
+ return normalizedToolCall;
+ }
+ return block;
+ });
+ return {
+ ...assistantMsg,
+ content: transformedContent
+ };
+ }
+ return msg;
+ });
+ const result = [];
+ let pendingToolCalls = [];
+ let existingToolResultIds = /* @__PURE__ */ new Set();
+ const heldSystemMessages = [];
+ const closePendingToolCalls = () => {
+ if (pendingToolCalls.length > 0) {
+ for (const tc of pendingToolCalls) {
+ if (!existingToolResultIds.has(tc.id)) {
+ result.push({
+ role: "toolResult",
+ toolCallId: tc.id,
+ toolName: tc.name,
+ content: [{ type: "text", text: "No result provided" }],
+ isError: true,
+ timestamp: Date.now()
+ });
+ }
+ }
+ pendingToolCalls = [];
+ existingToolResultIds = /* @__PURE__ */ new Set();
+ }
+ result.push(...heldSystemMessages);
+ heldSystemMessages.length = 0;
+ };
+ for (let i = 0; i < transformed.length; i++) {
+ const msg = transformed[i];
+ if (msg.role === "assistant") {
+ closePendingToolCalls();
+ const assistantMsg = msg;
+ if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {
+ continue;
+ }
+ const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall");
+ if (toolCalls.length > 0) {
+ pendingToolCalls = toolCalls;
+ existingToolResultIds = /* @__PURE__ */ new Set();
+ }
+ result.push(msg);
+ } else if (msg.role === "toolResult") {
+ existingToolResultIds.add(msg.toolCallId);
+ result.push(msg);
+ } else if (msg.role === "system") {
+ if (pendingToolCalls.length > 0) {
+ heldSystemMessages.push(msg);
+ } else {
+ result.push(msg);
+ }
+ } else if (msg.role === "user") {
+ closePendingToolCalls();
+ result.push(msg);
+ } else {
+ result.push(msg);
+ }
+ }
+ closePendingToolCalls();
+ return result;
+}
+var NON_VISION_USER_IMAGE_PLACEHOLDER, NON_VISION_TOOL_IMAGE_PLACEHOLDER;
+var init_transform_messages = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js"() {
+ NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
+ NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js
+var openai_completions_exports = {};
+__export(openai_completions_exports, {
+ convertMessages: () => convertMessages,
+ stream: () => stream,
+ streamSimple: () => streamSimple
+});
+function hasHeader(headers, name) {
+ if (!headers)
+ return false;
+ const expected = name.toLowerCase();
+ for (const [key, value] of Object.entries(headers)) {
+ if (key.toLowerCase() === expected && value !== null && value.trim().length > 0)
+ return true;
+ }
+ return false;
+}
+function getClientApiKey(provider, apiKey, headers) {
+ if (apiKey)
+ return apiKey;
+ if (hasHeader(headers, "authorization") || hasHeader(headers, "cf-aig-authorization"))
+ return "unused";
+ throw new Error(`No API key for provider: ${provider}`);
+}
+function hasToolHistory(messages) {
+ for (const msg of messages) {
+ if (msg.role === "toolResult") {
+ return true;
+ }
+ if (msg.role === "assistant") {
+ if (msg.content.some((block) => block.type === "toolCall")) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+function isTextContentBlock(block) {
+ return block.type === "text";
+}
+function isThinkingContentBlock(block) {
+ return block.type === "thinking";
+}
+function isToolCallBlock(block) {
+ return block.type === "toolCall";
+}
+function isImageContentBlock(block) {
+ return block.type === "image";
+}
+function isReasoningDetailObject(detail) {
+ return typeof detail === "object" && detail !== null && !Array.isArray(detail);
+}
+function hasValidCommonReasoningDetailFields(candidate) {
+ return (candidate.id === void 0 || candidate.id === null || typeof candidate.id === "string") && (candidate.format === void 0 || typeof candidate.format === "string") && (candidate.index === void 0 || typeof candidate.index === "number");
+}
+function isOpenAIReasoningDetail(detail) {
+ if (!isReasoningDetailObject(detail) || !hasValidCommonReasoningDetailFields(detail)) {
+ return false;
+ }
+ switch (detail.type) {
+ case "reasoning.summary":
+ return typeof detail.summary === "string";
+ case "reasoning.encrypted":
+ return typeof detail.data === "string";
+ case "reasoning.text":
+ return typeof detail.text === "string" && (detail.signature === void 0 || detail.signature === null || typeof detail.signature === "string");
+ default:
+ return false;
+ }
+}
+function parseOpenAIReasoningDetails(signature) {
+ if (!signature)
+ return void 0;
+ try {
+ const parsed = JSON.parse(signature);
+ return Array.isArray(parsed) && parsed.length > 0 && parsed.every(isOpenAIReasoningDetail) ? parsed : void 0;
+ } catch {
+ return void 0;
+ }
+}
+function parseLegacyEncryptedReasoningDetail(signature) {
+ if (!signature)
+ return void 0;
+ try {
+ const parsed = JSON.parse(signature);
+ return isOpenAIReasoningDetail(parsed) && parsed.type === "reasoning.encrypted" && typeof parsed.id === "string" && parsed.id.length > 0 && parsed.data.length > 0 ? parsed : void 0;
+ } catch {
+ return void 0;
+ }
+}
+function fillMissingCommonReasoningDetailFields(target, source) {
+ target.id ??= source.id;
+ target.format ||= source.format;
+ target.index ??= source.index;
+}
+function appendOpenAIReasoningDetail(details, detail) {
+ const lastDetail = details[details.length - 1];
+ if (detail.type === "reasoning.text" && lastDetail?.type === "reasoning.text") {
+ lastDetail.text += detail.text;
+ lastDetail.signature ||= detail.signature;
+ fillMissingCommonReasoningDetailFields(lastDetail, detail);
+ return;
+ }
+ if (detail.type === "reasoning.summary" && lastDetail?.type === "reasoning.summary") {
+ lastDetail.summary += detail.summary;
+ fillMissingCommonReasoningDetailFields(lastDetail, detail);
+ return;
+ }
+ details.push({ ...detail });
+}
+function isOpenAICompletionsReasoningField(field) {
+ return OPENAI_COMPLETIONS_REASONING_FIELDS.includes(field);
+}
+function resolveCacheRetention(cacheRetention, env) {
+ if (cacheRetention) {
+ return cacheRetention;
+ }
+ if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") {
+ return "long";
+ }
+ return "short";
+}
+function createClient(model, context, apiKey, optionsHeaders, fetch2, sessionId, compat = getCompat(model)) {
+ const headers = { "User-Agent": getPiUserAgent(), ...model.headers };
+ if (model.provider === "github-copilot") {
+ const hasImages = hasCopilotVisionInput(context.messages);
+ const copilotHeaders = buildCopilotDynamicHeaders({
+ messages: context.messages,
+ hasImages
+ });
+ Object.assign(headers, copilotHeaders);
+ }
+ if (sessionId && compat.sendSessionAffinityHeaders) {
+ if (compat.sessionAffinityFormat === "openrouter") {
+ headers["x-session-id"] = sessionId;
+ } else {
+ if (compat.sessionAffinityFormat === "openai") {
+ headers.session_id = sessionId;
+ }
+ headers["x-client-request-id"] = sessionId;
+ headers["x-session-affinity"] = sessionId;
+ }
+ }
+ if (optionsHeaders) {
+ Object.assign(headers, optionsHeaders);
+ }
+ return new OpenAI({
+ apiKey,
+ baseURL: model.baseUrl,
+ dangerouslyAllowBrowser: true,
+ fetch: fetch2,
+ defaultHeaders: headers
+ });
+}
+function buildParams(model, context, options, compat = getCompat(model), cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env), grammarToolInputProperties = createGrammarToolInputProperties(getDeclaredTools(context.messages), compat.supportsOpenAIGrammarTools)) {
+ const transcriptTools = resolveTranscriptTools(context.messages, compat.supportsMidConvoSystemMessages === true && compat.supportsMidConvoToolAdditions === true);
+ const messages = convertMessages(model, context, compat, {
+ grammarToolInputProperties
+ });
+ const cacheControl = getCompatCacheControl(compat, cacheRetention);
+ const params = {
+ model: model.id,
+ messages,
+ stream: true,
+ prompt_cache_key: model.baseUrl.includes("api.openai.com") && cacheRetention !== "none" || cacheRetention === "long" && compat.supportsLongCacheRetention ? clampOpenAIPromptCacheKey(options?.sessionId) : void 0,
+ prompt_cache_retention: cacheRetention === "long" && compat.supportsLongCacheRetention ? "24h" : void 0
+ };
+ if (compat.supportsUsageInStreaming !== false) {
+ params.stream_options = { include_usage: true };
+ }
+ if (compat.supportsStore) {
+ params.store = false;
+ }
+ if (options?.maxTokens) {
+ if (compat.maxTokensField === "max_tokens") {
+ params.max_tokens = options.maxTokens;
+ } else {
+ params.max_completion_tokens = options.maxTokens;
+ }
+ }
+ if (options?.temperature !== void 0) {
+ params.temperature = options.temperature;
+ }
+ if (transcriptTools.requestTools.length > 0) {
+ params.tools = convertTools(transcriptTools.requestTools, compat);
+ if (compat.zaiToolStream) {
+ params.tool_stream = true;
+ }
+ } else if (hasToolHistory(context.messages)) {
+ params.tools = [];
+ }
+ if (cacheControl) {
+ applyAnthropicCacheControl(messages, params.tools, cacheControl);
+ }
+ if (options?.toolChoice) {
+ params.tool_choice = options.toolChoice;
+ }
+ if (compat.vllmPriority !== void 0) {
+ params.priority = compat.vllmPriority;
+ }
+ const thinkingTokenBudgetField = resolveThinkingTokenBudgetField(compat);
+ const thinkingBudget = resolveClampedThinkingBudget(model, options, params);
+ if (compat.thinkingFormat === "zai" && model.reasoning) {
+ const zaiParams = params;
+ zaiParams.thinking = options?.reasoningEffort ? { type: "enabled", clear_thinking: false } : { type: "disabled" };
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
+ const mappedEffort = model.thinkingLevelMap?.[options.reasoningEffort];
+ const effort = mappedEffort === void 0 ? options.reasoningEffort : mappedEffort;
+ if (typeof effort === "string") {
+ zaiParams.reasoning_effort = effort;
+ }
+ }
+ } else if (compat.thinkingFormat === "qwen" && model.reasoning) {
+ params.enable_thinking = !!options?.reasoningEffort;
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
+ const effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
+ if (typeof effort === "string") {
+ params.reasoning_effort = effort;
+ }
+ }
+ } else if (compat.thinkingFormat === "qwen-chat-template" && model.reasoning) {
+ params.chat_template_kwargs = {
+ enable_thinking: !!options?.reasoningEffort,
+ preserve_thinking: true
+ };
+ } else if (compat.thinkingFormat === "chat-template" && model.reasoning) {
+ const chatTemplateKwargs = buildChatTemplateValues(model, options, compat.chatTemplateKwargs, thinkingBudget);
+ if (chatTemplateKwargs) {
+ params.chat_template_kwargs = chatTemplateKwargs;
+ }
+ } else if (compat.thinkingFormat === "baseten" && model.reasoning) {
+ const basetenParams = params;
+ const chatTemplateArgs = buildChatTemplateValues(model, options, compat.chatTemplateArgs, thinkingBudget);
+ if (chatTemplateArgs) {
+ basetenParams.chat_template_args = chatTemplateArgs;
+ }
+ if (compat.supportsReasoningEffort) {
+ const requestedEffort = options?.reasoningEffort;
+ const mappedEffort = requestedEffort ? model.thinkingLevelMap?.[requestedEffort] : model.thinkingLevelMap?.off;
+ const effort = mappedEffort === void 0 ? requestedEffort : mappedEffort;
+ if (typeof effort === "string") {
+ basetenParams.reasoning_effort = effort;
+ }
+ }
+ } else if (compat.thinkingFormat === "deepseek" && model.reasoning) {
+ if (options?.reasoningEffort) {
+ params.thinking = { type: "enabled" };
+ } else if (model.thinkingLevelMap?.off !== null) {
+ params.thinking = { type: "disabled" };
+ }
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
+ params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
+ }
+ } else if (compat.thinkingFormat === "openrouter" && model.reasoning) {
+ const openRouterParams = params;
+ if (options?.reasoningEffort) {
+ openRouterParams.reasoning = {
+ effort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort
+ };
+ } else if (model.thinkingLevelMap?.off !== null) {
+ openRouterParams.reasoning = { effort: model.thinkingLevelMap?.off ?? "none" };
+ }
+ } else if (compat.thinkingFormat === "ant-ling" && model.reasoning && options?.reasoningEffort) {
+ const effort = model.thinkingLevelMap?.[options.reasoningEffort];
+ if (typeof effort === "string") {
+ params.reasoning = { effort };
+ }
+ } else if (compat.thinkingFormat === "together" && model.reasoning) {
+ const togetherParams = params;
+ togetherParams.reasoning = { enabled: !!options?.reasoningEffort };
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
+ togetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
+ }
+ } else if (compat.thinkingFormat === "string-thinking" && model.reasoning) {
+ const stringThinkingParams = params;
+ if (options?.reasoningEffort) {
+ stringThinkingParams.thinking = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
+ } else if (model.thinkingLevelMap?.off !== null) {
+ stringThinkingParams.thinking = model.thinkingLevelMap?.off ?? "none";
+ }
+ } else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
+ params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
+ } else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
+ const offValue = model.thinkingLevelMap?.off;
+ if (typeof offValue === "string") {
+ params.reasoning_effort = offValue;
+ }
+ }
+ if (thinkingTokenBudgetField && thinkingBudget !== void 0) {
+ Object.assign(params, { [thinkingTokenBudgetField]: thinkingBudget });
+ }
+ if (model.compat?.openRouterRouting) {
+ params.provider = model.compat.openRouterRouting;
+ }
+ if (model.compat?.vercelGatewayRouting) {
+ const routing = model.compat.vercelGatewayRouting;
+ if (routing.only || routing.order) {
+ const gatewayOptions = {};
+ if (routing.only)
+ gatewayOptions.only = routing.only;
+ if (routing.order)
+ gatewayOptions.order = routing.order;
+ params.providerOptions = { gateway: gatewayOptions };
+ }
+ }
+ const samplingParams = resolveSamplingParams(model, options?.reasoningEffort ?? "off", options?.samplingParams);
+ if (samplingParams) {
+ Object.assign(params, samplingParams);
+ }
+ return params;
+}
+function resolveThinkingTokenBudgetField(compat) {
+ if (compat.thinkingTokenBudgetField)
+ return compat.thinkingTokenBudgetField;
+ if (compat.supportsThinkingTokenBudget)
+ return "thinking_token_budget";
+ return void 0;
+}
+function resolveClampedThinkingBudget(model, options, params) {
+ if (!options?.reasoningEffort || !model.reasoning)
+ return void 0;
+ const ceiling = params.max_tokens ?? params.max_completion_tokens ?? model.maxTokens;
+ const budget = clampThinkingBudgetToAnswerRoom(thinkingBudgetForLevel(options.reasoningEffort, options.thinkingBudgets), ceiling);
+ return budget > 0 ? budget : void 0;
+}
+function buildChatTemplateValues(model, options, values, thinkingBudget) {
+ const resolvedValues = {};
+ for (const [key, value] of Object.entries(values)) {
+ const resolved = resolveChatTemplateKwargValue(model, options, value, thinkingBudget);
+ if (resolved !== void 0) {
+ resolvedValues[key] = resolved;
+ }
+ }
+ return Object.keys(resolvedValues).length > 0 ? resolvedValues : void 0;
+}
+function resolveChatTemplateKwargValue(model, options, value, thinkingBudget) {
+ if (typeof value !== "object" || value === null) {
+ return value;
+ }
+ const reasoningEffort = options?.reasoningEffort;
+ if (!reasoningEffort && value.omitWhenOff) {
+ return void 0;
+ }
+ if (value.$var === "thinking.enabled") {
+ return !!reasoningEffort;
+ }
+ if (value.$var === "thinking.budget") {
+ return thinkingBudget;
+ }
+ const mappedValue = reasoningEffort ? model.thinkingLevelMap?.[reasoningEffort] : model.thinkingLevelMap?.off;
+ return mappedValue === void 0 ? reasoningEffort : typeof mappedValue === "string" ? mappedValue : void 0;
+}
+function getCompatCacheControl(compat, cacheRetention) {
+ if (compat.cacheControlFormat !== "anthropic" || cacheRetention === "none") {
+ return void 0;
+ }
+ const ttl = cacheRetention === "long" && compat.supportsLongCacheRetention ? "1h" : void 0;
+ return { type: "ephemeral", ...ttl ? { ttl } : {} };
+}
+function applyAnthropicCacheControl(messages, tools, cacheControl) {
+ addCacheControlToSystemPrompt(messages, cacheControl);
+ addCacheControlToLastTool(tools, cacheControl);
+ addCacheControlToLastConversationMessage(messages, cacheControl);
+}
+function addCacheControlToSystemPrompt(messages, cacheControl) {
+ for (const message of messages) {
+ if (message.role === "system" || message.role === "developer") {
+ addCacheControlToInstructionMessage(message, cacheControl);
+ return;
+ }
+ }
+}
+function addCacheControlToLastConversationMessage(messages, cacheControl) {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i];
+ if (message.role === "user" || message.role === "assistant" || message.role === "tool") {
+ if (addCacheControlToMessage(message, cacheControl)) {
+ return;
+ }
+ }
+ }
+}
+function addCacheControlToLastTool(tools, cacheControl) {
+ if (!tools || tools.length === 0) {
+ return;
+ }
+ const lastTool = tools[tools.length - 1];
+ lastTool.cache_control = cacheControl;
+}
+function addCacheControlToInstructionMessage(message, cacheControl) {
+ return addCacheControlToTextContent(message, cacheControl);
+}
+function addCacheControlToMessage(message, cacheControl) {
+ if (message.role === "user" || message.role === "assistant" || message.role === "tool") {
+ return addCacheControlToTextContent(message, cacheControl);
+ }
+ return false;
+}
+function addCacheControlToTextContent(message, cacheControl) {
+ const content = message.content;
+ if (typeof content === "string") {
+ if (content.length === 0) {
+ return false;
+ }
+ message.content = [
+ {
+ type: "text",
+ text: content,
+ cache_control: cacheControl
+ }
+ ];
+ return true;
+ }
+ if (!Array.isArray(content)) {
+ return false;
+ }
+ for (let i = content.length - 1; i >= 0; i--) {
+ const part = content[i];
+ if (part?.type === "text") {
+ const textPart = part;
+ textPart.cache_control = cacheControl;
+ return true;
+ }
+ }
+ return false;
+}
+function convertMessages(model, context, compat, options) {
+ const normalizedContext = resolveTranscript(context, compat.supportsMidConvoSystemMessages);
+ const params = [];
+ const normalizeToolCallId = (id) => {
+ if (id.includes("|")) {
+ const separatorIndex = id.indexOf("|");
+ const callId = id.slice(0, separatorIndex).replace(/[^a-zA-Z0-9_-]/g, "_");
+ const itemId = id.slice(separatorIndex + 1).replace(/[^a-zA-Z0-9_-]/g, "_");
+ const combinedId = itemId.length > 0 ? `${callId}_${itemId}` : callId;
+ if (combinedId.length <= 40) {
+ return combinedId;
+ }
+ const hash = shortHash(id).slice(0, 8);
+ const prefix = callId.slice(0, Math.max(1, 40 - hash.length - 1));
+ return `${prefix}_${hash}`;
+ }
+ if (model.provider === "openai")
+ return id.length > 40 ? id.slice(0, 40) : id;
+ return id;
+ };
+ const transformedMessages = transformMessages(normalizedContext.messages, model, (id) => normalizeToolCallId(id));
+ const transcriptTools = resolveTranscriptTools(normalizedContext.messages, compat.supportsMidConvoSystemMessages === true && compat.supportsMidConvoToolAdditions === true);
+ const instructionRole = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system";
+ let lastRole = null;
+ for (let i = 0; i < transformedMessages.length; i++) {
+ const msg = transformedMessages[i];
+ if (compat.requiresAssistantAfterToolResult && lastRole === "toolResult" && msg.role === "user") {
+ params.push({
+ role: "assistant",
+ content: "I have processed the tool results."
+ });
+ }
+ if (msg.role === "system") {
+ const addedTools = i > 0 && transcriptTools.anchorsAdditions ? msg.toolsAdded ?? [] : [];
+ if (addedTools.length > 0) {
+ const kimiToolMessage = {
+ role: "system",
+ tools: convertTools(addedTools, compat)
+ };
+ params.push(kimiToolMessage);
+ }
+ const text = i === 0 ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg);
+ if (text.length > 0) {
+ params.push({ role: instructionRole, content: sanitizeSurrogates(text) });
+ }
+ } else if (msg.role === "user") {
+ if (typeof msg.content === "string") {
+ params.push({
+ role: "user",
+ content: sanitizeSurrogates(msg.content)
+ });
+ } else {
+ const content = msg.content.filter((item) => item.type !== "text" || item.text.length > 0).map((item) => {
+ if (item.type === "text") {
+ return {
+ type: "text",
+ text: sanitizeSurrogates(item.text)
+ };
+ } else {
+ return {
+ type: "image_url",
+ image_url: {
+ url: `data:${item.mimeType};base64,${item.data}`
+ }
+ };
+ }
+ });
+ if (content.length === 0)
+ continue;
+ params.push({
+ role: "user",
+ content
+ });
+ }
+ } else if (msg.role === "assistant") {
+ const assistantMsg = {
+ role: "assistant",
+ content: compat.requiresAssistantAfterToolResult ? "" : null
+ };
+ const assistantTextParts = msg.content.filter(isTextContentBlock).filter((block) => block.text.trim().length > 0).map((block) => ({
+ type: "text",
+ text: sanitizeSurrogates(block.text)
+ }));
+ const assistantText = assistantTextParts.map((part) => part.text).join("");
+ const thinkingBlocks = msg.content.filter(isThinkingContentBlock);
+ const toolCalls = msg.content.filter(isToolCallBlock);
+ const signedReasoningDetails = thinkingBlocks.map((block) => parseOpenAIReasoningDetails(block.thinkingSignature)).find((details) => details !== void 0);
+ const legacyReasoningDetails = toolCalls.map((toolCall) => parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature)).filter((detail) => detail !== void 0);
+ const preservedReasoningDetails = signedReasoningDetails ?? (legacyReasoningDetails.length > 0 ? legacyReasoningDetails : void 0);
+ const nonEmptyThinkingBlocks = thinkingBlocks.filter((block) => block.thinking.trim().length > 0);
+ if (nonEmptyThinkingBlocks.length > 0) {
+ if (compat.requiresThinkingAsText) {
+ const thinkingText = nonEmptyThinkingBlocks.map((block) => sanitizeSurrogates(block.thinking)).join("\n\n");
+ assistantMsg.content = [{ type: "text", text: thinkingText }, ...assistantTextParts];
+ } else {
+ if (assistantText.length > 0) {
+ assistantMsg.content = assistantText;
+ }
+ if (!preservedReasoningDetails) {
+ let signature = nonEmptyThinkingBlocks[0].thinkingSignature;
+ if (model.provider === "opencode-go" && signature === "reasoning") {
+ signature = "reasoning_content";
+ }
+ if (signature && isOpenAICompletionsReasoningField(signature)) {
+ assistantMsg[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join("\n");
+ }
+ }
+ }
+ } else if (assistantText.length > 0) {
+ assistantMsg.content = assistantText;
+ }
+ if (toolCalls.length > 0) {
+ assistantMsg.tool_calls = toolCalls.map((tc) => {
+ const customInputProperty = options?.grammarToolInputProperties?.get(tc.name);
+ if (customInputProperty !== void 0) {
+ return {
+ id: tc.id,
+ type: "custom",
+ custom: {
+ name: tc.name,
+ input: sanitizeSurrogates(getGrammarToolInput(tc.name, tc.arguments, customInputProperty))
+ }
+ };
+ }
+ return {
+ id: tc.id,
+ type: "function",
+ function: {
+ name: tc.name,
+ arguments: JSON.stringify(tc.arguments)
+ }
+ };
+ });
+ }
+ if (preservedReasoningDetails) {
+ assistantMsg.reasoning_details = preservedReasoningDetails;
+ }
+ if (compat.requiresReasoningContentOnAssistantMessages && model.reasoning && assistantMsg.reasoning_content === void 0) {
+ assistantMsg.reasoning_content = "";
+ }
+ const content = assistantMsg.content;
+ const hasContent = content !== null && content !== void 0 && (typeof content === "string" ? content.length > 0 : content.length > 0);
+ if (!hasContent && !assistantMsg.tool_calls) {
+ continue;
+ }
+ params.push(assistantMsg);
+ } else if (msg.role === "toolResult") {
+ const imageBlocks = [];
+ let j = i;
+ for (; j < transformedMessages.length && transformedMessages[j].role === "toolResult"; j++) {
+ const toolMsg = transformedMessages[j];
+ const textResult = toolMsg.content.filter(isTextContentBlock).map((block) => block.text).join("\n");
+ const hasImages = toolMsg.content.some((c) => c.type === "image");
+ const hasText = textResult.length > 0;
+ const toolResultText = hasText ? textResult : hasImages ? "(see attached image)" : "(no tool output)";
+ const toolResultMsg = {
+ role: "tool",
+ content: sanitizeSurrogates(toolResultText),
+ tool_call_id: toolMsg.toolCallId
+ };
+ if (compat.requiresToolResultName && toolMsg.toolName) {
+ toolResultMsg.name = toolMsg.toolName;
+ }
+ params.push(toolResultMsg);
+ if (hasImages && model.input.includes("image")) {
+ for (const block of toolMsg.content) {
+ if (isImageContentBlock(block)) {
+ imageBlocks.push({
+ type: "image_url",
+ image_url: {
+ url: `data:${block.mimeType};base64,${block.data}`
+ }
+ });
+ }
+ }
+ }
+ }
+ i = j - 1;
+ if (imageBlocks.length > 0) {
+ if (compat.requiresAssistantAfterToolResult) {
+ params.push({
+ role: "assistant",
+ content: "I have processed the tool results."
+ });
+ }
+ params.push({
+ role: "user",
+ content: [
+ {
+ type: "text",
+ text: "Attached image(s) from tool result:"
+ },
+ ...imageBlocks
+ ]
+ });
+ lastRole = "user";
+ } else {
+ lastRole = "toolResult";
+ }
+ continue;
+ }
+ lastRole = msg.role;
+ }
+ return params;
+}
+function convertTools(tools, compat) {
+ return tools.map((tool) => {
+ const grammar = resolveGrammarConstrainedSampling(tool, compat.supportsOpenAIGrammarTools);
+ if (grammar) {
+ return {
+ type: "custom",
+ custom: {
+ name: tool.name,
+ description: tool.description,
+ format: {
+ type: "grammar",
+ grammar: {
+ syntax: grammar.format,
+ definition: grammar.definition
+ }
+ }
+ }
+ };
+ }
+ const strict = resolveJsonSchemaStrictSampling(tool, compat.supportsStrictMode !== false);
+ return {
+ type: "function",
+ function: {
+ name: tool.name,
+ description: tool.description,
+ parameters: getJsonSchemaToolParameters(tool, strict),
+ // Only include strict if provider supports it. Some reject unknown fields.
+ ...compat.supportsStrictMode !== false && { strict: strict ?? false }
+ }
+ };
+ });
+}
+function parseChunkUsage(rawUsage, model) {
+ const promptTokens = rawUsage.prompt_tokens || 0;
+ const cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? rawUsage.cached_tokens ?? 0;
+ const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;
+ const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);
+ const outputTokens = rawUsage.completion_tokens || 0;
+ const usage = {
+ input,
+ output: outputTokens,
+ cacheRead: cacheReadTokens,
+ cacheWrite: cacheWriteTokens,
+ reasoning: rawUsage.completion_tokens_details?.reasoning_tokens || 0,
+ totalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
+ };
+ calculateCost(model, usage);
+ return usage;
+}
+function mapStopReason(reason) {
+ if (reason === null)
+ return { stopReason: "stop" };
+ switch (reason) {
+ case "stop":
+ case "end":
+ return { stopReason: "stop" };
+ case "length":
+ return { stopReason: "length" };
+ case "function_call":
+ case "tool_calls":
+ return { stopReason: "toolUse" };
+ case "content_filter":
+ return { stopReason: "error", errorMessage: "Provider finish_reason: content_filter" };
+ case "network_error":
+ return { stopReason: "error", errorMessage: "Provider finish_reason: network_error" };
+ default:
+ return {
+ stopReason: "error",
+ errorMessage: `Provider finish_reason: ${reason}`
+ };
+ }
+}
+function detectCompat(model) {
+ const provider = model.provider;
+ const baseUrl = model.baseUrl;
+ const isZai = provider === "zai" || provider === "zai-coding-cn" || baseUrl.includes("api.z.ai") || baseUrl.includes("open.bigmodel.cn");
+ const isTogether = provider === "together" || baseUrl.includes("api.together.ai") || baseUrl.includes("api.together.xyz");
+ const isMoonshot = provider === "moonshotai" || provider === "moonshotai-cn" || baseUrl.includes("api.moonshot.");
+ const isOpenRouter = provider === "openrouter" || baseUrl.includes("openrouter.ai");
+ const isCloudflareWorkersAI = provider === "cloudflare-workers-ai" || baseUrl.includes("api.cloudflare.com");
+ const isCloudflareAiGateway = provider === "cloudflare-ai-gateway" || baseUrl.includes("gateway.ai.cloudflare.com");
+ const isNvidia = provider === "nvidia" || baseUrl.includes("integrate.api.nvidia.com");
+ const isAntLing = provider === "ant-ling" || baseUrl.includes("api.ant-ling.com");
+ const isCerebras = provider === "cerebras" || baseUrl.includes("cerebras.ai");
+ const isDeepSeek = provider === "deepseek" || baseUrl.toLowerCase().includes("deepseek.com");
+ const isNonStandard = isNvidia || isCerebras || provider === "xai" || baseUrl.includes("api.x.ai") || isTogether || baseUrl.includes("chutes.ai") || isDeepSeek || isZai || isMoonshot || provider === "opencode" || baseUrl.includes("opencode.ai") || isCloudflareWorkersAI || isCloudflareAiGateway || isAntLing;
+ const useMaxTokens = baseUrl.includes("chutes.ai") || isDeepSeek || isMoonshot || isCloudflareAiGateway || isTogether || isNvidia || isAntLing || isZai;
+ const isGrok = provider === "xai" || baseUrl.includes("api.x.ai");
+ const isOpenRouterDeveloperRoleModel = isOpenRouter && (model.id.startsWith("anthropic/") || model.id.startsWith("openai/"));
+ const cacheControlFormat = provider === "openrouter" && model.id.startsWith("anthropic/") ? "anthropic" : void 0;
+ return {
+ supportsStore: !isNonStandard,
+ supportsDeveloperRole: isOpenRouterDeveloperRoleModel || !isNonStandard && !isOpenRouter,
+ supportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing,
+ supportsUsageInStreaming: true,
+ supportsFinishReason: true,
+ maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens",
+ requiresToolResultName: false,
+ requiresAssistantAfterToolResult: false,
+ requiresThinkingAsText: false,
+ requiresReasoningContentOnAssistantMessages: isDeepSeek,
+ thinkingFormat: isDeepSeek ? "deepseek" : isZai ? "zai" : isTogether ? "together" : isAntLing ? "ant-ling" : isOpenRouter ? "openrouter" : "openai",
+ openRouterRouting: {},
+ vercelGatewayRouting: {},
+ chatTemplateKwargs: {},
+ chatTemplateArgs: {},
+ zaiToolStream: false,
+ supportsThinkingTokenBudget: false,
+ thinkingTokenBudgetField: void 0,
+ // OpenAI compatibility alone does not imply strict JSON-schema tool support.
+ supportsStrictMode: false,
+ supportsOpenAIGrammarTools: false,
+ supportsMidConvoSystemMessages: false,
+ supportsMidConvoToolAdditions: false,
+ cacheControlFormat,
+ sendSessionAffinityHeaders: isOpenRouter,
+ sessionAffinityFormat: isOpenRouter ? "openrouter" : "openai",
+ supportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway || isNvidia || isAntLing)
+ };
+}
+function getCompat(model) {
+ const detected = detectCompat(model);
+ if (!model.compat)
+ return detected;
+ return {
+ supportsStore: model.compat.supportsStore ?? detected.supportsStore,
+ supportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,
+ supportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,
+ supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
+ supportsFinishReason: model.compat.supportsFinishReason ?? detected.supportsFinishReason,
+ maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,
+ requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,
+ requiresAssistantAfterToolResult: model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
+ requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,
+ requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ?? detected.requiresReasoningContentOnAssistantMessages,
+ thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,
+ openRouterRouting: model.compat.openRouterRouting ?? {},
+ vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,
+ chatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs,
+ chatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs,
+ zaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,
+ supportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget,
+ thinkingTokenBudgetField: model.compat.thinkingTokenBudgetField ?? detected.thinkingTokenBudgetField,
+ supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,
+ supportsOpenAIGrammarTools: model.compat.supportsOpenAIGrammarTools ?? detected.supportsOpenAIGrammarTools,
+ supportsMidConvoSystemMessages: model.compat.supportsMidConvoSystemMessages ?? detected.supportsMidConvoSystemMessages,
+ supportsMidConvoToolAdditions: model.compat.supportsMidConvoToolAdditions ?? detected.supportsMidConvoToolAdditions,
+ cacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,
+ sendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,
+ sessionAffinityFormat: model.compat.sessionAffinityFormat ?? detected.sessionAffinityFormat,
+ supportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention,
+ vllmPriority: model.compat.vllmPriority
+ };
+}
+var OPENAI_COMPLETIONS_REASONING_FIELDS, stream, streamSimple;
+var init_openai_completions = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js"() {
+ init_openai();
+ init_models();
+ init_error_body();
+ init_event_stream();
+ init_hash();
+ init_headers2();
+ init_json_parse();
+ init_pi_user_agent();
+ init_provider_env();
+ init_provider_retry();
+ init_sanitize_unicode();
+ init_text();
+ init_transcript();
+ init_constrained_sampling();
+ init_github_copilot_headers();
+ init_openai_prompt_cache();
+ init_simple_options();
+ init_transform_messages();
+ OPENAI_COMPLETIONS_REASONING_FIELDS = ["reasoning", "reasoning_content", "reasoning_text"];
+ stream = (model, context, options) => {
+ const stream3 = new AssistantMessageEventStream();
+ const normalizedContext = resolveTranscript(context, getCompat(model).supportsMidConvoSystemMessages);
+ (async () => {
+ const output = {
+ role: "assistant",
+ content: [],
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
+ },
+ stopReason: "pending",
+ timestamp: Date.now()
+ };
+ let streamedReasoningDetails;
+ const applyStreamedReasoningDetails = (block) => {
+ if (streamedReasoningDetails !== void 0) {
+ block.thinkingSignature = JSON.stringify(streamedReasoningDetails);
+ }
+ };
+ try {
+ const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);
+ const compat = getCompat(model);
+ const grammarToolInputProperties = createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages), compat.supportsOpenAIGrammarTools);
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
+ const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
+ const client = createClient(model, normalizedContext, apiKey, options?.headers, options?.fetch, cacheSessionId, compat);
+ let params = buildParams(model, normalizedContext, options, compat, cacheRetention, grammarToolInputProperties);
+ const nextParams = await options?.onPayload?.(params, model);
+ if (nextParams !== void 0) {
+ params = nextParams;
+ }
+ const requestOptions = {
+ ...options?.signal ? { signal: options.signal } : {},
+ ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
+ maxRetries: 0
+ };
+ const { data: openaiStream, response } = await retryProviderRequest(() => client.chat.completions.create(params, requestOptions).withResponse(), {
+ maxRetries: options?.maxRetries,
+ maxRetryDelayMs: options?.maxRetryDelayMs,
+ signal: options?.signal
+ });
+ await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
+ stream3.push({ type: "start", partial: output });
+ let textBlock = null;
+ let thinkingBlock = null;
+ let hasFinishReason = false;
+ const toolCallBlocksByIndex = /* @__PURE__ */ new Map();
+ const toolCallBlocksById = /* @__PURE__ */ new Map();
+ const blocks = output.content;
+ const getContentIndex = (block) => blocks.indexOf(block);
+ const getCustomToolCallInput2 = (block) => {
+ const property = block.customInput?.property;
+ if (property === void 0)
+ return "";
+ const value = block.arguments[property];
+ return typeof value === "string" ? value : "";
+ };
+ const appendCustomToolCallInput2 = (block, nextInput, close) => {
+ const customInput = block.customInput;
+ if (!customInput)
+ return void 0;
+ const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);
+ block.arguments = { [customInput.property]: nextInput };
+ return delta;
+ };
+ const finishBlock = (block) => {
+ const contentIndex = getContentIndex(block);
+ if (contentIndex === -1) {
+ return;
+ }
+ if (block.type === "text") {
+ stream3.push({
+ type: "text_end",
+ contentIndex,
+ content: block.text,
+ partial: output
+ });
+ } else if (block.type === "thinking") {
+ applyStreamedReasoningDetails(block);
+ stream3.push({
+ type: "thinking_end",
+ contentIndex,
+ content: block.thinking,
+ partial: output
+ });
+ } else if (block.type === "toolCall") {
+ if (block.customInput) {
+ const delta = appendCustomToolCallInput2(block, getCustomToolCallInput2(block), true);
+ if (delta !== void 0) {
+ stream3.push({
+ type: "toolcall_delta",
+ contentIndex,
+ delta,
+ partial: output
+ });
+ }
+ } else {
+ block.arguments = parseStreamingJson(block.partialArgs);
+ }
+ delete block.partialArgs;
+ delete block.customInput;
+ delete block.streamIndex;
+ stream3.push({
+ type: "toolcall_end",
+ contentIndex,
+ toolCall: block,
+ partial: output
+ });
+ }
+ };
+ const ensureTextBlock = () => {
+ if (!textBlock) {
+ textBlock = { type: "text", text: "" };
+ blocks.push(textBlock);
+ stream3.push({ type: "text_start", contentIndex: getContentIndex(textBlock), partial: output });
+ }
+ return textBlock;
+ };
+ const ensureThinkingBlock = (thinkingSignature) => {
+ if (!thinkingBlock) {
+ thinkingBlock = {
+ type: "thinking",
+ thinking: "",
+ thinkingSignature
+ };
+ blocks.push(thinkingBlock);
+ stream3.push({ type: "thinking_start", contentIndex: getContentIndex(thinkingBlock), partial: output });
+ }
+ return thinkingBlock;
+ };
+ const ensureToolCallBlock = (toolCall) => {
+ const streamIndex = typeof toolCall.index === "number" ? toolCall.index : void 0;
+ const name = toolCall.function?.name ?? toolCall.custom?.name ?? "";
+ let block = streamIndex !== void 0 ? toolCallBlocksByIndex.get(streamIndex) : void 0;
+ if (!block && toolCall.id) {
+ block = toolCallBlocksById.get(toolCall.id);
+ }
+ if (!block) {
+ const customInputProperty = toolCall.custom && !toolCall.function ? grammarToolInputProperties.get(name) ?? "input" : void 0;
+ const hasCustomInput = customInputProperty !== void 0;
+ block = {
+ type: "toolCall",
+ id: toolCall.id || "",
+ name,
+ arguments: hasCustomInput ? { [customInputProperty]: "" } : {},
+ partialArgs: hasCustomInput ? void 0 : "",
+ customInput: hasCustomInput ? { property: customInputProperty, jsonBuffer: { input: "", started: false, closed: false } } : void 0,
+ streamIndex
+ };
+ if (streamIndex !== void 0) {
+ toolCallBlocksByIndex.set(streamIndex, block);
+ }
+ if (toolCall.id) {
+ toolCallBlocksById.set(toolCall.id, block);
+ }
+ blocks.push(block);
+ stream3.push({
+ type: "toolcall_start",
+ contentIndex: getContentIndex(block),
+ partial: output
+ });
+ }
+ if (streamIndex !== void 0 && block.streamIndex === void 0) {
+ block.streamIndex = streamIndex;
+ toolCallBlocksByIndex.set(streamIndex, block);
+ }
+ if (toolCall.id) {
+ toolCallBlocksById.set(toolCall.id, block);
+ }
+ if (!block.name && name) {
+ block.name = name;
+ }
+ if (toolCall.custom && !toolCall.function && !block.customInput) {
+ const customInputProperty = grammarToolInputProperties.get(block.name) ?? "input";
+ block.arguments = { [customInputProperty]: "" };
+ block.customInput = {
+ property: customInputProperty,
+ jsonBuffer: { input: "", started: false, closed: false }
+ };
+ delete block.partialArgs;
+ }
+ return block;
+ };
+ for await (const chunk of openaiStream) {
+ await options?.onProviderStreamEvent?.(chunk, model);
+ if (!chunk || typeof chunk !== "object")
+ continue;
+ output.responseId ||= chunk.id;
+ if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) {
+ output.responseModel ||= chunk.model;
+ }
+ if (chunk.usage) {
+ output.usage = parseChunkUsage(chunk.usage, model);
+ }
+ const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
+ if (!choice)
+ continue;
+ if (!chunk.usage && choice.usage) {
+ output.usage = parseChunkUsage(choice.usage, model);
+ }
+ if (choice.finish_reason) {
+ output.rawStopReason = choice.finish_reason;
+ const finishReasonResult = mapStopReason(choice.finish_reason);
+ output.stopReason = finishReasonResult.stopReason;
+ if (finishReasonResult.errorMessage) {
+ output.errorMessage = finishReasonResult.errorMessage;
+ }
+ hasFinishReason = true;
+ }
+ if (choice.delta) {
+ if (choice.delta.content !== null && choice.delta.content !== void 0 && choice.delta.content.length > 0) {
+ const block = ensureTextBlock();
+ block.text += choice.delta.content;
+ stream3.push({
+ type: "text_delta",
+ contentIndex: getContentIndex(block),
+ delta: choice.delta.content,
+ partial: output
+ });
+ }
+ const reasoningFields = ["reasoning_content", "reasoning", "reasoning_text"];
+ const deltaFields = choice.delta;
+ let foundReasoningField = null;
+ for (const field of reasoningFields) {
+ const value = deltaFields[field];
+ if (typeof value === "string" && value.length > 0) {
+ foundReasoningField = field;
+ break;
+ }
+ }
+ if (foundReasoningField) {
+ const delta = deltaFields[foundReasoningField];
+ if (typeof delta === "string" && delta.length > 0) {
+ const thinkingSignature = model.provider === "opencode-go" && foundReasoningField === "reasoning" ? "reasoning_content" : foundReasoningField;
+ const block = ensureThinkingBlock(thinkingSignature);
+ block.thinking += delta;
+ stream3.push({
+ type: "thinking_delta",
+ contentIndex: getContentIndex(block),
+ delta,
+ partial: output
+ });
+ }
+ }
+ if (choice?.delta?.tool_calls) {
+ for (const toolCall of choice.delta.tool_calls) {
+ const block = ensureToolCallBlock(toolCall);
+ if (!block.id && toolCall.id) {
+ block.id = toolCall.id;
+ toolCallBlocksById.set(toolCall.id, block);
+ }
+ const name = toolCall.function?.name ?? toolCall.custom?.name;
+ if (!block.name && name) {
+ block.name = name;
+ }
+ let delta = "";
+ if (toolCall.function?.arguments) {
+ delta = toolCall.function.arguments;
+ block.partialArgs = (block.partialArgs ?? "") + toolCall.function.arguments;
+ block.arguments = parseStreamingJson(block.partialArgs);
+ } else if (toolCall.custom?.input) {
+ const nextInput = getCustomToolCallInput2(block) + toolCall.custom.input;
+ delta = appendCustomToolCallInput2(block, nextInput, false) ?? "";
+ }
+ stream3.push({
+ type: "toolcall_delta",
+ contentIndex: getContentIndex(block),
+ delta,
+ partial: output
+ });
+ }
+ }
+ const reasoningDetails = choice.delta.reasoning_details;
+ if (Array.isArray(reasoningDetails)) {
+ for (const detail of reasoningDetails) {
+ if (!isOpenAIReasoningDetail(detail))
+ continue;
+ ensureThinkingBlock("");
+ streamedReasoningDetails ??= [];
+ appendOpenAIReasoningDetail(streamedReasoningDetails, detail);
+ }
+ }
+ }
+ }
+ for (const block of blocks) {
+ finishBlock(block);
+ }
+ if (options?.signal?.aborted) {
+ throw new Error("Request was aborted");
+ }
+ if (output.stopReason === "aborted") {
+ throw new Error("Request was aborted");
+ }
+ if (!hasFinishReason && !compat.supportsFinishReason) {
+ output.stopReason = output.content.some((block) => block.type === "toolCall") ? "toolUse" : "stop";
+ }
+ if (output.stopReason === "error") {
+ throw new Error(output.errorMessage || "Provider returned an error stop reason");
+ }
+ if (compat.supportsFinishReason && !hasFinishReason || output.stopReason === "pending") {
+ throw new Error("Stream ended without finish_reason");
+ }
+ stream3.push({ type: "done", reason: output.stopReason, message: output });
+ stream3.end();
+ } catch (error) {
+ for (const block of output.content) {
+ if (block.type === "thinking") {
+ applyStreamedReasoningDetails(block);
+ }
+ delete block.index;
+ delete block.partialArgs;
+ delete block.customInput;
+ delete block.streamIndex;
+ }
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
+ output.errorMessage = formatProviderError(normalizeProviderError(error));
+ const rawMetadata = error?.error?.metadata?.raw;
+ if (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) {
+ output.errorMessage += `
+${rawMetadata}`;
+ }
+ stream3.push({ type: "error", reason: output.stopReason, error: output });
+ stream3.end();
+ }
+ })();
+ return stream3;
+ };
+ streamSimple = (model, context, options) => {
+ getClientApiKey(model.provider, options?.apiKey, options?.headers);
+ const base = {
+ ...buildBaseOptions(model, context, options, options?.apiKey),
+ toolChoice: options?.toolChoice
+ };
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
+ const reasoningEffort = clampedReasoning === "off" ? void 0 : clampedReasoning;
+ return stream(model, context, {
+ ...base,
+ reasoningEffort,
+ thinkingBudgets: options?.thinkingBudgets
+ });
+ };
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js
+function encodeTextSignatureV1(id, phase) {
+ const payload = { v: 1, id };
+ if (phase)
+ payload.phase = phase;
+ return JSON.stringify(payload);
+}
+function parseTextSignature(signature) {
+ if (!signature)
+ return void 0;
+ if (signature.startsWith("{")) {
+ try {
+ const parsed = JSON.parse(signature);
+ if (parsed.v === 1 && typeof parsed.id === "string") {
+ if (parsed.phase === "commentary" || parsed.phase === "final_answer") {
+ return { id: parsed.id, phase: parsed.phase };
+ }
+ return { id: parsed.id };
+ }
+ } catch {
+ }
+ }
+ return { id: signature };
+}
+function convertToolResultOutput(model, content) {
+ const textResult = content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
+ const images = content.filter((c) => c.type === "image");
+ const hasText = textResult.length > 0;
+ if (images.length === 0 || !model.input.includes("image")) {
+ return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? "(see attached image)" : "(no tool output)");
+ }
+ const output = [];
+ if (hasText) {
+ output.push({ type: "input_text", text: sanitizeSurrogates(textResult) });
+ }
+ for (const image of images) {
+ output.push({
+ type: "input_image",
+ detail: "auto",
+ image_url: `data:${image.mimeType};base64,${image.data}`
+ });
+ }
+ return output;
+}
+function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
+ const normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);
+ const messages = [];
+ const normalizeIdPart = (part) => {
+ const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
+ const normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;
+ return normalized.replace(/_+$/, "");
+ };
+ const buildForeignResponsesItemId = (itemId) => {
+ const normalized = `fc_${shortHash(itemId)}`;
+ return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
+ };
+ const normalizeToolCallId = (id, _targetModel, source) => {
+ if (!allowedToolCallProviders.has(model.provider))
+ return normalizeIdPart(id);
+ if (!id.includes("|"))
+ return normalizeIdPart(id);
+ const [callId, itemId] = id.split("|");
+ const normalizedCallId = normalizeIdPart(callId);
+ const isForeignToolCall = source.provider !== model.provider || source.api !== model.api;
+ let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
+ if (!normalizedItemId.startsWith("fc_")) {
+ normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
+ }
+ return `${normalizedCallId}|${normalizedItemId}`;
+ };
+ const transformedMessages = transformMessages(normalizedContext.messages, model, normalizeToolCallId);
+ const transcriptTools = resolveTranscriptTools(normalizedContext.messages, (options?.supportsAdditionalTools ?? false) || (options?.supportsToolSearch ?? false));
+ const appendSystemToolAdditions = (message, seed) => {
+ const tools = transcriptTools.anchorsAdditions ? message.toolsAdded ?? [] : [];
+ if (tools.length === 0)
+ return;
+ if (options?.supportsAdditionalTools) {
+ messages.push({
+ type: "additional_tools",
+ role: "developer",
+ tools: convertResponsesTools(tools, options.toolOptions)
+ });
+ return;
+ }
+ if (!options?.supportsToolSearch)
+ return;
+ const names3 = tools.map((tool) => tool.name);
+ const callId = `pi_tool_load_${shortHash(`${seed}:${names3.join(",")}`)}`;
+ messages.push({
+ type: "tool_search_call",
+ call_id: callId,
+ execution: "client",
+ status: "completed",
+ arguments: { query: names3.join(" "), limit: names3.length }
+ });
+ messages.push({
+ type: "tool_search_output",
+ call_id: callId,
+ execution: "client",
+ status: "completed",
+ tools: convertResponsesTools(tools, { ...options.toolOptions, toolSearchResult: true })
+ });
+ };
+ const includeInitialSystemMessage = options?.includeSystemPrompt ?? true;
+ const compat = model.compat;
+ const instructionRole = model.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system";
+ let msgIndex = 0;
+ let sourceIndex = 0;
+ for (const msg of transformedMessages) {
+ const isLeadingSystemMessage = sourceIndex++ === 0 && msg.role === "system";
+ if (msg.role === "system") {
+ if (!isLeadingSystemMessage)
+ appendSystemToolAdditions(msg, `system:${msgIndex}`);
+ if (!isLeadingSystemMessage || includeInitialSystemMessage) {
+ const text = isLeadingSystemMessage ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg);
+ if (text.length > 0) {
+ messages.push({ role: instructionRole, content: sanitizeSurrogates(text) });
+ }
+ }
+ } else if (msg.role === "user") {
+ if (typeof msg.content === "string") {
+ messages.push({
+ role: "user",
+ content: [{ type: "input_text", text: sanitizeSurrogates(msg.content) }]
+ });
+ } else {
+ const content = msg.content.map((item) => {
+ if (item.type === "text") {
+ return {
+ type: "input_text",
+ text: sanitizeSurrogates(item.text)
+ };
+ }
+ return {
+ type: "input_image",
+ detail: "auto",
+ image_url: `data:${item.mimeType};base64,${item.data}`
+ };
+ });
+ if (content.length === 0)
+ continue;
+ messages.push({
+ role: "user",
+ content
+ });
+ }
+ } else if (msg.role === "assistant") {
+ const output = [];
+ const assistantMsg = msg;
+ const isSameProviderAndApi = assistantMsg.provider === model.provider && assistantMsg.api === model.api;
+ const isSameModel = isSameProviderAndApi && assistantMsg.model === model.id;
+ const isDifferentModel = isSameProviderAndApi && assistantMsg.model !== model.id;
+ let textBlockIndex = 0;
+ for (const block of msg.content) {
+ if (block.type === "thinking") {
+ if (block.thinkingSignature) {
+ const reasoningItem = JSON.parse(block.thinkingSignature);
+ output.push(reasoningItem);
+ }
+ } else if (block.type === "text") {
+ const textBlock = block;
+ const parsedSignature = parseTextSignature(textBlock.textSignature);
+ const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;
+ textBlockIndex++;
+ let msgId = parsedSignature?.id;
+ if (!msgId) {
+ msgId = fallbackMessageId;
+ } else if (msgId.length > 64) {
+ msgId = `msg_${shortHash(msgId)}`;
+ }
+ output.push({
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: sanitizeSurrogates(textBlock.text), annotations: [] }],
+ status: "completed",
+ id: msgId,
+ phase: parsedSignature?.phase
+ });
+ } else if (block.type === "toolCall") {
+ const toolCall = block;
+ const [callId, itemIdRaw] = toolCall.id.split("|");
+ const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);
+ let itemId = itemIdRaw;
+ const itemIdPrefix = customInputProperty === void 0 ? "fc_" : "ctc_";
+ if (isDifferentModel || !itemId?.startsWith(itemIdPrefix)) {
+ itemId = void 0;
+ }
+ if (customInputProperty !== void 0) {
+ output.push({
+ type: "custom_tool_call",
+ id: itemId,
+ call_id: callId,
+ name: toolCall.name,
+ input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty)),
+ ...isSameModel && toolCall.namespace !== void 0 ? { namespace: toolCall.namespace } : {}
+ });
+ } else {
+ output.push({
+ type: "function_call",
+ id: itemId,
+ call_id: callId,
+ name: toolCall.name,
+ arguments: JSON.stringify(toolCall.arguments),
+ ...isSameModel && toolCall.namespace !== void 0 ? { namespace: toolCall.namespace } : {}
+ });
+ }
+ }
+ }
+ if (output.length === 0)
+ continue;
+ messages.push(...output);
+ } else if (msg.role === "toolResult") {
+ const [callId] = msg.toolCallId.split("|");
+ const output = convertToolResultOutput(model, msg.content);
+ if (options?.grammarToolInputProperties?.has(msg.toolName)) {
+ messages.push({
+ type: "custom_tool_call_output",
+ call_id: callId,
+ output
+ });
+ } else {
+ messages.push({
+ type: "function_call_output",
+ call_id: callId,
+ output
+ });
+ }
+ }
+ if (!isLeadingSystemMessage)
+ msgIndex++;
+ }
+ return messages;
+}
+function convertResponsesTools(tools, options) {
+ const defaultStrict = options?.strict === void 0 ? false : options.strict;
+ const supportsStrictMode = options?.supportsStrictMode ?? true;
+ const supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;
+ return tools.map((tool) => {
+ const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
+ if (grammar) {
+ return {
+ type: "custom",
+ name: tool.name,
+ description: tool.description,
+ format: {
+ type: "grammar",
+ syntax: grammar.format,
+ definition: grammar.definition
+ },
+ ...options?.toolSearchResult ? { defer_loading: true } : {}
+ };
+ }
+ const constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);
+ const strict = constrainedStrict ?? defaultStrict;
+ const functionTool = {
+ type: "function",
+ name: tool.name,
+ description: tool.description,
+ parameters: getJsonSchemaToolParameters(tool, strict === true),
+ ...options?.toolSearchResult ? { defer_loading: true } : {}
+ };
+ if (supportsStrictMode) {
+ functionTool.strict = strict;
+ }
+ return functionTool;
+ });
+}
+function getCustomToolCallInput(block) {
+ const property = block.customInput?.property;
+ if (property === void 0)
+ return "";
+ const value = block.arguments[property];
+ return typeof value === "string" ? value : "";
+}
+function appendCustomToolCallInput(block, nextInput, close) {
+ const customInput = block.customInput;
+ if (!customInput)
+ return void 0;
+ const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);
+ block.arguments = { [customInput.property]: nextInput };
+ return delta;
+}
+async function processResponsesStream(openaiStream, output, stream3, model, options) {
+ let sawTerminalResponseEvent = false;
+ const outputSlots = /* @__PURE__ */ new Map();
+ const reasoningBlocksById = /* @__PURE__ */ new Map();
+ const applyMessagePhaseStopReason = (item) => {
+ if (item.type === "message" && item.phase === "final_answer") {
+ output.stopReason = "stop";
+ }
+ };
+ const getSlot = (outputIndex, type) => {
+ const slot = outputSlots.get(outputIndex);
+ return slot?.type === type ? slot : void 0;
+ };
+ const pushToolCallDelta = (slot, delta) => {
+ if (delta === void 0)
+ return;
+ stream3.push({
+ type: "toolcall_delta",
+ contentIndex: slot.contentIndex,
+ delta,
+ partial: output
+ });
+ };
+ const createSlot = (outputIndex, item) => {
+ if (item.type === "reasoning") {
+ const block = { type: "thinking", thinking: "" };
+ output.content.push(block);
+ const slot = {
+ type: "thinking",
+ block,
+ contentIndex: output.content.length - 1
+ };
+ outputSlots.set(outputIndex, slot);
+ stream3.push({ type: "thinking_start", contentIndex: slot.contentIndex, partial: output });
+ return slot;
+ }
+ if (item.type === "message") {
+ applyMessagePhaseStopReason(item);
+ const block = { type: "text", text: "" };
+ output.content.push(block);
+ const slot = { type: "text", block, contentIndex: output.content.length - 1 };
+ outputSlots.set(outputIndex, slot);
+ stream3.push({ type: "text_start", contentIndex: slot.contentIndex, partial: output });
+ return slot;
+ }
+ if (item.type === "function_call") {
+ const block = {
+ type: "toolCall",
+ id: `${item.call_id}|${item.id}`,
+ name: item.name,
+ arguments: {},
+ ...item.namespace !== void 0 ? { namespace: item.namespace } : {},
+ partialJson: item.arguments || ""
+ };
+ output.content.push(block);
+ const slot = {
+ type: "toolCall",
+ block,
+ contentIndex: output.content.length - 1
+ };
+ outputSlots.set(outputIndex, slot);
+ stream3.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });
+ return slot;
+ }
+ if (item.type === "custom_tool_call") {
+ const inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? "input";
+ const input = item.input || "";
+ const block = {
+ type: "toolCall",
+ id: `${item.call_id}|${item.id}`,
+ name: item.name,
+ arguments: { [inputProperty]: input },
+ ...item.namespace !== void 0 ? { namespace: item.namespace } : {},
+ customInput: {
+ property: inputProperty,
+ jsonBuffer: { input: "", started: false, closed: false }
+ }
+ };
+ output.content.push(block);
+ const slot = {
+ type: "toolCall",
+ block,
+ contentIndex: output.content.length - 1
+ };
+ outputSlots.set(outputIndex, slot);
+ stream3.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });
+ return slot;
+ }
+ return void 0;
+ };
+ const getOrCreateSlot = (outputIndex, item) => {
+ return outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);
+ };
+ const backfillReasoningSignatures = (responseOutput) => {
+ for (const item of responseOutput) {
+ if (item.type !== "reasoning" || !item.encrypted_content)
+ continue;
+ const block = reasoningBlocksById.get(item.id);
+ if (!block?.thinkingSignature)
+ continue;
+ const storedItem = JSON.parse(block.thinkingSignature);
+ if (storedItem.encrypted_content)
+ continue;
+ block.thinkingSignature = JSON.stringify({
+ ...storedItem,
+ encrypted_content: item.encrypted_content
+ });
+ }
+ };
+ const finalizeResponse2 = (response) => {
+ sawTerminalResponseEvent = true;
+ backfillReasoningSignatures(response.output ?? []);
+ if (response?.id) {
+ output.responseId = response.id;
+ }
+ if (response?.usage) {
+ const inputDetails = response.usage.input_tokens_details;
+ const cachedTokens = inputDetails?.cached_tokens || 0;
+ const cacheWriteTokens = inputDetails?.cache_write_tokens || 0;
+ output.usage = {
+ // OpenAI includes cached and cache-write tokens in input_tokens, so subtract both.
+ input: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),
+ output: response.usage.output_tokens || 0,
+ cacheRead: cachedTokens,
+ cacheWrite: cacheWriteTokens,
+ reasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,
+ totalTokens: response.usage.total_tokens || 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
+ };
+ }
+ calculateCost(model, output.usage);
+ if (options?.applyServiceTierPricing) {
+ const serviceTier = options.resolveServiceTier ? options.resolveServiceTier(response?.service_tier, options.serviceTier) : response?.service_tier ?? options.serviceTier;
+ options.applyServiceTierPricing(output.usage, serviceTier);
+ }
+ const status = response?.status;
+ const incompleteDetails = response?.incomplete_details;
+ const incompleteReason = typeof incompleteDetails?.reason === "string" ? incompleteDetails.reason : void 0;
+ output.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;
+ const mappedStop = mapStopReason2(status, incompleteReason);
+ output.stopReason = mappedStop.stopReason;
+ if (mappedStop.errorMessage === void 0)
+ delete output.errorMessage;
+ else
+ output.errorMessage = mappedStop.errorMessage;
+ if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") {
+ output.stopReason = "toolUse";
+ }
+ };
+ for await (const event of openaiStream) {
+ await options?.onProviderStreamEvent?.(event, model);
+ if (event.type === "response.created") {
+ output.responseId = event.response.id;
+ } else if (event.type === "response.output_item.added") {
+ createSlot(event.output_index, event.item);
+ } else if (event.type === "response.reasoning_summary_text.delta") {
+ const slot = getSlot(event.output_index, "thinking");
+ if (!slot)
+ continue;
+ slot.block.thinking += event.delta;
+ stream3.push({
+ type: "thinking_delta",
+ contentIndex: slot.contentIndex,
+ delta: event.delta,
+ partial: output
+ });
+ } else if (event.type === "response.reasoning_summary_part.done") {
+ const slot = getSlot(event.output_index, "thinking");
+ if (!slot)
+ continue;
+ slot.block.thinking += "\n\n";
+ stream3.push({
+ type: "thinking_delta",
+ contentIndex: slot.contentIndex,
+ delta: "\n\n",
+ partial: output
+ });
+ } else if (event.type === "response.reasoning_text.delta") {
+ const slot = getSlot(event.output_index, "thinking");
+ if (!slot)
+ continue;
+ slot.block.thinking += event.delta;
+ stream3.push({
+ type: "thinking_delta",
+ contentIndex: slot.contentIndex,
+ delta: event.delta,
+ partial: output
+ });
+ } else if (event.type === "response.output_text.delta") {
+ const slot = getSlot(event.output_index, "text");
+ if (!slot)
+ continue;
+ slot.block.text += event.delta;
+ stream3.push({
+ type: "text_delta",
+ contentIndex: slot.contentIndex,
+ delta: event.delta,
+ partial: output
+ });
+ } else if (event.type === "response.refusal.delta") {
+ const slot = getSlot(event.output_index, "text");
+ if (!slot)
+ continue;
+ slot.block.text += event.delta;
+ stream3.push({
+ type: "text_delta",
+ contentIndex: slot.contentIndex,
+ delta: event.delta,
+ partial: output
+ });
+ } else if (event.type === "response.function_call_arguments.delta") {
+ const slot = getSlot(event.output_index, "toolCall");
+ if (!slot || slot.block.partialJson === void 0)
+ continue;
+ slot.block.partialJson += event.delta;
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
+ pushToolCallDelta(slot, event.delta);
+ } else if (event.type === "response.function_call_arguments.done") {
+ const slot = getSlot(event.output_index, "toolCall");
+ if (!slot || slot.block.partialJson === void 0)
+ continue;
+ const previousPartialJson = slot.block.partialJson;
+ slot.block.partialJson = event.arguments;
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
+ if (event.arguments.startsWith(previousPartialJson)) {
+ const delta = event.arguments.slice(previousPartialJson.length);
+ if (delta.length > 0)
+ pushToolCallDelta(slot, delta);
+ }
+ } else if (event.type === "response.custom_tool_call_input.delta") {
+ const slot = getSlot(event.output_index, "toolCall");
+ if (!slot || !slot.block.customInput)
+ continue;
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, getCustomToolCallInput(slot.block) + event.delta, false));
+ } else if (event.type === "response.custom_tool_call_input.done") {
+ const slot = getSlot(event.output_index, "toolCall");
+ if (!slot || !slot.block.customInput)
+ continue;
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, event.input, true));
+ } else if (event.type === "response.output_item.done") {
+ const item = event.item;
+ applyMessagePhaseStopReason(item);
+ const slot = getOrCreateSlot(event.output_index, item);
+ if (item.type === "reasoning" && slot?.type === "thinking") {
+ const summaryText2 = item.summary?.map((s) => s.text).join("\n\n") || "";
+ const contentText3 = item.content?.map((c) => c.text).join("\n\n") || "";
+ slot.block.thinking = summaryText2 || contentText3 || slot.block.thinking;
+ slot.block.thinkingSignature = JSON.stringify(item);
+ reasoningBlocksById.set(item.id, slot.block);
+ stream3.push({
+ type: "thinking_end",
+ contentIndex: slot.contentIndex,
+ content: slot.block.thinking,
+ partial: output
+ });
+ outputSlots.delete(event.output_index);
+ } else if (item.type === "message" && slot?.type === "text") {
+ slot.block.text = item.content?.map((c) => c.type === "output_text" ? c.text : c.refusal).join("") || "";
+ slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? void 0);
+ stream3.push({
+ type: "text_end",
+ contentIndex: slot.contentIndex,
+ content: slot.block.text,
+ partial: output
+ });
+ outputSlots.delete(event.output_index);
+ } else if (item.type === "function_call" && slot?.type === "toolCall" && slot.block.partialJson !== void 0) {
+ slot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || "{}");
+ if (item.namespace !== void 0)
+ slot.block.namespace = item.namespace;
+ delete slot.block.partialJson;
+ stream3.push({
+ type: "toolcall_end",
+ contentIndex: slot.contentIndex,
+ toolCall: slot.block,
+ partial: output
+ });
+ outputSlots.delete(event.output_index);
+ } else if (item.type === "custom_tool_call" && slot?.type === "toolCall" && slot.block.customInput) {
+ pushToolCallDelta(slot, appendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true));
+ if (item.namespace !== void 0)
+ slot.block.namespace = item.namespace;
+ delete slot.block.customInput;
+ stream3.push({
+ type: "toolcall_end",
+ contentIndex: slot.contentIndex,
+ toolCall: slot.block,
+ partial: output
+ });
+ outputSlots.delete(event.output_index);
+ }
+ } else if (event.type === "response.completed" || event.type === "response.incomplete") {
+ finalizeResponse2(event.response);
+ } else if (event.type === "error") {
+ throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
+ } else if (event.type === "response.failed") {
+ sawTerminalResponseEvent = true;
+ output.rawStopReason = event.response?.status;
+ const error = event.response?.error;
+ const details = event.response?.incomplete_details;
+ const msg = error ? `${error.code || "unknown"}: ${error.message || "no message"}` : details?.reason ? `incomplete: ${details.reason}` : "Unknown error (no error details in response)";
+ throw new Error(msg);
+ }
+ }
+ if (!sawTerminalResponseEvent) {
+ throw new Error("OpenAI Responses stream ended before a terminal response event");
+ }
+ if (output.stopReason === "toolUse") {
+ for (const block of output.content) {
+ if (block.type !== "toolCall")
+ continue;
+ const toolCall = block;
+ if (toolCall.partialJson !== void 0 || toolCall.customInput !== void 0) {
+ throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`);
+ }
+ }
+ }
+}
+function mapStopReason2(status, incompleteReason) {
+ if (!status)
+ return { stopReason: "stop" };
+ switch (status) {
+ case "completed":
+ return { stopReason: "stop" };
+ case "incomplete":
+ if (incompleteReason === "max_output_tokens") {
+ return { stopReason: "length" };
+ }
+ return {
+ stopReason: "error",
+ errorMessage: incompleteReason ? `Response incomplete: ${incompleteReason}` : "Response incomplete without a provider reason"
+ };
+ case "failed":
+ case "cancelled":
+ return { stopReason: "error" };
+ // These two are wonky ...
+ case "in_progress":
+ case "queued":
+ return { stopReason: "stop" };
+ default: {
+ const _exhaustive = status;
+ throw new Error(`Unhandled stop reason: ${_exhaustive}`);
+ }
+ }
+}
+var init_openai_responses_shared = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js"() {
+ init_models();
+ init_hash();
+ init_json_parse();
+ init_sanitize_unicode();
+ init_text();
+ init_transcript();
+ init_constrained_sampling();
+ init_transform_messages();
+ }
+});
+
+// node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js
+var openai_responses_exports = {};
+__export(openai_responses_exports, {
+ stream: () => stream2,
+ streamSimple: () => streamSimple2
+});
+function isChatGPTSignIn(model, apiKey) {
+ return model.provider === "openai" && model.baseUrl === "https://api.openai.com/v1" && apiKey !== void 0 && !apiKey.startsWith("sk-");
+}
+function hasHeader2(headers, name) {
+ if (!headers)
+ return false;
+ const expected = name.toLowerCase();
+ for (const [key, value] of Object.entries(headers)) {
+ if (key.toLowerCase() === expected && value !== null && value.trim().length > 0)
+ return true;
+ }
+ return false;
+}
+function getClientApiKey2(provider, apiKey, headers) {
+ if (apiKey)
+ return apiKey;
+ if (hasHeader2(headers, "authorization") || hasHeader2(headers, "cf-aig-authorization"))
+ return "unused";
+ throw new Error(`No API key for provider: ${provider}`);
+}
+function detectSessionAffinityFormat(model) {
+ return model.provider === "openrouter" || model.baseUrl.includes("openrouter.ai") ? "openrouter" : "openai";
+}
+function resolveCacheRetention2(cacheRetention, env) {
+ if (cacheRetention) {
+ return cacheRetention;
+ }
+ if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") {
+ return "long";
+ }
+ return "short";
+}
+function getCompat2(model) {
+ return {
+ supportsDeveloperRole: model.compat?.supportsDeveloperRole ?? true,
+ supportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,
+ sessionAffinityFormat: model.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model),
+ supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,
+ supportsStrictMode: model.compat?.supportsStrictMode ?? false,
+ supportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false,
+ supportsAdditionalTools: model.compat?.supportsAdditionalTools ?? false,
+ supportsToolSearch: model.compat?.supportsToolSearch ?? false,
+ supportsExplicitPromptCacheMode: model.compat?.supportsExplicitPromptCacheMode ?? false,
+ supportsMaxOutputTokens: model.compat?.supportsMaxOutputTokens ?? true
+ };
+}
+function getPromptCacheRetention(compat, cacheRetention) {
+ return cacheRetention === "long" && compat.supportsLongCacheRetention && !compat.supportsExplicitPromptCacheMode ? "24h" : void 0;
+}
+function getPromptCacheOptions(compat, cacheRetention) {
+ if (!compat.supportsExplicitPromptCacheMode)
+ return void 0;
+ if (cacheRetention === "none")
+ return { mode: "explicit" };
+ if (cacheRetention === "long" && compat.supportsLongCacheRetention)
+ return { ttl: "30m" };
+ return void 0;
+}
+function createClient2(model, context, apiKey, optionsHeaders, fetch2, sessionId) {
+ const compat = getCompat2(model);
+ const headers = { "User-Agent": getPiUserAgent(), ...model.headers };
+ if (model.provider === "github-copilot") {
+ const hasImages = hasCopilotVisionInput(context.messages);
+ const copilotHeaders = buildCopilotDynamicHeaders({
+ messages: context.messages,
+ hasImages
+ });
+ Object.assign(headers, copilotHeaders);
+ }
+ if (sessionId) {
+ if (compat.sessionAffinityFormat === "openrouter") {
+ headers["x-session-id"] = sessionId;
+ } else {
+ if (compat.sessionAffinityFormat === "openai") {
+ headers.session_id = sessionId;
+ }
+ headers["x-client-request-id"] = sessionId;
+ }
+ }
+ if (optionsHeaders) {
+ Object.assign(headers, optionsHeaders);
+ }
+ return new OpenAI({
+ apiKey,
+ baseURL: model.baseUrl,
+ dangerouslyAllowBrowser: true,
+ fetch: fetch2,
+ defaultHeaders: headers
+ });
+}
+function buildParams2(model, context, options, compat = getCompat2(model), grammarToolInputProperties = createGrammarToolInputProperties(getDeclaredTools(context.messages), compat.supportsOpenAIGrammarTools)) {
+ const transcriptTools = resolveTranscriptTools(context.messages, compat.supportsAdditionalTools || compat.supportsToolSearch);
+ const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {
+ grammarToolInputProperties,
+ supportsMidConvoSystemMessages: compat.supportsMidConvoSystemMessages,
+ supportsAdditionalTools: compat.supportsAdditionalTools,
+ supportsToolSearch: compat.supportsToolSearch,
+ toolOptions: {
+ supportsStrictMode: compat.supportsStrictMode,
+ supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools
+ }
+ });
+ const cacheRetention = resolveCacheRetention2(options?.cacheRetention, options?.env);
+ const omitUnsupportedFields = isChatGPTSignIn(model, options?.apiKey);
+ const params = {
+ model: model.id,
+ input: messages,
+ stream: true,
+ prompt_cache_key: cacheRetention === "none" ? void 0 : clampOpenAIPromptCacheKey(options?.sessionId),
+ prompt_cache_retention: omitUnsupportedFields ? void 0 : getPromptCacheRetention(compat, cacheRetention),
+ prompt_cache_options: omitUnsupportedFields ? void 0 : getPromptCacheOptions(compat, cacheRetention),
+ store: false
+ };
+ if (options?.maxTokens && compat.supportsMaxOutputTokens && !omitUnsupportedFields) {
+ params.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);
+ }
+ if (options?.temperature !== void 0 && !omitUnsupportedFields) {
+ params.temperature = options?.temperature;
+ }
+ if (options?.serviceTier !== void 0) {
+ params.service_tier = options.serviceTier;
+ }
+ if (transcriptTools.requestTools.length > 0) {
+ params.tools = convertResponsesTools(transcriptTools.requestTools, {
+ supportsStrictMode: compat.supportsStrictMode,
+ supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools
+ });
+ }
+ if (options?.toolChoice !== void 0) {
+ params.tool_choice = options.toolChoice;
+ }
+ const reasoningEffort = options?.reasoningEffort ?? (options?.reasoningSummary ? "medium" : void 0);
+ if (model.reasoning) {
+ if (reasoningEffort) {
+ const effort = options?.reasoningEffort ? model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort : reasoningEffort;
+ params.reasoning = {
+ effort,
+ summary: options?.reasoningSummary || "auto"
+ };
+ params.include = ["reasoning.encrypted_content"];
+ } else if (model.provider !== "github-copilot" && model.thinkingLevelMap?.off !== null) {
+ params.reasoning = {
+ effort: model.thinkingLevelMap?.off ?? "none"
+ };
+ }
+ if (model.provider === "xai")
+ params.include = ["reasoning.encrypted_content"];
+ }
+ const samplingParams = resolveSamplingParams(model, reasoningEffort ?? "off", options?.samplingParams);
+ if (samplingParams) {
+ Object.assign(params, samplingParams);
+ }
+ return params;
+}
+function getServiceTierCostMultiplier(model, serviceTier) {
+ switch (serviceTier) {
+ case "flex":
+ return 0.5;
+ case "priority":
+ case "fast":
+ return model.id === "gpt-5.5" ? 2.5 : 2;
+ default:
+ return 1;
+ }
+}
+function applyServiceTierPricing(usage, serviceTier, model) {
+ const multiplier = getServiceTierCostMultiplier(model, serviceTier);
+ if (multiplier === 1)
+ return;
+ usage.cost.input *= multiplier;
+ usage.cost.output *= multiplier;
+ usage.cost.cacheRead *= multiplier;
+ usage.cost.cacheWrite *= multiplier;
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
+}
+var OPENAI_TOOL_CALL_PROVIDERS, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS, CHATGPT_USAGE_URL, stream2, streamSimple2;
+var init_openai_responses = __esm({
+ "node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js"() {
+ init_openai();
+ init_models();
+ init_error_body();
+ init_event_stream();
+ init_headers2();
+ init_pi_user_agent();
+ init_provider_env();
+ init_provider_retry();
+ init_transcript();
+ init_constrained_sampling();
+ init_github_copilot_headers();
+ init_openai_prompt_cache();
+ init_openai_responses_shared();
+ init_simple_options();
+ OPENAI_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]);
+ OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;
+ CHATGPT_USAGE_URL = "https://chatgpt.com/settings/usage";
+ stream2 = (model, context, options) => {
+ const stream3 = new AssistantMessageEventStream();
+ const normalizedContext = resolveTranscript(context, getCompat2(model).supportsMidConvoSystemMessages);
+ (async () => {
+ const output = {
+ role: "assistant",
+ content: [],
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
+ },
+ stopReason: "pending",
+ timestamp: Date.now()
+ };
+ try {
+ const apiKey = getClientApiKey2(model.provider, options?.apiKey, options?.headers);
+ const cacheRetention = resolveCacheRetention2(options?.cacheRetention, options?.env);
+ const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
+ const compat = getCompat2(model);
+ const grammarToolInputProperties = createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages), compat.supportsOpenAIGrammarTools);
+ const client = createClient2(model, normalizedContext, apiKey, options?.headers, options?.fetch, cacheSessionId);
+ let params = buildParams2(model, normalizedContext, options, compat, grammarToolInputProperties);
+ const nextParams = await options?.onPayload?.(params, model);
+ if (nextParams !== void 0) {
+ params = nextParams;
+ }
+ const requestOptions = {
+ ...options?.signal ? { signal: options.signal } : {},
+ ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
+ maxRetries: 0
+ };
+ const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {
+ maxRetries: options?.maxRetries,
+ maxRetryDelayMs: options?.maxRetryDelayMs,
+ signal: options?.signal
+ });
+ await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
+ stream3.push({ type: "start", partial: output });
+ await processResponsesStream(openaiStream, output, stream3, model, {
+ onProviderStreamEvent: options?.onProviderStreamEvent,
+ serviceTier: options?.serviceTier,
+ grammarToolInputProperties,
+ applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model)
+ });
+ if (options?.signal?.aborted) {
+ throw new Error("Request was aborted");
+ }
+ if (output.stopReason === "pending") {
+ throw new Error("OpenAI Responses stream ended without a stop reason");
+ }
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
+ throw new Error(output.errorMessage || "An unknown error occurred");
+ }
+ stream3.push({ type: "done", reason: output.stopReason, message: output });
+ stream3.end();
+ } catch (error) {
+ for (const block of output.content) {
+ delete block.index;
+ delete block.partialJson;
+ delete block.customInput;
+ }
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
+ const errorMessage = formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);
+ output.errorMessage = errorMessage.includes("subscription_sharing_usage_limit_exceeded") ? `${errorMessage}
+Check your ChatGPT usage: ${CHATGPT_USAGE_URL}` : errorMessage;
+ stream3.push({ type: "error", reason: output.stopReason, error: output });
+ stream3.end();
+ }
+ })();
+ return stream3;
+ };
+ streamSimple2 = (model, context, options) => {
+ getClientApiKey2(model.provider, options?.apiKey, options?.headers);
+ const base = {
+ ...buildBaseOptions(model, context, options, options?.apiKey),
+ toolChoice: options?.toolChoice
+ };
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
+ const reasoningEffort = clampedReasoning === "off" ? void 0 : clampedReasoning;
+ return stream2(model, context, {
+ ...base,
+ reasoningEffort
+ });
+ };
+ }
+});
+
+// src/runner.mjs
+import { fileURLToPath as fileURLToPath2 } from "node:url";
+
+// src/engine.mjs
+import path3 from "node:path";
+
+// node_modules/@earendil-works/chord/dist/context/index.js
+var ABORT_SIGNAL_CONTEXT_KEY = Object.freeze({
+ token: Symbol("chord.abortSignal")
+});
+var BaseContext = class {
+ get abortSignal() {
+ return this.value(ABORT_SIGNAL_CONTEXT_KEY);
+ }
+};
+var EmptyContext = class extends BaseContext {
+ #name;
+ constructor(name) {
+ super();
+ this.#name = name;
+ }
+ value(_key) {
+ return void 0;
+ }
+ toString() {
+ return this.#name;
+ }
+};
+var ContextValue = class extends BaseContext {
+ #parent;
+ #key;
+ #value;
+ constructor(parent, key, value) {
+ super();
+ this.#parent = parent;
+ this.#key = key;
+ this.#value = value;
+ }
+ value(key) {
+ if (key.token === this.#key.token)
+ return this.#value;
+ return this.#parent.value(key);
+ }
+ toString() {
+ return `${this.#parent}.WithValue(${this.#key.token.description ?? "anonymous"})`;
+ }
+};
+var BACKGROUND_CONTEXT = new EmptyContext("[Context BACKGROUND_CONTEXT]");
+var TODO_CONTEXT = new EmptyContext("[Context TODO_CONTEXT]");
+function withContextValue(key, value, parent) {
+ return new ContextValue(parent, key, value);
+}
+function withAbortSignal(signal, context) {
+ const parentSignal = context.abortSignal;
+ const combined = parentSignal === void 0 ? signal : AbortSignal.any([parentSignal, signal]);
+ return withContextValue(ABORT_SIGNAL_CONTEXT_KEY, combined, context);
+}
+function withoutAbortSignal(context) {
+ return withContextValue(ABORT_SIGNAL_CONTEXT_KEY, void 0, context);
+}
+function awaitWithContext(promise, context) {
+ const signal = context.abortSignal;
+ if (signal === void 0)
+ return promise;
+ if (signal.aborted)
+ return Promise.reject(abortError(signal));
+ return new Promise((resolve3, reject) => {
+ const onAbort = () => reject(abortError(signal));
+ signal.addEventListener("abort", onAbort, { once: true });
+ void promise.then((value) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve3(value);
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function abortError(signal) {
+ const reason = signal.reason;
+ return reason instanceof Error ? reason : new DOMException("The operation was aborted", "AbortError");
+}
+
+// src/engine.mjs
+init_models();
+
+// node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
+init_lazy();
+var openAICompletionsApi = () => lazyApi(() => Promise.resolve().then(() => (init_openai_completions(), openai_completions_exports)));
+
+// node_modules/@earendil-works/pi-ai/dist/api/openai-responses.lazy.js
+init_lazy();
+var openAIResponsesApi = () => lazyApi(() => Promise.resolve().then(() => (init_openai_responses(), openai_responses_exports)));
+
+// src/engine.mjs
+init_event_stream();
+
+// node_modules/@earendil-works/chord/dist/json.js
+var DATA_DESCRIPTOR = {
+ value: void 0,
+ writable: true,
+ enumerable: true,
+ configurable: true
+};
+function copyJson(value, options) {
+ return copy(value, void 0, options?.omitUndefinedProperties === true);
+}
+function copy(value, ancestors, omitUndefinedProperties) {
+ if (value === null || typeof value === "string" || typeof value === "boolean")
+ return value;
+ if (typeof value === "number") {
+ if (Number.isFinite(value))
+ return value;
+ throw new TypeError("Value contains a non-finite number and is not strict JSON");
+ }
+ if (typeof value !== "object")
+ throw new TypeError(`Value contains a non-JSON ${typeof value}; expected strict JSON`);
+ const active = ancestors ?? /* @__PURE__ */ new Set();
+ if (active.has(value))
+ throw new TypeError("Value contains cycles and is not strict JSON");
+ active.add(value);
+ try {
+ if (Array.isArray(value)) {
+ if (Object.getPrototypeOf(value) !== Array.prototype || Reflect.ownKeys(value).length !== value.length + 1) {
+ throw new TypeError("Value must contain strict JSON dense plain arrays");
+ }
+ const result2 = new Array(value.length);
+ for (let index3 = 0; index3 < value.length; index3++) {
+ const descriptor = Object.getOwnPropertyDescriptor(value, index3);
+ if (descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor)) {
+ throw new TypeError("Value must contain strict JSON enumerable indexed data properties");
+ }
+ defineData(result2, String(index3), copy(descriptor.value, active, omitUndefinedProperties));
+ }
+ return result2;
+ }
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null) {
+ throw new TypeError("Value must contain strict JSON plain objects or arrays");
+ }
+ const result = Object.create(prototype);
+ for (const key of Reflect.ownKeys(value)) {
+ if (typeof key === "symbol")
+ throw new TypeError("Value contains a symbol key and is not strict JSON");
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
+ if (!descriptor.enumerable || !("value" in descriptor)) {
+ throw new TypeError("Value must contain strict JSON enumerable data properties");
+ }
+ if (descriptor.value === void 0 && omitUndefinedProperties)
+ continue;
+ defineData(result, key, copy(descriptor.value, active, omitUndefinedProperties));
+ }
+ return result;
+ } finally {
+ active.delete(value);
+ }
+}
+function defineData(target, key, value) {
+ DATA_DESCRIPTOR.value = value;
+ Object.defineProperty(target, key, DATA_DESCRIPTOR);
+ DATA_DESCRIPTOR.value = void 0;
+}
+
+// node_modules/@earendil-works/chord/dist/delta/apply-immutable-trusted.js
+var DATA_DESCRIPTOR2 = {
+ value: void 0,
+ writable: true,
+ enumerable: true,
+ configurable: true
+};
+function applyImmutableTrusted(target, operations) {
+ let root = target;
+ const owned = /* @__PURE__ */ new WeakSet();
+ for (const operation of operations) {
+ if (operation[0] === "r") {
+ root = operation[1];
+ continue;
+ }
+ if (operation[0] === "p" || operation[0] === "m") {
+ const copied2 = copyPath(root, operation[1], operation[1].length, owned);
+ root = copied2.root;
+ if (!Array.isArray(copied2.target))
+ throw new TypeError("Trusted array operation target is not an array");
+ if (operation[0] === "p")
+ spliceTrusted(copied2.target, operation[2], operation[3], operation[4]);
+ else
+ permuteTrusted(copied2.target, operation[2]);
+ continue;
+ }
+ const path5 = operation[1];
+ const copied = copyPath(root, path5, path5.length - 1, owned);
+ root = copied.root;
+ const key = path5[path5.length - 1];
+ switch (operation[0]) {
+ case "s":
+ defineData2(copied.target, key, operation[2]);
+ break;
+ case "d":
+ if (Array.isArray(copied.target)) {
+ if (typeof key !== "number")
+ throw new TypeError("Trusted array deletion key is not numeric");
+ spliceTrusted(copied.target, key, 1, []);
+ } else
+ Reflect.deleteProperty(copied.target, key);
+ break;
+ case "a": {
+ const current = read(copied.target, key);
+ if (typeof current !== "string")
+ throw new TypeError("Trusted append target is not a string");
+ defineData2(copied.target, key, `${current}${operation[2]}`);
+ break;
+ }
+ case "t": {
+ const current = read(copied.target, key);
+ if (typeof current !== "string")
+ throw new TypeError("Trusted truncate target is not a string");
+ defineData2(copied.target, key, current.slice(operation[2]));
+ break;
+ }
+ }
+ }
+ return root;
+}
+function copyPath(root, path5, length, owned) {
+ if (!isContainer(root))
+ throw new TypeError("Trusted operation root is not a container");
+ let copiedRoot = root;
+ if (!owned.has(root)) {
+ copiedRoot = shallowCopy(root);
+ owned.add(copiedRoot);
+ }
+ let destination = copiedRoot;
+ for (let index3 = 0; index3 < length; index3++) {
+ const segment = path5[index3];
+ const child = read(destination, segment);
+ if (!isContainer(child))
+ throw new TypeError("Trusted operation path is not a container");
+ if (owned.has(child)) {
+ destination = child;
+ continue;
+ }
+ const copy2 = shallowCopy(child);
+ defineData2(destination, segment, copy2);
+ owned.add(copy2);
+ destination = copy2;
+ }
+ return { root: copiedRoot, target: destination };
+}
+function shallowCopy(value) {
+ if (Array.isArray(value))
+ return Array.from(value);
+ const result = Object.create(Object.getPrototypeOf(value) === null ? null : Object.prototype);
+ for (const key of Object.keys(value))
+ defineData2(result, key, value[key]);
+ return result;
+}
+function read(target, key) {
+ return target[key];
+}
+function defineData2(target, key, value) {
+ DATA_DESCRIPTOR2.value = value;
+ Object.defineProperty(target, key, DATA_DESCRIPTOR2);
+ DATA_DESCRIPTOR2.value = void 0;
+}
+function spliceTrusted(target, start, remove, items) {
+ const oldLength = target.length;
+ const delta = items.length - remove;
+ if (delta > 0) {
+ target.length = oldLength + delta;
+ target.copyWithin(start + items.length, start + remove, oldLength);
+ } else if (delta < 0) {
+ target.copyWithin(start + items.length, start + remove, oldLength);
+ target.length = oldLength + delta;
+ }
+ for (let index3 = 0; index3 < items.length; index3++)
+ defineData2(target, start + index3, items[index3]);
+}
+function permuteTrusted(target, permutation) {
+ if (target.length !== permutation.length)
+ throw new TypeError("Trusted permutation length mismatch");
+ const previous = target.slice();
+ for (let index3 = 0; index3 < permutation.length; index3++)
+ target[index3] = previous[permutation[index3]];
+}
+function isContainer(value) {
+ return value !== null && typeof value === "object";
+}
+
+// node_modules/@earendil-works/chord/dist/delta/tracker.js
+var NODE = Symbol("chord.delta.overlay.node");
+var PREPARED = /* @__PURE__ */ new WeakMap();
+var RELEASED = {};
+var ARRAY_MUTATORS = /* @__PURE__ */ new Set([
+ "push",
+ "pop",
+ "shift",
+ "unshift",
+ "splice",
+ "reverse",
+ "sort",
+ "fill",
+ "copyWithin"
+]);
+var MAX_DELTA_OPERATIONS = 4096;
+var MAX_SIMPLE_OBJECT_NODES = 128;
+var DATA_DESCRIPTOR3 = {
+ value: void 0,
+ writable: true,
+ enumerable: true,
+ configurable: true
+};
+var PreparedImpl = class {
+ #context;
+ value;
+ base;
+ ops;
+ constructor(context, value, operations) {
+ this.#context = context;
+ this.value = value;
+ this.base = context.baseValue;
+ this.ops = operations;
+ PREPARED.set(this, context);
+ }
+ get baseRevision() {
+ return this.#context.baseRevision;
+ }
+ abort() {
+ abortContext(this.#context);
+ }
+};
+var ChangeImpl = class {
+ #context;
+ #preparedStatus;
+ #settled = false;
+ constructor(context) {
+ this.#context = context;
+ }
+ get state() {
+ const state3 = this.#context?.root?.proxy;
+ if (state3 === void 0)
+ throw new TypeError("Cannot use a settled overlay");
+ return state3;
+ }
+ prepare() {
+ if (this.#settled)
+ throw new Error("Change has already been settled");
+ const context = this.#context;
+ assertWritable(context);
+ context.status.value = "prepared";
+ try {
+ if (!context.replacement)
+ context.ops = context.dirty.length === 0 ? [] : emitOperations(context);
+ const prepared = materializePrepared(context);
+ this.#preparedStatus = context.status;
+ this.#settled = true;
+ return prepared;
+ } catch (error) {
+ context.status.value = "aborted";
+ clearContext(context);
+ this.#settled = true;
+ throw error;
+ } finally {
+ this.#context = void 0;
+ }
+ }
+ abort() {
+ if (this.#settled) {
+ if (this.#preparedStatus?.value === "prepared")
+ this.#preparedStatus.value = "aborted";
+ this.#preparedStatus = void 0;
+ return;
+ }
+ this.#settled = true;
+ abortContext(this.#context);
+ this.#context = void 0;
+ }
+};
+var TrackerImpl = class {
+ #owner = {};
+ #contexts = /* @__PURE__ */ new Set();
+ #selfRef;
+ #value;
+ #revision = 0;
+ #pruneBudget = 256;
+ constructor(initial) {
+ this.#value = initial;
+ this.#selfRef = new WeakRef(this);
+ }
+ get value() {
+ return this.#value;
+ }
+ get revision() {
+ return this.#revision;
+ }
+ beginChange() {
+ const context = createContext(this.#selfRef, this.#owner, this.#revision, this.#value, false, this.#value);
+ this.#register(context);
+ return new ChangeImpl(context);
+ }
+ prepareReplace(value) {
+ const context = createContext(this.#selfRef, this.#owner, this.#revision, value, true, this.#value);
+ context.status.value = "prepared";
+ this.#register(context);
+ try {
+ return materializePrepared(context);
+ } catch (error) {
+ context.status.value = "aborted";
+ clearContext(context);
+ throw error;
+ }
+ }
+ adopt(prepared) {
+ const context = PREPARED.get(prepared);
+ if (context?.owner !== this.#owner)
+ throw new Error("Prepared change belongs to a different tracker");
+ if (context.status.value === "consumed")
+ throw new Error("Prepared change has already been used");
+ if (context.status.value === "aborted")
+ throw new Error("Prepared change has been aborted");
+ if (context.status.value === "stale")
+ throw new Error("Prepared change is stale");
+ if (context.status.value !== "prepared")
+ throw new Error("Prepared change is not ready");
+ if (context.baseRevision !== this.#revision) {
+ context.status.value = "stale";
+ clearContext(context);
+ throw new Error("Prepared change is stale");
+ }
+ if (this.#value !== prepared.base) {
+ context.status.value = "stale";
+ throw new Error("Prepared change is stale");
+ }
+ this.#value = prepared.value;
+ context.status.value = "consumed";
+ this.#revision += 1;
+ this.#invalidate(context);
+ }
+ releaseContext(context) {
+ if (context.registryRef !== void 0)
+ this.#contexts.delete(context.registryRef);
+ context.registryRef = void 0;
+ }
+ #register(context) {
+ const reference = new WeakRef(context);
+ context.registryRef = reference;
+ this.#contexts.add(reference);
+ this.#pruneBudget -= 1;
+ if (this.#pruneBudget === 0) {
+ this.#prune();
+ this.#pruneBudget = Math.max(256, this.#contexts.size);
+ }
+ }
+ #prune() {
+ for (const reference of this.#contexts) {
+ if (reference.deref() === void 0)
+ this.#contexts.delete(reference);
+ }
+ }
+ #invalidate(winner) {
+ for (const reference of this.#contexts) {
+ const context = reference.deref();
+ if (context === void 0 || context === winner)
+ continue;
+ if (context.status.value === "open" || context.status.value === "prepared")
+ context.status.value = "stale";
+ releaseOverlayReferences(context);
+ }
+ this.#contexts.clear();
+ this.#pruneBudget = 256;
+ }
+ replacementBase(context) {
+ return context.baseRevision === this.#revision ? this.#value : void 0;
+ }
+};
+function track(initial) {
+ return new TrackerImpl(initial);
+}
+function materializePrepared(context) {
+ const operations = ensureOperations(context);
+ const base = context.baseValue;
+ const value = operations.length === 0 ? base : context.simpleObjectMaterialization ? cloneNode(context.root) : materializeOperations(base, operations);
+ const prepared = new PreparedImpl(context, value, operations);
+ if (context.nodes.length > 4096)
+ releaseOverlayReferences(context);
+ else
+ clearContext(context);
+ return prepared;
+}
+function materializeOperations(base, operations) {
+ for (const operation of operations) {
+ if (operation[0] === "p" || operation[0] === "m")
+ return applyImmutable(base, operations);
+ }
+ return applyImmutableTrusted(base, operations);
+}
+function createContext(tracker, owner, baseRevision, root, replacement, base) {
+ const context = {
+ owner,
+ tracker,
+ baseRevision,
+ status: { value: "open" },
+ root: void 0,
+ bases: [],
+ stored: [],
+ dirty: [],
+ nodes: [],
+ rawNodes: /* @__PURE__ */ new WeakMap(),
+ ops: void 0,
+ replacement,
+ replacementNoop: false,
+ baseValue: base,
+ overlayReleased: false,
+ simpleObjectMaterialization: false,
+ registryRef: void 0
+ };
+ context.root = createNode(context, root, void 0);
+ return context;
+}
+var sharedObjectHandler = {
+ deleteProperty(target, property) {
+ return deleteProperty(nodeForTarget(target), property);
+ },
+ defineProperty(target) {
+ assertWritable(nodeForTarget(target).context);
+ throw new TypeError("Defining overlay properties is not supported");
+ },
+ get(target, property) {
+ if (property === "then") {
+ const node2 = target[NODE];
+ if (node2 === void 0 || isSettledContext(node2.context))
+ return void 0;
+ }
+ const node = nodeForTarget(target);
+ if (property === NODE)
+ return node;
+ return getProperty(node, property);
+ },
+ getOwnPropertyDescriptor(target, property) {
+ return getDescriptor(nodeForTarget(target), property);
+ },
+ getPrototypeOf(target) {
+ const node = nodeForTarget(target);
+ assertReadable(node.context);
+ return Object.getPrototypeOf(nodeBase(node));
+ },
+ has(target, property) {
+ return hasProperty(nodeForTarget(target), property);
+ },
+ isExtensible(target) {
+ assertReadable(nodeForTarget(target).context);
+ return true;
+ },
+ ownKeys(target) {
+ return ownKeys(nodeForTarget(target));
+ },
+ preventExtensions(target) {
+ assertWritable(nodeForTarget(target).context);
+ throw new TypeError("Overlays cannot be made non-extensible");
+ },
+ set(target, property, value) {
+ return setProperty(nodeForTarget(target), property, value);
+ },
+ setPrototypeOf(target) {
+ assertWritable(nodeForTarget(target).context);
+ throw new TypeError("Changing an overlay prototype is not supported");
+ }
+};
+var sharedArrayHandler = sharedObjectHandler;
+function createNode(context, base, parent, parentKind = 0, parentKey = "", parentSource = void 0, parentPlacement = false) {
+ const existing = context.rawNodes.get(base);
+ if (existing !== void 0)
+ return existing;
+ const target = Array.isArray(base) ? [] : {};
+ const baseIndex = context.bases.length;
+ const parentIndex = parent?.baseIndex ?? -1;
+ context.bases.push(base);
+ const node = {
+ context,
+ baseIndex,
+ parentIndex,
+ parentKind,
+ parentKey,
+ parentPlacement,
+ target,
+ proxy: target
+ };
+ if (parentSource !== void 0)
+ node.parentSource = parentSource;
+ target[NODE] = node;
+ node.proxy = new Proxy(target, Array.isArray(base) ? sharedArrayHandler : sharedObjectHandler);
+ context.rawNodes.set(base, node);
+ context.nodes.push(node);
+ return node;
+}
+function nodeBase(node) {
+ return node.context.bases[node.baseIndex];
+}
+function nodeParent(node) {
+ return node.parentIndex < 0 ? void 0 : node.context.nodes[node.parentIndex];
+}
+function storeValue(context, value) {
+ if (!isContainer2(value))
+ return value;
+ const index3 = context.stored.length;
+ context.stored.push(value);
+ return { index: index3 };
+}
+function storedValue(context, reference) {
+ return typeof reference === "object" && reference !== null ? context.stored[reference.index] : reference;
+}
+function replaceStoredValue(context, reference, value) {
+ if (isContainer2(value)) {
+ if (typeof reference === "object" && reference !== null) {
+ context.stored[reference.index] = value;
+ return reference;
+ }
+ return storeValue(context, value);
+ }
+ if (typeof reference === "object" && reference !== null)
+ context.stored[reference.index] = RELEASED;
+ return value;
+}
+function releaseStoredValue(context, reference) {
+ if (typeof reference === "object" && reference !== null)
+ context.stored[reference.index] = RELEASED;
+}
+function nodeForTarget(target) {
+ const node = target[NODE];
+ if (node === void 0)
+ throw new TypeError("Cannot use a settled overlay");
+ return node;
+}
+function isSettledContext(context) {
+ return context.overlayReleased || context.status.value === "consumed" || context.status.value === "aborted" || context.status.value === "stale";
+}
+function assertReadable(context) {
+ if (isSettledContext(context))
+ throw new TypeError("Cannot use a settled overlay");
+}
+function assertWritable(context) {
+ assertReadable(context);
+ if (context.status.value !== "open")
+ throw new TypeError("Prepared overlays are read-only");
+}
+function getProperty(node, property) {
+ assertReadable(node.context);
+ if (Array.isArray(nodeBase(node))) {
+ const overlay = arrayOverlay(node);
+ if (property === "length")
+ return arrayLength(overlay);
+ if (ARRAY_MUTATORS.has(property))
+ return arrayMutators[property];
+ const index3 = arrayIndex(property);
+ if (index3 !== void 0)
+ return getArrayIndex(node, index3);
+ return Reflect.get(Array.prototype, property, node.proxy);
+ }
+ if (typeof property === "symbol")
+ return Reflect.get(nodeBase(node), property, node.proxy);
+ const key = String(property);
+ if (!objectHas(node, key)) {
+ if (isObjectDeleted(node, key) || Object.hasOwn(nodeBase(node), key))
+ return void 0;
+ return Reflect.get(nodeBase(node), property, node.proxy);
+ }
+ const value = objectValue(node, key);
+ if (!isContainer2(value))
+ return value;
+ return createNode(node.context, value, node, 0, key, void 0, hasObjectWrite(node, key)).proxy;
+}
+function getArrayIndex(node, index3) {
+ const overlay = arrayOverlay(node);
+ if (index3 >= arrayLength(overlay))
+ return void 0;
+ const piece = locatePiece(overlay, index3);
+ const sourceIndex = piece.start + piece.step * overlay.locatedOffset;
+ const value = entryValueAt(node, piece, sourceIndex);
+ if (!isContainer2(value))
+ return value;
+ return createNode(node.context, value, node, piece.kind === "base" ? 1 : 2, sourceIndex, piece.kind === "insert" ? piece.source : void 0, piece.kind === "insert" || hasEntryOverrideAt(overlay, piece, sourceIndex)).proxy;
+}
+function setProperty(node, property, supplied) {
+ assertWritable(node.context);
+ if (typeof property === "symbol")
+ throw new TypeError("Symbol writes are not supported");
+ if (Array.isArray(nodeBase(node))) {
+ if (property === "length") {
+ setArrayLength(node, toArrayLength(supplied));
+ return true;
+ }
+ const index3 = arrayIndex(property);
+ if (index3 === void 0)
+ throw new TypeError("Only array indices and length can be written");
+ if (index3 > arrayLength(arrayOverlay(node)))
+ throw new TypeError("Overlay arrays cannot contain holes");
+ setArrayIndex(node, index3, clonePlacement(supplied));
+ return true;
+ }
+ const key = String(property);
+ if (supplied === void 0)
+ return deleteProperty(node, key);
+ const stored = clonePlacement(supplied);
+ const current = objectValue(node, key);
+ const wasDeleted = isObjectDeleted(node, key);
+ if (!wasDeleted && !isContainer2(stored) && current === stored)
+ return true;
+ setObjectWrite(node, key, stored);
+ if (wasDeleted && Object.hasOwn(nodeBase(node), key)) {
+ if (node.readded === void 0)
+ node.readded = /* @__PURE__ */ new Set();
+ node.readded.add(key);
+ }
+ deleteObjectDeletion(node, key);
+ markDirty(node);
+ return true;
+}
+function deleteProperty(node, property) {
+ assertWritable(node.context);
+ if (typeof property === "symbol")
+ throw new TypeError("Symbol writes are not supported");
+ if (Array.isArray(nodeBase(node)))
+ throw new TypeError("Overlay arrays cannot contain holes");
+ const key = String(property);
+ if (!objectHas(node, key))
+ return true;
+ deleteObjectWrite(node, key);
+ node.readded?.delete(key);
+ setObjectDeletion(node, key);
+ markDirty(node);
+ return true;
+}
+function hasProperty(node, property) {
+ assertReadable(node.context);
+ if (Array.isArray(nodeBase(node))) {
+ if (property === "length")
+ return true;
+ const index3 = arrayIndex(property);
+ if (index3 !== void 0)
+ return index3 < arrayLength(arrayOverlay(node));
+ return property in Array.prototype;
+ }
+ return typeof property === "symbol" ? property in nodeBase(node) : objectHas(node, String(property));
+}
+function ownKeys(node) {
+ assertReadable(node.context);
+ if (Array.isArray(nodeBase(node))) {
+ const length = arrayLength(arrayOverlay(node));
+ const keys2 = new Array(length + 1);
+ for (let index3 = 0; index3 < length; index3++)
+ keys2[index3] = String(index3);
+ keys2[length] = "length";
+ return keys2;
+ }
+ let existingKeysOnly = node.deleteKey === void 0 && node.deletes === void 0 && node.readded === void 0 && (node.writeKey === void 0 || Object.hasOwn(nodeBase(node), node.writeKey));
+ if (existingKeysOnly && node.writes !== void 0) {
+ for (const key of node.writes.keys()) {
+ if (!Object.hasOwn(nodeBase(node), key)) {
+ existingKeysOnly = false;
+ break;
+ }
+ }
+ }
+ if (existingKeysOnly)
+ return Object.keys(nodeBase(node));
+ const keys = Object.keys(nodeBase(node)).filter((key) => !isObjectDeleted(node, key) && !node.readded?.has(key));
+ const seen = new Set(keys);
+ if (node.writeKey !== void 0 && !seen.has(node.writeKey)) {
+ keys.push(node.writeKey);
+ seen.add(node.writeKey);
+ }
+ if (node.writes !== void 0) {
+ for (const key of node.writes.keys()) {
+ if (seen.has(key))
+ continue;
+ keys.push(key);
+ seen.add(key);
+ }
+ }
+ const indices = [];
+ const strings = [];
+ for (const key of keys) {
+ const index3 = arrayIndex(key);
+ if (index3 === void 0)
+ strings.push(key);
+ else
+ indices.push(index3);
+ }
+ indices.sort((left, right) => left - right);
+ return [...indices.map(String), ...strings];
+}
+function getDescriptor(node, property) {
+ assertReadable(node.context);
+ if (Array.isArray(nodeBase(node))) {
+ if (property === "length") {
+ const length = arrayLength(arrayOverlay(node));
+ node.target.length = length;
+ return Reflect.getOwnPropertyDescriptor(node.target, "length");
+ }
+ const index3 = arrayIndex(property);
+ if (index3 === void 0 || index3 >= arrayLength(arrayOverlay(node)))
+ return void 0;
+ } else {
+ if (typeof property === "symbol" || !objectHas(node, String(property)))
+ return void 0;
+ }
+ return {
+ configurable: true,
+ enumerable: true,
+ writable: node.context.status.value === "open",
+ value: getProperty(node, property)
+ };
+}
+function hasObjectWrite(node, key) {
+ return node.writeKey === key || (node.writes?.has(key) ?? false);
+}
+function setObjectWrite(node, key, value) {
+ if (node.writes !== void 0) {
+ const reference = node.writes.get(key);
+ node.writes.set(key, reference === void 0 ? storeValue(node.context, value) : replaceStoredValue(node.context, reference, value));
+ return;
+ }
+ if (node.writeKey === void 0 || node.writeKey === key) {
+ node.writeKey = key;
+ node.writeValue = node.writeValue === void 0 ? storeValue(node.context, value) : replaceStoredValue(node.context, node.writeValue, value);
+ return;
+ }
+ node.writes = /* @__PURE__ */ new Map();
+ node.writes.set(node.writeKey, node.writeValue);
+ node.writes.set(key, storeValue(node.context, value));
+ node.writeKey = void 0;
+ node.writeValue = void 0;
+}
+function deleteObjectWrite(node, key) {
+ if (node.writeKey === key) {
+ node.writeKey = void 0;
+ releaseStoredValue(node.context, node.writeValue);
+ node.writeValue = void 0;
+ } else {
+ const reference = node.writes?.get(key);
+ if (reference !== void 0)
+ releaseStoredValue(node.context, reference);
+ node.writes?.delete(key);
+ }
+}
+function isObjectDeleted(node, key) {
+ return node.deleteKey === key || (node.deletes?.has(key) ?? false);
+}
+function setObjectDeletion(node, key) {
+ if (node.deletes !== void 0) {
+ node.deletes.add(key);
+ return;
+ }
+ if (node.deleteKey === void 0 || node.deleteKey === key) {
+ node.deleteKey = key;
+ return;
+ }
+ node.deletes = /* @__PURE__ */ new Set();
+ node.deletes.add(node.deleteKey);
+ node.deletes.add(key);
+ node.deleteKey = void 0;
+}
+function deleteObjectDeletion(node, key) {
+ if (node.deleteKey === key)
+ node.deleteKey = void 0;
+ else
+ node.deletes?.delete(key);
+}
+function objectHas(node, key) {
+ if (isObjectDeleted(node, key))
+ return false;
+ return hasObjectWrite(node, key) || Object.hasOwn(nodeBase(node), key);
+}
+function objectValue(node, key) {
+ if (node.writeKey === key)
+ return storedValue(node.context, node.writeValue);
+ const reference = node.writes?.get(key);
+ if (reference !== void 0)
+ return storedValue(node.context, reference);
+ return nodeBase(node)[key];
+}
+function markDirty(node) {
+ if (node.dirty)
+ return;
+ node.dirty = true;
+ node.context.dirty.push(node);
+ for (let parent = nodeParent(node); parent !== void 0; parent = nodeParent(parent))
+ parent.subtreeDirty = true;
+}
+function arrayOverlay(node) {
+ if (node.array !== void 0)
+ return node.array;
+ const base = nodeBase(node);
+ const overlay = {
+ root: void 0,
+ pieces: void 0,
+ baseOverrides: void 0,
+ insertOverrides: void 0,
+ structural: false,
+ generation: 0,
+ plan: void 0,
+ seed: 2654435769,
+ locatedOffset: 0,
+ baseLocations: void 0,
+ insertLocations: void 0
+ };
+ if (base.length > 0)
+ overlay.root = createPieceNode(overlay, { kind: "base", start: 0, length: base.length, step: 1 });
+ node.array = overlay;
+ return overlay;
+}
+function baseOverridesForWrite(overlay) {
+ if (overlay.baseOverrides === void 0)
+ overlay.baseOverrides = /* @__PURE__ */ new Map();
+ return overlay.baseOverrides;
+}
+function insertOverridesForWrite(overlay) {
+ if (overlay.insertOverrides === void 0)
+ overlay.insertOverrides = /* @__PURE__ */ new Map();
+ return overlay.insertOverrides;
+}
+function nextPiecePriority(overlay) {
+ let value = overlay.seed;
+ value ^= value << 13;
+ value ^= value >>> 17;
+ value ^= value << 5;
+ overlay.seed = value >>> 0;
+ return overlay.seed;
+}
+function treeElements(node) {
+ return node?.elements ?? 0;
+}
+function updatePieceNode(node) {
+ node.elements = treeElements(node.left) + node.piece.length + treeElements(node.right);
+}
+function createPieceNode(overlay, piece) {
+ return { piece, left: void 0, right: void 0, priority: nextPiecePriority(overlay), elements: piece.length };
+}
+function mergePieceTrees(left, right) {
+ if (left === void 0)
+ return right;
+ if (right === void 0)
+ return left;
+ if (left.priority >= right.priority) {
+ left.right = mergePieceTrees(left.right, right);
+ updatePieceNode(left);
+ return left;
+ }
+ right.left = mergePieceTrees(left, right.left);
+ updatePieceNode(right);
+ return right;
+}
+function splitPieceTree(overlay, root, index3) {
+ if (root === void 0)
+ return [void 0, void 0];
+ const leftLength = treeElements(root.left);
+ if (index3 < leftLength) {
+ const [left, right] = splitPieceTree(overlay, root.left, index3);
+ root.left = right;
+ updatePieceNode(root);
+ return [left, root];
+ }
+ const pieceEnd = leftLength + root.piece.length;
+ if (index3 > pieceEnd) {
+ const [left, right] = splitPieceTree(overlay, root.right, index3 - pieceEnd);
+ root.right = left;
+ updatePieceNode(root);
+ return [root, right];
+ }
+ if (index3 === leftLength) {
+ const left = root.left;
+ root.left = void 0;
+ updatePieceNode(root);
+ return [left, root];
+ }
+ if (index3 === pieceEnd) {
+ const right = root.right;
+ root.right = void 0;
+ updatePieceNode(root);
+ return [root, right];
+ }
+ const offset = index3 - leftLength;
+ const first = { ...root.piece, length: offset };
+ const second = {
+ ...root.piece,
+ start: root.piece.start + root.piece.step * offset,
+ length: root.piece.length - offset
+ };
+ return [
+ mergePieceTrees(root.left, createPieceNode(overlay, first)),
+ mergePieceTrees(createPieceNode(overlay, second), root.right)
+ ];
+}
+function leftmostPieceNode(node) {
+ while (node.left !== void 0)
+ node = node.left;
+ return node;
+}
+function rightmostPieceNode(node) {
+ while (node.right !== void 0)
+ node = node.right;
+ return node;
+}
+function mergeablePieces(left, right) {
+ if (left.kind !== right.kind)
+ return false;
+ if (left.kind === "insert" && left.source !== right.source)
+ return false;
+ if (left.length === 1 && right.length === 1)
+ return Math.abs(right.start - left.start) === 1;
+ return left.step === right.step && left.start + left.step * left.length === right.start;
+}
+function joinNormalized(overlay, left, right) {
+ if (left === void 0)
+ return right;
+ if (right === void 0)
+ return left;
+ const leftPiece = rightmostPieceNode(left).piece;
+ const rightPiece = leftmostPieceNode(right).piece;
+ if (!mergeablePieces(leftPiece, rightPiece))
+ return mergePieceTrees(left, right);
+ const [leftRest] = splitPieceTree(overlay, left, treeElements(left) - leftPiece.length);
+ const [, rightRest] = splitPieceTree(overlay, right, rightPiece.length);
+ const step = leftPiece.length === 1 ? rightPiece.start - leftPiece.start : leftPiece.step;
+ const combined = leftPiece.kind === "base" ? { kind: "base", start: leftPiece.start, length: leftPiece.length + rightPiece.length, step } : {
+ kind: "insert",
+ source: leftPiece.source,
+ start: leftPiece.start,
+ length: leftPiece.length + rightPiece.length,
+ step
+ };
+ return joinNormalized(overlay, joinNormalized(overlay, leftRest, createPieceNode(overlay, combined)), rightRest);
+}
+function flattenPieceTree(node, output) {
+ if (node === void 0)
+ return;
+ flattenPieceTree(node.left, output);
+ output.push(node.piece);
+ flattenPieceTree(node.right, output);
+}
+function piecesOf(overlay) {
+ if (overlay.pieces === void 0) {
+ overlay.pieces = [];
+ flattenPieceTree(overlay.root, overlay.pieces);
+ }
+ return overlay.pieces;
+}
+function treeFromPieces(overlay, pieces) {
+ mergePieces(pieces);
+ let root;
+ for (const piece of pieces)
+ root = mergePieceTrees(root, createPieceNode(overlay, piece));
+ return root;
+}
+function replaceAllPieces(overlay, pieces) {
+ overlay.root = treeFromPieces(overlay, pieces);
+ overlay.pieces = void 0;
+ overlay.baseLocations = void 0;
+ overlay.insertLocations = void 0;
+}
+function arrayLength(overlay) {
+ return treeElements(overlay.root);
+}
+function locatePiece(overlay, index3) {
+ let node = overlay.root;
+ while (node !== void 0) {
+ const leftLength = treeElements(node.left);
+ if (index3 < leftLength)
+ node = node.left;
+ else if (index3 >= leftLength + node.piece.length) {
+ index3 -= leftLength + node.piece.length;
+ node = node.right;
+ } else {
+ overlay.locatedOffset = index3 - leftLength;
+ return node.piece;
+ }
+ }
+ throw new RangeError("Array overlay index is out of range");
+}
+function arrayIndex(property) {
+ if (typeof property !== "string" || property.length === 0 || property.length > 10)
+ return void 0;
+ if (property === "0")
+ return 0;
+ const first = property.charCodeAt(0);
+ if (first < 49 || first > 57)
+ return void 0;
+ let index3 = first - 48;
+ for (let offset = 1; offset < property.length; offset++) {
+ const digit = property.charCodeAt(offset) - 48;
+ if (digit < 0 || digit > 9)
+ return void 0;
+ index3 = index3 * 10 + digit;
+ if (index3 >= 4294967295)
+ return void 0;
+ }
+ return index3;
+}
+function entryValueAt(node, piece, sourceIndex) {
+ const overlay = arrayOverlay(node);
+ if (piece.kind === "base") {
+ const valueIndex = overlay.baseOverrides?.get(sourceIndex);
+ return valueIndex === void 0 ? nodeBase(node)[sourceIndex] : storedValue(node.context, valueIndex);
+ }
+ const overrides = overlay.insertOverrides?.get(piece.source);
+ const reference = overrides?.has(sourceIndex) ? overrides.get(sourceIndex) : piece.source.refs[sourceIndex];
+ return storedValue(node.context, reference);
+}
+function hasEntryOverrideAt(overlay, piece, sourceIndex) {
+ return piece.kind === "base" ? overlay.baseOverrides?.has(sourceIndex) ?? false : overlay.insertOverrides?.get(piece.source)?.has(sourceIndex) ?? false;
+}
+function extendRightmostPiece(node, amount) {
+ if (node.right !== void 0)
+ extendRightmostPiece(node.right, amount);
+ else
+ node.piece.length += amount;
+ updatePieceNode(node);
+}
+function invalidatePieceCaches(overlay) {
+ overlay.pieces = void 0;
+ overlay.baseLocations = void 0;
+ overlay.insertLocations = void 0;
+ overlay.plan = void 0;
+}
+function replacePieceRange(node, index3, remove, inserted) {
+ if (remove === 0 && inserted.length === 0)
+ return;
+ const overlay = arrayOverlay(node);
+ if (remove === 0 && index3 === arrayLength(overlay) && inserted.length === 1 && overlay.root !== void 0) {
+ const addition = inserted[0];
+ const tail = rightmostPieceNode(overlay.root).piece;
+ if (addition.kind === "insert" && tail.kind === "insert" && tail.step === 1 && tail.start + tail.length === tail.source.refs.length) {
+ for (let offset = 0; offset < addition.length; offset++) {
+ tail.source.refs.push(addition.source.refs[addition.start + offset]);
+ }
+ extendRightmostPiece(overlay.root, addition.length);
+ invalidatePieceCaches(overlay);
+ overlay.structural = true;
+ overlay.generation += 1;
+ markDirty(node);
+ return;
+ }
+ }
+ const [left, rest] = splitPieceTree(overlay, overlay.root, index3);
+ const [, right] = splitPieceTree(overlay, rest, remove);
+ const middle = treeFromPieces(overlay, inserted);
+ overlay.root = joinNormalized(overlay, joinNormalized(overlay, left, middle), right);
+ invalidatePieceCaches(overlay);
+ overlay.structural = true;
+ overlay.generation += 1;
+ markDirty(node);
+}
+function mergePieces(pieces) {
+ for (let index3 = 1; index3 < pieces.length; ) {
+ const left = pieces[index3 - 1];
+ const right = pieces[index3];
+ const sameSource = left.kind === right.kind && (left.kind === "base" || left.source === right.source);
+ if (sameSource && left.length === 1 && right.length === 1 && Math.abs(right.start - left.start) === 1) {
+ left.step = right.start - left.start;
+ left.length = 2;
+ pieces.splice(index3, 1);
+ } else if (sameSource && left.step === right.step && left.start + left.step * left.length === right.start) {
+ left.length += right.length;
+ pieces.splice(index3, 1);
+ } else
+ index3 += 1;
+ }
+}
+function insertPiece(node, items, start = 0) {
+ if (items.length === start)
+ return [];
+ const refs = [];
+ for (let index3 = start; index3 < items.length; index3++)
+ refs.push(storeValue(node.context, items[index3]));
+ return [{ kind: "insert", source: { refs }, start: 0, length: refs.length, step: 1 }];
+}
+function insertPlacementPiece(node, values, start = 0) {
+ if (values.length === start)
+ return [];
+ const storedLength = node.context.stored.length;
+ try {
+ for (let index3 = start; index3 < values.length; index3++)
+ values[index3] = storeValue(node.context, clonePlacement(values[index3]));
+ } catch (error) {
+ node.context.stored.length = storedLength;
+ throw error;
+ }
+ return [
+ {
+ kind: "insert",
+ source: { refs: values },
+ start,
+ length: values.length - start,
+ step: 1
+ }
+ ];
+}
+function setArrayIndex(node, index3, stored) {
+ const overlay = arrayOverlay(node);
+ const length = arrayLength(overlay);
+ if (index3 === length) {
+ replacePieceRange(node, length, 0, insertPiece(node, [stored]));
+ return;
+ }
+ const piece = locatePiece(overlay, index3);
+ const sourceIndex = piece.start + piece.step * overlay.locatedOffset;
+ const current = entryValueAt(node, piece, sourceIndex);
+ if (!isContainer2(stored) && current === stored)
+ return;
+ if (piece.kind === "base") {
+ const existingIndex = overlay.baseOverrides?.get(sourceIndex);
+ if (!isContainer2(stored) && stored === nodeBase(node)[sourceIndex]) {
+ if (existingIndex !== void 0)
+ releaseStoredValue(node.context, existingIndex);
+ overlay.baseOverrides?.delete(sourceIndex);
+ } else if (existingIndex === void 0) {
+ baseOverridesForWrite(overlay).set(sourceIndex, storeValue(node.context, stored));
+ } else
+ overlay.baseOverrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex, stored));
+ } else {
+ let overrides = overlay.insertOverrides?.get(piece.source);
+ const existingIndex = overrides?.get(sourceIndex);
+ if (!isContainer2(stored) && stored === storedValue(node.context, piece.source.refs[sourceIndex])) {
+ if (existingIndex !== void 0)
+ releaseStoredValue(node.context, existingIndex);
+ overrides?.delete(sourceIndex);
+ if (overrides?.size === 0)
+ overlay.insertOverrides?.delete(piece.source);
+ } else {
+ if (overrides === void 0) {
+ overrides = /* @__PURE__ */ new Map();
+ insertOverridesForWrite(overlay).set(piece.source, overrides);
+ }
+ if (existingIndex === void 0)
+ overrides.set(sourceIndex, storeValue(node.context, stored));
+ else
+ overrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex, stored));
+ }
+ }
+ markDirty(node);
+}
+function setArrayLength(node, next) {
+ const current = arrayLength(arrayOverlay(node));
+ if (next === current)
+ return;
+ if (next < current)
+ replacePieceRange(node, next, current - next, []);
+ else
+ replacePieceRange(node, current, 0, insertPiece(node, Array.from({ length: next - current }, () => null)));
+}
+function toArrayLength(value) {
+ const number = Number(value);
+ if (!Number.isInteger(number) || number < 0 || number >= 4294967296)
+ throw new RangeError("Invalid array length");
+ return number;
+}
+function toIntegerOrInfinity(value) {
+ const number = Number(value);
+ if (Number.isNaN(number) || number === 0)
+ return 0;
+ return Number.isFinite(number) ? Math.trunc(number) : number;
+}
+function clampIndex(value, length) {
+ if (value === Number.NEGATIVE_INFINITY)
+ return 0;
+ if (value < 0)
+ return Math.max(length + value, 0);
+ return Math.min(value, length);
+}
+function mutatorNode(receiver) {
+ if (!isContainer2(receiver))
+ return void 0;
+ const node = Reflect.get(receiver, NODE);
+ if (node === void 0)
+ return void 0;
+ if (!Array.isArray(nodeBase(node)))
+ throw new TypeError("Array mutator called on incompatible receiver");
+ assertWritable(node.context);
+ return node;
+}
+var arrayMutators = {
+ push(...items) {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.push, this, items);
+ const length = arrayLength(arrayOverlay(node));
+ replacePieceRange(node, length, 0, insertPlacementPiece(node, items));
+ return length + items.length;
+ },
+ pop() {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.pop, this, []);
+ const length = arrayLength(arrayOverlay(node));
+ if (length === 0)
+ return void 0;
+ const value = getArrayIndex(node, length - 1);
+ replacePieceRange(node, length - 1, 1, []);
+ return value;
+ },
+ shift() {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.shift, this, []);
+ const length = arrayLength(arrayOverlay(node));
+ if (length === 0)
+ return void 0;
+ const value = getArrayIndex(node, 0);
+ replacePieceRange(node, 0, 1, []);
+ return value;
+ },
+ unshift(...items) {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.unshift, this, items);
+ replacePieceRange(node, 0, 0, insertPlacementPiece(node, items));
+ return arrayLength(arrayOverlay(node));
+ },
+ splice(...args) {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.splice, this, args);
+ const length = arrayLength(arrayOverlay(node));
+ const start = args.length === 0 ? 0 : clampIndex(toIntegerOrInfinity(args[0]), length);
+ const remove = args.length === 0 ? 0 : args.length === 1 ? length - start : Math.min(Math.max(toIntegerOrInfinity(args[1]), 0), length - start);
+ const removed = Array.from({ length: remove }, (_, offset) => getArrayIndex(node, start + offset));
+ const itemStart = Math.min(2, args.length);
+ const itemCount = Math.max(args.length - 2, 0);
+ replacePieceRange(node, start, remove, insertPlacementPiece(node, args, itemStart));
+ setArrayLength(node, length - remove + itemCount);
+ return removed;
+ },
+ reverse() {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.reverse, this, []);
+ const overlay = arrayOverlay(node);
+ if (arrayLength(overlay) < 2)
+ return node.proxy;
+ const pieces = [...piecesOf(overlay)].reverse();
+ for (const piece of pieces) {
+ piece.start += piece.step * (piece.length - 1);
+ piece.step = piece.step === 1 ? -1 : 1;
+ }
+ replaceAllPieces(overlay, pieces);
+ overlay.structural = true;
+ overlay.generation += 1;
+ overlay.plan = void 0;
+ markDirty(node);
+ return node.proxy;
+ },
+ sort(comparator) {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.sort, this, [comparator]);
+ if (comparator !== void 0 && typeof comparator !== "function")
+ throw new TypeError("Comparator must be a function");
+ const overlay = arrayOverlay(node);
+ const insertedSources = [];
+ const insertedIndices = [];
+ const insertedValues = [];
+ const baseValues = new Array(nodeBase(node).length);
+ const order = [];
+ for (const piece of piecesOf(overlay)) {
+ for (let offset = 0; offset < piece.length; offset++) {
+ const sourceIndex = piece.start + piece.step * offset;
+ if (piece.kind === "base") {
+ order.push(sourceIndex);
+ baseValues[sourceIndex] = publicSortValue(node, sourceIndex, insertedSources, insertedIndices);
+ } else {
+ insertedSources.push(piece.source);
+ insertedIndices.push(sourceIndex);
+ const token = -insertedSources.length;
+ order.push(token);
+ insertedValues.push(publicSortValue(node, token, insertedSources, insertedIndices));
+ }
+ }
+ }
+ const baseSnapshot = /* @__PURE__ */ new Map();
+ for (const [index3, valueIndex] of overlay.baseOverrides ?? [])
+ baseSnapshot.set(index3, storedValue(node.context, valueIndex));
+ const insertSnapshots = /* @__PURE__ */ new Map();
+ for (const [source, overrides] of overlay.insertOverrides ?? []) {
+ const snapshot = /* @__PURE__ */ new Map();
+ for (const [index3, valueIndex] of overrides)
+ snapshot.set(index3, storedValue(node.context, valueIndex));
+ insertSnapshots.set(source, snapshot);
+ }
+ const generation = overlay.generation;
+ order.sort((left, right) => {
+ const leftValue = left < 0 ? insertedValues[-left - 1] : baseValues[left];
+ const rightValue = right < 0 ? insertedValues[-right - 1] : baseValues[right];
+ if (typeof comparator === "function")
+ return Number(comparator(leftValue, rightValue));
+ const a = String(leftValue);
+ const b = String(rightValue);
+ return a < b ? -1 : a > b ? 1 : 0;
+ });
+ if (baseSnapshot.size > 0 || insertSnapshots.size > 0 || (overlay.baseOverrides?.size ?? 0) > 0 || (overlay.insertOverrides?.size ?? 0) > 0) {
+ for (const token of order) {
+ restoreSortOverride(node, token, insertedSources, insertedIndices, baseSnapshot, insertSnapshots);
+ }
+ }
+ const comparatorWasStructural = overlay.generation !== generation;
+ const currentLength = arrayLength(overlay);
+ const samePrefix = currentLength >= order.length && order.every((token, index3) => sameSortTokenAt(overlay, index3, token, insertedSources, insertedIndices));
+ if (!samePrefix) {
+ replacePieceRange(node, 0, Math.min(order.length, currentLength), piecesFromSortOrder(order, insertedSources, insertedIndices));
+ }
+ if (comparatorWasStructural)
+ deduplicateArrayEntries(node);
+ return node.proxy;
+ },
+ fill(supplied, startArg, endArg) {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.fill, this, [supplied, startArg, endArg]);
+ const length = arrayLength(arrayOverlay(node));
+ const start = startArg === void 0 ? 0 : clampIndex(toIntegerOrInfinity(startArg), length);
+ const end = endArg === void 0 ? length : clampIndex(toIntegerOrInfinity(endArg), length);
+ if (end <= start)
+ return node.proxy;
+ const items = Array.from({ length: end - start }, () => clonePlacement(supplied));
+ replacePieceRange(node, start, end - start, insertPiece(node, items));
+ return node.proxy;
+ },
+ copyWithin(targetArg, startArg, endArg) {
+ const node = mutatorNode(this);
+ if (node === void 0)
+ return Reflect.apply(Array.prototype.copyWithin, this, [targetArg, startArg, endArg]);
+ const length = arrayLength(arrayOverlay(node));
+ const target = clampIndex(toIntegerOrInfinity(targetArg), length);
+ const start = clampIndex(toIntegerOrInfinity(startArg), length);
+ const end = endArg === void 0 ? length : clampIndex(toIntegerOrInfinity(endArg), length);
+ const count = Math.min(Math.max(end - start, 0), length - target);
+ const values = Array.from({ length: count }, (_, offset) => clonePlacement(getArrayIndex(node, start + offset)));
+ replacePieceRange(node, target, count, insertPiece(node, values));
+ return node.proxy;
+ }
+};
+function sortTokenSource(token, sources2) {
+ return token < 0 ? sources2[-token - 1] : void 0;
+}
+function sortTokenIndex(token, indices) {
+ return token < 0 ? indices[-token - 1] : token;
+}
+function publicSortValue(node, token, sources2, indices) {
+ const overlay = arrayOverlay(node);
+ const source = sortTokenSource(token, sources2);
+ const sourceIndex = sortTokenIndex(token, indices);
+ const overrideIndex = source === void 0 ? overlay.baseOverrides?.get(sourceIndex) : overlay.insertOverrides?.get(source)?.get(sourceIndex);
+ const value = overrideIndex !== void 0 ? storedValue(node.context, overrideIndex) : source === void 0 ? nodeBase(node)[sourceIndex] : storedValue(node.context, source.refs[sourceIndex]);
+ if (!isContainer2(value))
+ return value;
+ return createNode(node.context, value, node, source === void 0 ? 1 : 2, sourceIndex, source, source !== void 0 || (overlay.baseOverrides?.has(sourceIndex) ?? false)).proxy;
+}
+function restoreSortOverride(node, token, sources2, indices, baseSnapshot, insertSnapshots) {
+ const overlay = arrayOverlay(node);
+ const source = sortTokenSource(token, sources2);
+ const sourceIndex = sortTokenIndex(token, indices);
+ if (source === void 0) {
+ const existingIndex2 = overlay.baseOverrides?.get(sourceIndex);
+ const snapshotValue2 = baseSnapshot.get(sourceIndex);
+ if (snapshotValue2 !== void 0) {
+ if (existingIndex2 === void 0)
+ baseOverridesForWrite(overlay).set(sourceIndex, storeValue(node.context, snapshotValue2));
+ else
+ overlay.baseOverrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex2, snapshotValue2));
+ } else {
+ if (existingIndex2 !== void 0)
+ releaseStoredValue(node.context, existingIndex2);
+ overlay.baseOverrides?.delete(sourceIndex);
+ }
+ return;
+ }
+ let overrides = overlay.insertOverrides?.get(source);
+ const existingIndex = overrides?.get(sourceIndex);
+ const snapshotValue = insertSnapshots.get(source)?.get(sourceIndex);
+ if (snapshotValue !== void 0) {
+ if (overrides === void 0) {
+ overrides = /* @__PURE__ */ new Map();
+ insertOverridesForWrite(overlay).set(source, overrides);
+ }
+ if (existingIndex === void 0)
+ overrides.set(sourceIndex, storeValue(node.context, snapshotValue));
+ else
+ overrides.set(sourceIndex, replaceStoredValue(node.context, existingIndex, snapshotValue));
+ } else {
+ if (existingIndex !== void 0)
+ releaseStoredValue(node.context, existingIndex);
+ overrides?.delete(sourceIndex);
+ if (overrides?.size === 0)
+ overlay.insertOverrides?.delete(source);
+ }
+}
+function sameSortTokenAt(overlay, logicalIndex, token, sources2, indices) {
+ const piece = locatePiece(overlay, logicalIndex);
+ const sourceIndex = piece.start + piece.step * overlay.locatedOffset;
+ const tokenSource = sortTokenSource(token, sources2);
+ return sourceIndex === sortTokenIndex(token, indices) && (piece.kind === "base" && tokenSource === void 0 || piece.kind === "insert" && piece.source === tokenSource);
+}
+function deduplicateArrayEntries(node) {
+ const overlay = arrayOverlay(node);
+ const seenBase = /* @__PURE__ */ new Set();
+ const seenInsert = /* @__PURE__ */ new Map();
+ const next = [];
+ let duplicated = false;
+ for (const piece of piecesOf(overlay)) {
+ for (let offset = 0; offset < piece.length; offset++) {
+ const sourceIndex = piece.start + piece.step * offset;
+ let seen;
+ if (piece.kind === "base") {
+ seen = seenBase.has(sourceIndex);
+ seenBase.add(sourceIndex);
+ } else {
+ let indices = seenInsert.get(piece.source);
+ if (indices === void 0) {
+ indices = /* @__PURE__ */ new Set();
+ seenInsert.set(piece.source, indices);
+ }
+ seen = indices.has(sourceIndex);
+ indices.add(sourceIndex);
+ }
+ if (seen) {
+ duplicated = true;
+ appendMergedPiece(next, insertPiece(node, [clonePlacementStored(entryValueAt(node, piece, sourceIndex), node.context)])[0]);
+ } else
+ appendMergedPiece(next, singletonPiece(piece, sourceIndex));
+ }
+ }
+ if (!duplicated)
+ return;
+ replaceAllPieces(overlay, next);
+ overlay.structural = true;
+ overlay.generation += 1;
+ overlay.plan = void 0;
+ markDirty(node);
+}
+function piecesFromSortOrder(order, sources2, indices) {
+ const pieces = [];
+ for (const token of order) {
+ const source = token < 0 ? sources2[-token - 1] : void 0;
+ const sourceIndex = token < 0 ? indices[-token - 1] : token;
+ const previous = pieces.at(-1);
+ const sameSource = previous !== void 0 && (source === void 0 && previous.kind === "base" || source !== void 0 && previous.kind === "insert" && previous.source === source);
+ if (previous !== void 0 && sameSource) {
+ if (previous.length === 1) {
+ const step = sourceIndex - previous.start;
+ if (step === 1 || step === -1) {
+ previous.step = step;
+ previous.length = 2;
+ continue;
+ }
+ } else if (previous.start + previous.step * previous.length === sourceIndex) {
+ previous.length += 1;
+ continue;
+ }
+ }
+ pieces.push(source === void 0 ? { kind: "base", start: sourceIndex, length: 1, step: 1 } : { kind: "insert", source, start: sourceIndex, length: 1, step: 1 });
+ }
+ return pieces;
+}
+function appendMergedPiece(pieces, piece) {
+ const previous = pieces.at(-1);
+ const sameSource = previous !== void 0 && previous.kind === piece.kind && (previous.kind === "base" || previous.source === piece.source);
+ if (previous !== void 0 && sameSource && previous.length === 1 && piece.length === 1) {
+ const step = piece.start - previous.start;
+ if (step === 1 || step === -1) {
+ previous.step = step;
+ previous.length = 2;
+ return;
+ }
+ }
+ if (previous !== void 0 && sameSource && previous.step === piece.step && previous.start + previous.step * previous.length === piece.start) {
+ previous.length += piece.length;
+ } else
+ pieces.push(piece);
+}
+function singletonPiece(piece, sourceIndex) {
+ return piece.kind === "base" ? { kind: "base", start: sourceIndex, length: 1, step: 1 } : { kind: "insert", source: piece.source, start: sourceIndex, length: 1, step: 1 };
+}
+function clonePlacement(value) {
+ const proxyNode = isContainer2(value) ? Reflect.get(value, NODE) : void 0;
+ return proxyNode === void 0 ? copyJson(value) : clonePlacementNode(proxyNode);
+}
+function cloneNode(node) {
+ assertReadable(node.context);
+ if (Array.isArray(nodeBase(node))) {
+ const overlay = arrayOverlay(node);
+ const result2 = [];
+ for (const piece of piecesOf(overlay)) {
+ for (let offset = 0; offset < piece.length; offset++) {
+ const sourceIndex = piece.start + piece.step * offset;
+ result2.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));
+ }
+ }
+ return result2;
+ }
+ const result = Object.create(Object.getPrototypeOf(nodeBase(node)));
+ for (const key of ownKeys(node))
+ defineData3(result, key, cloneStored(objectValue(node, key), node.context));
+ return result;
+}
+function cloneStored(value, context) {
+ if (!isContainer2(value))
+ return value;
+ const node = context.rawNodes.get(value);
+ return node === void 0 || !node.dirty && !node.subtreeDirty ? value : cloneNode(node);
+}
+function clonePlacementNode(node) {
+ assertReadable(node.context);
+ if (Array.isArray(nodeBase(node))) {
+ const overlay = arrayOverlay(node);
+ const result2 = [];
+ for (const piece of piecesOf(overlay)) {
+ for (let offset = 0; offset < piece.length; offset++) {
+ const sourceIndex = piece.start + piece.step * offset;
+ result2.push(clonePlacementStored(entryValueAt(node, piece, sourceIndex), node.context));
+ }
+ }
+ return result2;
+ }
+ const result = Object.create(Object.getPrototypeOf(nodeBase(node)));
+ for (const key of ownKeys(node))
+ defineData3(result, key, clonePlacementStored(objectValue(node, key), node.context));
+ return result;
+}
+function clonePlacementStored(value, context) {
+ if (!isContainer2(value))
+ return copyJson(value);
+ const node = context.rawNodes.get(value);
+ return node === void 0 ? copyJson(value) : clonePlacementNode(node);
+}
+function defineData3(target, key, value) {
+ DATA_DESCRIPTOR3.value = value;
+ Object.defineProperty(target, key, DATA_DESCRIPTOR3);
+ DATA_DESCRIPTOR3.value = void 0;
+}
+function emitOperations(context) {
+ const simple = emitSimpleObjectOperations(context);
+ if (simple !== void 0)
+ return simple;
+ const operations = [];
+ const forcedFolds = /* @__PURE__ */ new Map();
+ const emissionPaths = /* @__PURE__ */ new Map();
+ const denseIndices = /* @__PURE__ */ new Map();
+ for (const node of context.dirty) {
+ recordDenseArrayPosition(node, denseIndices);
+ if (Array.isArray(nodeBase(node))) {
+ const overlay = arrayOverlay(node);
+ if (!overlay.structural && (overlay.baseOverrides?.size ?? 0) > 0) {
+ let candidates = denseIndices.get(node);
+ if (candidates === void 0) {
+ candidates = { indices: [], bits: void 0, length: nodeBase(node).length };
+ denseIndices.set(node, candidates);
+ }
+ for (const index3 of overlay.baseOverrides.keys())
+ addDenseCandidate(candidates, index3);
+ }
+ }
+ }
+ const denseRegions = /* @__PURE__ */ new Map();
+ for (const [array, candidates] of denseIndices) {
+ const path5 = resolvePath(array);
+ if (path5 === void 0 || path5.some((segment) => typeof segment === "string" && RESERVED_SEGMENTS.has(segment))) {
+ continue;
+ }
+ const regions = buildDenseRegions(candidates);
+ if (regions.length > 0)
+ denseRegions.set(array, regions);
+ }
+ for (const node of context.dirty) {
+ const path5 = resolvePath(node);
+ if (path5 === void 0)
+ continue;
+ if (hasCoveringDenseRegion(node, path5, denseRegions))
+ continue;
+ emissionPaths.set(node, path5);
+ if (!Array.isArray(nodeBase(node)) && hasReservedMutation(node))
+ forcedFolds.set(node, path5);
+ const reservedAt = path5.findIndex((segment) => typeof segment === "string" && RESERVED_SEGMENTS.has(segment));
+ if (reservedAt >= 0) {
+ let ancestor = node;
+ for (let depth = path5.length; depth > reservedAt; depth--)
+ ancestor = nodeParent(ancestor);
+ forcedFolds.set(ancestor, path5.slice(0, reservedAt));
+ }
+ }
+ for (const [node, path5] of forcedFolds)
+ emissionPaths.set(node, path5);
+ for (const node of denseRegions.keys()) {
+ const path5 = resolvePath(node);
+ if (path5 !== void 0 && !hasCoveringDenseRegion(node, path5, denseRegions))
+ emissionPaths.set(node, path5);
+ }
+ let maxDepth = 0;
+ for (const path5 of emissionPaths.values())
+ maxDepth = Math.max(maxDepth, path5.length);
+ const buckets = Array.from({ length: maxDepth + 1 }, () => []);
+ for (const [node, path5] of emissionPaths)
+ buckets[path5.length].push(node);
+ const folded = /* @__PURE__ */ new Set();
+ for (const bucket of buckets) {
+ for (const node of bucket) {
+ const path5 = emissionPaths.get(node);
+ if (hasPlacementAncestor(node) || hasFoldedAncestor(node, folded))
+ continue;
+ if (forcedFolds.has(node)) {
+ emitSet(operations, path5, cloneNode(node));
+ folded.add(node);
+ continue;
+ }
+ if (Array.isArray(nodeBase(node)))
+ emitArrayOperations(node, path5, operations, denseRegions.get(node));
+ else
+ emitObjectOperations(node, path5, operations);
+ if (operations.length > MAX_DELTA_OPERATIONS) {
+ locatedDenseArray = void 0;
+ return [["r", cloneNode(context.root)]];
+ }
+ }
+ }
+ locatedDenseArray = void 0;
+ return operations;
+}
+function emitSimpleObjectOperations(context) {
+ const nodes = [];
+ for (const node of context.dirty) {
+ if (Array.isArray(nodeBase(node)) || hasReservedMutation(node) || hasPlacementAncestor(node))
+ return void 0;
+ for (let parent = nodeParent(node); parent !== void 0; parent = nodeParent(parent)) {
+ if (Array.isArray(nodeBase(parent)))
+ return void 0;
+ }
+ const path5 = resolvePath(node);
+ if (path5 === void 0)
+ continue;
+ for (const segment of path5) {
+ if (typeof segment === "string" && RESERVED_SEGMENTS.has(segment))
+ return void 0;
+ }
+ nodes.push(node);
+ if (nodes.length > MAX_SIMPLE_OBJECT_NODES)
+ return void 0;
+ }
+ for (let index3 = 1; index3 < nodes.length; index3++) {
+ const node = nodes[index3];
+ const depth = node.preparedPath.length;
+ let at = index3;
+ while (at > 0 && nodes[at - 1].preparedPath.length > depth) {
+ nodes[at] = nodes[at - 1];
+ at -= 1;
+ }
+ nodes[at] = node;
+ }
+ const operations = [];
+ let canMaterializeDirectly = true;
+ for (const node of nodes) {
+ if (emitObjectOperations(node, node.preparedPath, operations))
+ canMaterializeDirectly = false;
+ if (operations.length > MAX_DELTA_OPERATIONS)
+ return [["r", cloneNode(context.root)]];
+ }
+ context.simpleObjectMaterialization = canMaterializeDirectly;
+ return operations;
+}
+var locatedDenseArray;
+var locatedDenseIndex = 0;
+function locateDenseArrayPosition(node) {
+ let child = node;
+ for (let parent = nodeParent(child); parent !== void 0; parent = nodeParent(child)) {
+ if (Array.isArray(nodeBase(parent))) {
+ const overlay = arrayOverlay(parent);
+ if (child.parentKind !== 1 || overlay.structural)
+ return false;
+ const sourceIndex = child.parentKey;
+ const valueIndex = overlay.baseOverrides?.get(sourceIndex);
+ const current = valueIndex === void 0 ? nodeBase(parent)[sourceIndex] : storedValue(parent.context, valueIndex);
+ if (current !== nodeBase(child))
+ return false;
+ locatedDenseArray = parent;
+ locatedDenseIndex = sourceIndex;
+ return true;
+ }
+ child = parent;
+ }
+ return false;
+}
+function hasCoveringDenseRegion(node, path5, denseRegions) {
+ for (let parent = nodeParent(node); parent !== void 0; parent = nodeParent(parent)) {
+ const regions = denseRegions.get(parent);
+ if (regions === void 0)
+ continue;
+ const parentPath = resolvePath(parent);
+ if (parentPath === void 0 || path5.length <= parentPath.length)
+ continue;
+ let matches = true;
+ for (let index4 = 0; index4 < parentPath.length; index4++) {
+ if (path5[index4] !== parentPath[index4]) {
+ matches = false;
+ break;
+ }
+ }
+ if (!matches)
+ continue;
+ const index3 = path5[parentPath.length];
+ if (typeof index3 === "number" && regionContaining(regions, index3))
+ return true;
+ }
+ return false;
+}
+function addDenseCandidate(candidates, index3) {
+ if (candidates.bits !== void 0) {
+ candidates.bits[index3] = 1;
+ return;
+ }
+ candidates.indices.push(index3);
+ if (candidates.indices.length < 256)
+ return;
+ candidates.bits = new Uint8Array(candidates.length);
+ for (const existing of candidates.indices)
+ candidates.bits[existing] = 1;
+ candidates.indices.length = 0;
+}
+function recordDenseArrayPosition(node, groups) {
+ if (!locateDenseArrayPosition(node))
+ return;
+ let candidates = groups.get(locatedDenseArray);
+ if (candidates === void 0) {
+ candidates = { indices: [], bits: void 0, length: nodeBase(locatedDenseArray).length };
+ groups.set(locatedDenseArray, candidates);
+ }
+ addDenseCandidate(candidates, locatedDenseIndex);
+}
+function buildDenseRegions(candidates) {
+ if (candidates.bits === void 0)
+ return [];
+ const regions = [];
+ const bits = candidates.bits;
+ for (let at = 0; at < bits.length; ) {
+ while (at < bits.length && bits[at] === 0)
+ at += 1;
+ if (at === bits.length)
+ break;
+ const start = at;
+ let end = at;
+ let count = 0;
+ let gap = 0;
+ while (at < bits.length) {
+ if (bits[at] !== 0) {
+ count += 1;
+ end = at;
+ gap = 0;
+ } else if (++gap > 1)
+ break;
+ at += 1;
+ }
+ const length = end - start + 1;
+ if (count >= 256 && count * 2 >= length)
+ regions.push({ start, length });
+ }
+ return regions;
+}
+function regionContaining(regions, index3) {
+ for (const region of regions)
+ if (index3 >= region.start && index3 < region.start + region.length)
+ return true;
+ return false;
+}
+function hasReservedMutation(node) {
+ if (node.writeKey !== void 0 && RESERVED_SEGMENTS.has(node.writeKey))
+ return true;
+ if (node.deleteKey !== void 0 && RESERVED_SEGMENTS.has(node.deleteKey))
+ return true;
+ if (node.writes !== void 0) {
+ for (const key of node.writes.keys())
+ if (RESERVED_SEGMENTS.has(key))
+ return true;
+ }
+ if (node.deletes !== void 0) {
+ for (const key of node.deletes)
+ if (RESERVED_SEGMENTS.has(key))
+ return true;
+ }
+ return false;
+}
+function hasFoldedAncestor(node, folded) {
+ for (let parent = nodeParent(node); parent !== void 0; parent = nodeParent(parent))
+ if (folded.has(parent))
+ return true;
+ return false;
+}
+function hasPlacementAncestor(node) {
+ for (let current = node; current !== void 0; current = nodeParent(current)) {
+ if (nodeParent(current) !== void 0 && current.parentPlacement)
+ return true;
+ }
+ return false;
+}
+function emitObjectWrite(node, path5, operations, key, value) {
+ const nextPath = [...path5, key];
+ const before = node.readded?.has(key) || !Object.hasOwn(nodeBase(node), key) ? void 0 : nodeBase(node)[key];
+ const after = cloneStored(value, node.context);
+ const emitted = emitChangedValue(operations, nextPath, before, after);
+ return isContainer2(before) && isContainer2(after) && !emitted;
+}
+function emitObjectOperations(node, path5, operations) {
+ if (node.readded !== void 0) {
+ for (const key of node.readded) {
+ if (Object.hasOwn(nodeBase(node), key))
+ operations.push(["d", [...path5, key]]);
+ }
+ }
+ let normalizedContainerWrite = false;
+ if (node.writeKey !== void 0)
+ normalizedContainerWrite = emitObjectWrite(node, path5, operations, node.writeKey, objectValue(node, node.writeKey));
+ if (node.writes !== void 0) {
+ for (const [key, valueIndex] of node.writes) {
+ if (operations.length > MAX_DELTA_OPERATIONS)
+ return normalizedContainerWrite;
+ if (emitObjectWrite(node, path5, operations, key, storedValue(node.context, valueIndex)))
+ normalizedContainerWrite = true;
+ }
+ }
+ if (node.deleteKey !== void 0 && Object.hasOwn(nodeBase(node), node.deleteKey)) {
+ operations.push(["d", [...path5, node.deleteKey]]);
+ }
+ if (node.deletes !== void 0) {
+ for (const key of node.deletes) {
+ if (operations.length > MAX_DELTA_OPERATIONS)
+ return normalizedContainerWrite;
+ if (Object.hasOwn(nodeBase(node), key))
+ operations.push(["d", [...path5, key]]);
+ }
+ }
+ return normalizedContainerWrite;
+}
+function buildArrayPlan(node) {
+ const overlay = arrayOverlay(node);
+ if (overlay.plan !== void 0)
+ return overlay.plan;
+ const base = nodeBase(node);
+ const pieces = piecesOf(overlay);
+ const retained = new Uint8Array(base.length);
+ const targetBase = [];
+ for (const piece of pieces) {
+ if (piece.kind !== "base")
+ continue;
+ for (let offset = 0; offset < piece.length; offset++) {
+ const index3 = piece.start + piece.step * offset;
+ retained[index3] = 1;
+ targetBase.push(index3);
+ }
+ }
+ const removeRuns = [];
+ for (let end = base.length; end > 0; ) {
+ if (retained[end - 1] !== 0) {
+ end -= 1;
+ continue;
+ }
+ let start = end - 1;
+ while (start > 0 && retained[start - 1] === 0)
+ start -= 1;
+ removeRuns.push(start, end - start);
+ end = start;
+ }
+ const retainedBase = [];
+ for (let index3 = 0; index3 < retained.length; index3++)
+ if (retained[index3] !== 0)
+ retainedBase.push(index3);
+ let permutation;
+ if (targetBase.some((value, index3) => value !== retainedBase[index3])) {
+ const positions = new Map(retainedBase.map((value, index3) => [value, index3]));
+ permutation = targetBase.map((value) => positions.get(value));
+ }
+ const insertRuns = [];
+ let logicalIndex = 0;
+ for (let pieceIndex = 0; pieceIndex < pieces.length; ) {
+ const piece = pieces[pieceIndex];
+ if (piece.kind === "base") {
+ logicalIndex += piece.length;
+ pieceIndex += 1;
+ continue;
+ }
+ const startPiece = pieceIndex;
+ while (pieceIndex < pieces.length && pieces[pieceIndex].kind === "insert") {
+ logicalIndex += pieces[pieceIndex].length;
+ pieceIndex += 1;
+ }
+ insertRuns.push(logicalIndex - rangeLength(pieces, startPiece, pieceIndex), startPiece, pieceIndex);
+ }
+ overlay.plan = { removeRuns, permutation, insertRuns };
+ return overlay.plan;
+}
+function rangeLength(pieces, start, end) {
+ let length = 0;
+ for (let index3 = start; index3 < end; index3++)
+ length += pieces[index3].length;
+ return length;
+}
+function emitArrayOperations(node, path5, operations, denseRegions) {
+ const overlay = arrayOverlay(node);
+ const base = nodeBase(node);
+ if (denseRegions !== void 0) {
+ for (const region of denseRegions) {
+ if (operations.length > MAX_DELTA_OPERATIONS)
+ return;
+ operations.push(["p", path5, region.start, region.length, cloneArrayRegion(node, region)]);
+ }
+ }
+ if (overlay.structural) {
+ const plan = buildArrayPlan(node);
+ for (let index3 = 0; index3 < plan.removeRuns.length; index3 += 2) {
+ if (operations.length > MAX_DELTA_OPERATIONS)
+ return;
+ operations.push(["p", path5, plan.removeRuns[index3], plan.removeRuns[index3 + 1], []]);
+ }
+ if (plan.permutation !== void 0)
+ operations.push(["m", path5, plan.permutation]);
+ const pieces = piecesOf(overlay);
+ for (let run2 = 0; run2 < plan.insertRuns.length; run2 += 3) {
+ if (operations.length > MAX_DELTA_OPERATIONS)
+ return;
+ const logicalIndex = plan.insertRuns[run2];
+ const items = [];
+ for (let pieceIndex = plan.insertRuns[run2 + 1]; pieceIndex < plan.insertRuns[run2 + 2]; pieceIndex++) {
+ const piece = pieces[pieceIndex];
+ for (let offset = 0; offset < piece.length; offset++) {
+ const sourceIndex = piece.start + piece.step * offset;
+ items.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));
+ }
+ }
+ operations.push(["p", path5, logicalIndex, 0, items]);
+ }
+ }
+ for (const [baseIndex, valueIndex] of overlay.baseOverrides ?? []) {
+ if (operations.length > MAX_DELTA_OPERATIONS)
+ return;
+ const index3 = findEntryIndex(overlay, 1, baseIndex, void 0);
+ if (index3 === void 0 || denseRegions !== void 0 && regionContaining(denseRegions, index3))
+ continue;
+ emitChangedValue(operations, [...path5, index3], base[baseIndex], cloneStored(storedValue(node.context, valueIndex), node.context));
+ }
+}
+function cloneArrayRegion(node, region) {
+ const overlay = arrayOverlay(node);
+ const result = [];
+ for (let index3 = region.start; index3 < region.start + region.length; index3++) {
+ const piece = locatePiece(overlay, index3);
+ const sourceIndex = piece.start + piece.step * overlay.locatedOffset;
+ result.push(cloneStored(entryValueAt(node, piece, sourceIndex), node.context));
+ }
+ return result;
+}
+function emitChangedValue(operations, path5, before, after) {
+ if (!isContainer2(after) && before === after)
+ return false;
+ if (isContainer2(before) && isContainer2(after) && equalTrustedJson(before, after))
+ return false;
+ if (typeof before === "string" && typeof after === "string") {
+ if (after.length > before.length && after.slice(0, before.length) === before) {
+ operations.push(["a", path5, after.slice(before.length)]);
+ return true;
+ }
+ const shared = overlap(before, after, 65536);
+ if (shared > 0) {
+ operations.push(["t", path5, before.length - shared]);
+ if (after.length > shared)
+ operations.push(["a", path5, after.slice(shared)]);
+ return true;
+ }
+ }
+ operations.push(["s", path5, after]);
+ return true;
+}
+function emitSet(operations, path5, value) {
+ if (path5.length === 0)
+ operations.push(["r", value]);
+ else
+ operations.push(["s", path5, value]);
+}
+function resolvePath(node) {
+ if (node.preparedPath !== void 0)
+ return node.preparedPath;
+ const parent = nodeParent(node);
+ if (parent === void 0) {
+ node.preparedPath = [];
+ return node.preparedPath;
+ }
+ const parentPath = resolvePath(parent);
+ if (parentPath === void 0)
+ return void 0;
+ if (node.parentKind === 0) {
+ const key = node.parentKey;
+ if (!objectHas(parent, key) || objectValue(parent, key) !== nodeBase(node))
+ return void 0;
+ node.preparedPath = [...parentPath, key];
+ return node.preparedPath;
+ }
+ const overlay = arrayOverlay(parent);
+ const index3 = findEntryIndex(overlay, node.parentKind, node.parentKey, node.parentSource);
+ if (index3 === void 0)
+ return void 0;
+ const piece = locatePiece(overlay, index3);
+ if (entryValueAt(parent, piece, node.parentKey) !== nodeBase(node))
+ return void 0;
+ node.preparedPath = [...parentPath, index3];
+ return node.preparedPath;
+}
+function ensurePieceLocations(overlay) {
+ if (overlay.baseLocations !== void 0)
+ return;
+ overlay.baseLocations = [];
+ overlay.insertLocations = /* @__PURE__ */ new Map();
+ let logicalStart = 0;
+ for (const piece of piecesOf(overlay)) {
+ const last = piece.start + piece.step * (piece.length - 1);
+ const location = {
+ piece,
+ logicalStart,
+ minimum: Math.min(piece.start, last),
+ maximum: Math.max(piece.start, last)
+ };
+ if (piece.kind === "base")
+ overlay.baseLocations.push(location);
+ else {
+ let locations = overlay.insertLocations.get(piece.source);
+ if (locations === void 0) {
+ locations = [];
+ overlay.insertLocations.set(piece.source, locations);
+ }
+ locations.push(location);
+ }
+ logicalStart += piece.length;
+ }
+ const byMinimum = (left, right) => left.minimum - right.minimum;
+ overlay.baseLocations.sort(byMinimum);
+ for (const locations of overlay.insertLocations.values())
+ locations.sort(byMinimum);
+}
+function findEntryIndex(overlay, kind, sourceIndex, source) {
+ if (kind === 1 && !overlay.structural)
+ return sourceIndex;
+ ensurePieceLocations(overlay);
+ const locations = kind === 1 ? overlay.baseLocations : overlay.insertLocations.get(source);
+ if (locations === void 0)
+ return void 0;
+ let low = 0;
+ let high = locations.length;
+ while (low < high) {
+ const middle = low + high >>> 1;
+ if (locations[middle].minimum <= sourceIndex)
+ low = middle + 1;
+ else
+ high = middle;
+ }
+ const location = locations[low - 1];
+ if (location === void 0 || sourceIndex > location.maximum)
+ return void 0;
+ const offset = (sourceIndex - location.piece.start) / location.piece.step;
+ return offset >= 0 && offset < location.piece.length ? location.logicalStart + offset : void 0;
+}
+function ensureOperations(context) {
+ if (context.ops !== void 0)
+ return context.ops;
+ assertReadable(context);
+ if (context.replacement) {
+ const base = context.tracker.deref()?.replacementBase(context);
+ context.replacementNoop = base !== void 0 && equalTrustedJson(base, nodeBase(context.root));
+ context.ops = context.replacementNoop ? [] : [["r", nodeBase(context.root)]];
+ } else
+ context.ops = emitOperations(context);
+ return context.ops;
+}
+function equalTrustedJson(left, right) {
+ if (left === right)
+ return true;
+ if (!isContainer2(left) || !isContainer2(right) || Array.isArray(left) !== Array.isArray(right))
+ return false;
+ if (Array.isArray(left)) {
+ const other2 = right;
+ if (left.length !== other2.length)
+ return false;
+ for (let index3 = 0; index3 < left.length; index3++)
+ if (!equalTrustedJson(left[index3], other2[index3]))
+ return false;
+ return true;
+ }
+ const other = right;
+ const keys = Object.keys(left);
+ if (keys.length !== Object.keys(other).length)
+ return false;
+ for (const key of keys)
+ if (!Object.hasOwn(other, key) || !equalTrustedJson(left[key], other[key]))
+ return false;
+ return true;
+}
+function abortContext(context) {
+ if (context.status.value === "aborted" || context.status.value === "consumed" || context.status.value === "stale")
+ return;
+ context.status.value = "aborted";
+ clearContext(context);
+}
+function releaseOverlayReferences(context) {
+ context.tracker.deref()?.releaseContext(context);
+ if (locatedDenseArray?.context === context)
+ locatedDenseArray = void 0;
+ context.overlayReleased = true;
+ context.dirty.length = 0;
+ context.nodes.length = 0;
+ context.rawNodes = void 0;
+ context.ops = void 0;
+ context.root = void 0;
+ context.bases = void 0;
+ context.stored = void 0;
+ context.baseValue = void 0;
+}
+function clearContext(context) {
+ context.tracker.deref()?.releaseContext(context);
+ if (locatedDenseArray?.context === context)
+ locatedDenseArray = void 0;
+ for (const node of context.nodes) {
+ if (Array.isArray(node.target))
+ node.target.length = 0;
+ Reflect.deleteProperty(node.target, NODE);
+ node.writes?.clear();
+ node.deletes?.clear();
+ node.readded?.clear();
+ if (node.array?.pieces !== void 0)
+ node.array.pieces.length = 0;
+ if (node.array !== void 0) {
+ node.array.root = void 0;
+ node.array.baseLocations = void 0;
+ node.array.insertLocations = void 0;
+ }
+ node.array?.baseOverrides?.clear();
+ node.array?.insertOverrides?.clear();
+ node.parentSource = void 0;
+ node.target = RELEASED;
+ node.proxy = RELEASED;
+ node.writeKey = void 0;
+ node.writeValue = void 0;
+ node.writes = void 0;
+ node.deleteKey = void 0;
+ node.deletes = void 0;
+ node.readded = void 0;
+ node.array = void 0;
+ node.subtreeDirty = void 0;
+ node.preparedPath = void 0;
+ }
+ context.dirty.length = 0;
+ context.nodes.length = 0;
+ context.rawNodes = void 0;
+ context.ops = void 0;
+ context.root = void 0;
+ context.bases = void 0;
+ context.stored = void 0;
+ context.baseValue = void 0;
+ context.overlayReleased = true;
+}
+function isContainer2(value) {
+ return value !== null && typeof value === "object";
+}
+
+// node_modules/@earendil-works/chord/dist/delta/index.js
+var isObj2 = (value) => value !== null && typeof value === "object";
+function overlap(a, b, scan, probe = 64, maxCandidates = 8) {
+ if (a.length === 0 || b.length === 0 || scan === 0)
+ return 0;
+ const tail = a.length > scan ? a.slice(a.length - scan) : a;
+ for (const h of [Math.min(probe, b.length), 1]) {
+ const head = b.slice(0, h);
+ let tried = 0;
+ for (let k = tail.indexOf(head); k !== -1; k = tail.indexOf(head, k + 1)) {
+ if (++tried > maxCandidates)
+ break;
+ const n = tail.length - k;
+ if (n <= b.length && tail.slice(k) === b.slice(0, n))
+ return n;
+ }
+ if (h === 1)
+ break;
+ }
+ return 0;
+}
+var RESERVED_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
+var UnsafePathError = class extends Error {
+ // Not a parameter property: Node's --experimental-strip-types rejects those,
+ // and these files are meant to run under it directly.
+ segment;
+ constructor(segment) {
+ super(`unsafe path segment: ${String(segment)}`);
+ this.segment = segment;
+ this.name = "UnsafePathError";
+ }
+};
+function assertValidOp(op) {
+ if (!Array.isArray(op) || op.length === 0)
+ throw new TypeError("op is not a tuple");
+ switch (op[0]) {
+ case "r":
+ if (op.length !== 2)
+ throw new TypeError("r arity");
+ return;
+ case "s":
+ if (op.length !== 3)
+ throw new TypeError("s arity");
+ assertPathArg(op[1], true);
+ return;
+ case "d":
+ if (op.length !== 2)
+ throw new TypeError("d arity");
+ assertPathArg(op[1], true);
+ return;
+ case "a":
+ if (op.length !== 3 || typeof op[2] !== "string")
+ throw new TypeError("a shape");
+ assertPathArg(op[1], true);
+ return;
+ case "t":
+ if (op.length !== 3 || !Number.isInteger(op[2]) || op[2] < 0)
+ throw new TypeError("t shape");
+ assertPathArg(op[1], true);
+ return;
+ case "p": {
+ if (op.length !== 5)
+ throw new TypeError("p arity");
+ assertPathArg(op[1]);
+ if (!Number.isInteger(op[2]) || op[2] < 0)
+ throw new TypeError("p index");
+ if (!Number.isInteger(op[3]) || op[3] < 0)
+ throw new TypeError("p remove");
+ if (!Array.isArray(op[4]))
+ throw new TypeError("p items");
+ return;
+ }
+ case "m":
+ if (op.length !== 3)
+ throw new TypeError("m arity");
+ assertPathArg(op[1]);
+ assertPermutation(op[2]);
+ return;
+ // Silently skipping an unknown verb is how a newer producer's op vanishes.
+ default:
+ throw new TypeError(`unknown op verb: ${String(op[0])}`);
+ }
+}
+function assertPathArg(p, nonEmpty = false) {
+ if (!Array.isArray(p))
+ throw new TypeError("path is not an array");
+ if (nonEmpty && p.length === 0)
+ throw new TypeError("path is empty");
+ assertSafePath(p);
+}
+function assertPermutation(value) {
+ if (!Array.isArray(value))
+ throw new TypeError("m permutation is not an array");
+ const seen = new Uint8Array(value.length);
+ for (const index3 of value) {
+ if (!Number.isInteger(index3) || index3 < 0 || index3 >= value.length || seen[index3] !== 0) {
+ throw new TypeError("m permutation is not a bijection");
+ }
+ seen[index3] = 1;
+ }
+}
+function assertSafePath(path5) {
+ for (const seg of path5) {
+ if (typeof seg === "string") {
+ if (RESERVED_SEGMENTS.has(seg))
+ throw new UnsafePathError(seg);
+ } else if (!Number.isInteger(seg) || seg < 0) {
+ throw new UnsafePathError(seg);
+ }
+ }
+}
+function assertIndexInRange(parent, index3) {
+ if (index3 > parent.length)
+ throw new UnsafePathError(index3);
+}
+var PathError = class extends Error {
+ path;
+ constructor(path5) {
+ super(`unresolvable path: ${JSON.stringify(path5)}`);
+ this.path = path5;
+ this.name = "PathError";
+ }
+};
+function applyOps(target, ops) {
+ let root = target;
+ for (const op of ops) {
+ assertValidOp(op);
+ if (op[0] === "r") {
+ root = op[1];
+ continue;
+ }
+ const path5 = op[1];
+ assertSafePath(path5);
+ if (op[0] === "p") {
+ const target_ = path5.length === 0 ? root : resolve(root, path5);
+ if (!Array.isArray(target_))
+ throw new PathError(path5);
+ target_.splice(op[2], op[3]);
+ const chunkSize = 1e4;
+ for (let offset = 0; offset < op[4].length; offset += chunkSize) {
+ target_.splice(op[2] + offset, 0, ...op[4].slice(offset, offset + chunkSize));
+ }
+ continue;
+ }
+ if (op[0] === "m") {
+ const target_ = path5.length === 0 ? root : resolve(root, path5);
+ if (!Array.isArray(target_) || target_.length !== op[2].length)
+ throw new PathError(path5);
+ const previous = target_.slice();
+ for (let index3 = 0; index3 < op[2].length; index3++)
+ target_[index3] = previous[op[2][index3]];
+ continue;
+ }
+ const parent = resolve(root, path5.slice(0, -1));
+ const key = path5[path5.length - 1];
+ if (Array.isArray(parent)) {
+ if (typeof key !== "number")
+ throw new UnsafePathError(key);
+ assertIndexInRange(parent, key);
+ }
+ const write = (value) => {
+ Object.defineProperty(parent, key, { value, writable: true, enumerable: true, configurable: true });
+ };
+ const read2 = () => Object.hasOwn(parent, key) ? parent[key] : void 0;
+ switch (op[0]) {
+ case "s":
+ write(op[2]);
+ break;
+ case "d":
+ if (Array.isArray(parent)) {
+ if (typeof key !== "number" || key >= parent.length)
+ throw new PathError(path5);
+ parent.splice(key, 1);
+ } else
+ delete parent[key];
+ break;
+ case "a": {
+ const current = read2();
+ if (typeof current !== "string")
+ throw new PathError(path5);
+ write(`${current}${op[2]}`);
+ break;
+ }
+ case "t": {
+ const current = read2();
+ if (typeof current !== "string")
+ throw new PathError(path5);
+ write(current.slice(op[2]));
+ break;
+ }
+ }
+ }
+ return root;
+}
+function applyImmutable(target, ops) {
+ return applyImmutableBatches(target, [ops]);
+}
+function applyImmutableBatches(target, batches) {
+ let root = target;
+ const owned = /* @__PURE__ */ new WeakSet();
+ for (const ops of batches) {
+ for (const op of ops) {
+ assertValidOp(op);
+ if (op[0] === "r") {
+ root = op[1];
+ continue;
+ }
+ root = copyContainers(root, op[0] === "p" || op[0] === "m" ? op[1] : op[1].slice(0, -1), owned);
+ root = applyOps(root, [op]);
+ }
+ }
+ return root;
+}
+function copyContainers(root, path5, owned) {
+ const copy2 = (value) => {
+ if (Array.isArray(value))
+ return value.slice();
+ if (!isObj2(value))
+ throw new PathError(path5);
+ const result = Object.create(Object.getPrototypeOf(value) === null ? null : Object.prototype);
+ for (const key of Object.keys(value)) {
+ Object.defineProperty(result, key, {
+ value: value[key],
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ }
+ return result;
+ };
+ if (!isObj2(root))
+ throw new PathError(path5);
+ let copiedRoot;
+ if (owned.has(root))
+ copiedRoot = root;
+ else {
+ copiedRoot = copy2(root);
+ owned.add(copiedRoot);
+ }
+ let destination = copiedRoot;
+ for (const segment of path5) {
+ if (!Object.hasOwn(destination, segment))
+ throw new PathError(path5);
+ if (Array.isArray(destination) && typeof segment !== "number")
+ throw new UnsafePathError(segment);
+ const child = destination[segment];
+ if (!isObj2(child))
+ throw new PathError(path5);
+ if (owned.has(child)) {
+ destination = child;
+ continue;
+ }
+ const copiedChild = copy2(child);
+ Object.defineProperty(destination, segment, {
+ value: copiedChild,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ owned.add(copiedChild);
+ destination = copiedChild;
+ }
+ return copiedRoot;
+}
+function resolveValue(root, path5) {
+ let node = root;
+ for (const seg of path5) {
+ if (!isObj2(node))
+ throw new PathError(path5);
+ if (Array.isArray(node) && typeof seg !== "number")
+ throw new UnsafePathError(seg);
+ if (!Object.hasOwn(node, seg))
+ throw new PathError(path5);
+ node = node[seg];
+ }
+ return node;
+}
+function resolve(root, path5) {
+ const node = resolveValue(root, path5);
+ if (!isObj2(node))
+ throw new PathError(path5);
+ return node;
+}
+
+// node_modules/@earendil-works/chord/dist/services/state-internals.js
+var sources = /* @__PURE__ */ new WeakMap();
+function registerReplicatedStateInternals(value, internals) {
+ sources.set(value, internals);
+}
+
+// node_modules/@earendil-works/chord/dist/services/state.js
+var StateSubscriber = class {
+ #listener;
+ #reportError;
+ #pending = [];
+ #running = false;
+ #started = false;
+ #closed = false;
+ constructor(listener, reportError) {
+ this.#listener = listener;
+ this.#reportError = reportError;
+ }
+ push(frame) {
+ if (this.#closed)
+ return;
+ if (this.#pending.length === 100) {
+ const hydration = this.#started ? void 0 : this.#pending[0];
+ this.#pending.length = 0;
+ if (hydration !== void 0)
+ this.#pending.push(hydration);
+ }
+ this.#pending.push(frame);
+ }
+ drain() {
+ if (this.#running || this.#closed)
+ return;
+ this.#running = true;
+ for (let frame = this.#pending.shift(); frame !== void 0; frame = this.#pending.shift()) {
+ this.#started = true;
+ try {
+ const result = this.#listener(frame.value, frame.context, frame.delivery);
+ if (isPromiseLike(result)) {
+ void Promise.resolve(result).then(() => this.#resume(), (error) => {
+ this.#report(error);
+ this.#resume();
+ });
+ return;
+ }
+ } catch (error) {
+ this.#report(error);
+ }
+ }
+ this.#running = false;
+ }
+ clear() {
+ this.#pending.length = 0;
+ }
+ close() {
+ this.#closed = true;
+ this.clear();
+ }
+ #resume() {
+ this.#running = false;
+ this.drain();
+ }
+ #report(error) {
+ try {
+ this.#reportError(toError(error));
+ } catch (reportError) {
+ reportErrorAsync(toError(reportError));
+ }
+ }
+};
+var ReplicatedStatePublisher = class {
+ #listeners = /* @__PURE__ */ new Map();
+ #reportError;
+ #sourceListeners = /* @__PURE__ */ new Set();
+ #publications = [];
+ #value;
+ #sequence = 0;
+ #delivering = false;
+ constructor(initial, reportError = reportErrorAsync) {
+ this.#value = initial;
+ this.#reportError = reportError;
+ }
+ get value() {
+ return this.#value;
+ }
+ snapshot() {
+ return { value: this.#value, sequence: this.#sequence };
+ }
+ subscribe(listener) {
+ const { value, sequence: sequence2 } = this.snapshot();
+ const subscriber = new StateSubscriber(listener, this.#reportError);
+ this.#listeners.set(subscriber, sequence2);
+ subscriber.push({ value, context: serviceDeliveryContext(), delivery: { kind: "hydrate", sequence: sequence2 } });
+ subscriber.drain();
+ return () => {
+ subscriber.close();
+ this.#listeners.delete(subscriber);
+ };
+ }
+ subscribeSource(listener) {
+ this.#sourceListeners.add(listener);
+ return () => this.#sourceListeners.delete(listener);
+ }
+ /** Publish an already-prepared immutable revision and return isolated listener failures. */
+ publish(value, ops, context) {
+ this.#value = value;
+ this.#sequence += 1;
+ this.#publications.push({ value, ops, sequence: this.#sequence, context });
+ if (this.#delivering)
+ return [];
+ this.#delivering = true;
+ const errors = [];
+ try {
+ for (let publication = this.#publications.shift(); publication !== void 0; publication = this.#publications.shift()) {
+ for (const listener of [...this.#sourceListeners]) {
+ try {
+ listener(publication.ops, publication.sequence, publication.context);
+ } catch (error) {
+ errors.push(error);
+ }
+ }
+ const delivery = { kind: "update", sequence: publication.sequence };
+ for (const [subscriber, hydratedSequence] of [...this.#listeners]) {
+ if (publication.sequence <= hydratedSequence)
+ continue;
+ subscriber.push({ value: publication.value, context: publication.context, delivery });
+ subscriber.drain();
+ }
+ }
+ } finally {
+ this.#delivering = false;
+ }
+ return errors;
+ }
+};
+var MutableReplicatedStateImpl = class {
+ #tracker;
+ #publisher;
+ #changing = false;
+ constructor(initial) {
+ this.#tracker = track(initial);
+ this.#publisher = new ReplicatedStatePublisher(this.#tracker.value);
+ registerReplicatedStateInternals(this, {
+ snapshot: () => this.#publisher.snapshot(),
+ subscribe: (listener) => this.#publisher.subscribeSource(listener)
+ });
+ }
+ get value() {
+ return this.#tracker.value;
+ }
+ change(context, mutate) {
+ if (this.#changing)
+ throw new Error("Replicated state cannot be changed reentrantly from a change callback");
+ this.#changing = true;
+ let prepared;
+ try {
+ const change = this.#tracker.beginChange();
+ try {
+ const outcome = mutate(change.state);
+ if (isPromiseLike(outcome)) {
+ void Promise.resolve(outcome).catch(() => void 0);
+ throw new TypeError("Replicated state change callbacks must be synchronous");
+ }
+ prepared = change.prepare();
+ } catch (error) {
+ change.abort();
+ throw error;
+ }
+ } finally {
+ this.#changing = false;
+ }
+ this.#tracker.adopt(prepared);
+ if (prepared.ops.length === 0)
+ return;
+ throwCollectedErrors(this.#publisher.publish(prepared.value, prepared.ops, context), "Replicated state listeners failed");
+ }
+ replace(context, value) {
+ if (this.#changing)
+ throw new Error("Replicated state cannot be replaced from a change callback");
+ const prepared = this.#tracker.prepareReplace(value);
+ this.#tracker.adopt(prepared);
+ if (prepared.ops.length === 0)
+ return;
+ throwCollectedErrors(this.#publisher.publish(prepared.value, prepared.ops, context), "Replicated state listeners failed");
+ }
+ subscribe(listener) {
+ return this.#publisher.subscribe(listener);
+ }
+};
+var AttachedReplicatedStateImpl = class {
+ #publisher;
+ #attachment;
+ #reportError;
+ #cursor;
+ #disposed = false;
+ constructor(attachment, options) {
+ const { snapshot } = attachment;
+ assertCursor(snapshot.cursor, "snapshot");
+ this.#attachment = attachment;
+ this.#cursor = snapshot.cursor;
+ this.#reportError = options.onError ?? reportErrorAsync;
+ this.#publisher = new ReplicatedStatePublisher(snapshot.value, (error) => this.#report(error));
+ registerReplicatedStateInternals(this, {
+ snapshot: () => this.#publisher.snapshot(),
+ subscribe: (listener) => this.#publisher.subscribeSource(listener)
+ });
+ }
+ get value() {
+ return this.#publisher.value;
+ }
+ subscribe(listener) {
+ return this.#publisher.subscribe(listener);
+ }
+ activate() {
+ this.#attachment.activate((frame) => this.#receive(frame));
+ }
+ dispose() {
+ if (this.#disposed)
+ return;
+ this.#disposed = true;
+ this.#attachment.dispose();
+ }
+ #receive(frame) {
+ if (this.#disposed)
+ return;
+ try {
+ assertCursor(frame.cursor, "frame");
+ const expected = this.#cursor + 1;
+ if (frame.cursor !== expected) {
+ throw new Error(`Replicated state source cursor has a gap: expected ${expected}, received ${frame.cursor}`);
+ }
+ this.#cursor = frame.cursor;
+ const errors = this.#publisher.publish(frame.value, frame.ops, frame.context);
+ if (errors.length === 1)
+ this.#report(errors[0]);
+ else if (errors.length > 1)
+ this.#report(new AggregateError(errors, "Replicated state listeners failed"));
+ } catch (error) {
+ this.#fail(toError(error));
+ }
+ }
+ #fail(error) {
+ if (this.#disposed)
+ return;
+ this.#disposed = true;
+ try {
+ this.#attachment.dispose();
+ } catch (disposeError) {
+ this.#report(new AggregateError([error, disposeError], "Replicated state source contract failed"));
+ return;
+ }
+ this.#report(error);
+ }
+ #report(error) {
+ try {
+ this.#reportError(toError(error));
+ } catch (reportError) {
+ reportErrorAsync(toError(reportError));
+ }
+ }
+};
+function attachReplicatedStateSource(source, options = {}) {
+ const attachment = source.attach();
+ try {
+ const state3 = new AttachedReplicatedStateImpl(attachment, options);
+ state3.activate();
+ return state3;
+ } catch (error) {
+ try {
+ attachment.dispose();
+ } catch (disposeError) {
+ throw new AggregateError([error, disposeError], "Failed to attach replicated state source");
+ }
+ throw error;
+ }
+}
+function serviceDeliveryContext() {
+ return BACKGROUND_CONTEXT;
+}
+function assertCursor(cursor, kind) {
+ if (!Number.isSafeInteger(cursor))
+ throw new TypeError(`Replicated state source ${kind} cursor must be a safe integer`);
+}
+function isPromiseLike(value) {
+ return (typeof value === "object" && value !== null || typeof value === "function") && typeof value.then === "function";
+}
+function throwCollectedErrors(errors, message) {
+ if (errors.length === 1)
+ throw errors[0];
+ if (errors.length > 1)
+ throw new AggregateError(errors, message);
+}
+function reportErrorAsync(error) {
+ queueMicrotask(() => {
+ throw error;
+ });
+}
+function toError(error) {
+ return error instanceof Error ? error : new Error(String(error));
+}
+
+// node_modules/@earendil-works/chord/dist/api.js
+function replicatedState(initialOrSource, options) {
+ if (isReplicatedStateSource(initialOrSource))
+ return attachReplicatedStateSource(initialOrSource, options);
+ return new MutableReplicatedStateImpl(initialOrSource);
+}
+function isReplicatedStateSource(value) {
+ return typeof value.attach === "function";
+}
+
+// node_modules/@earendil-works/pi-durable/dist/ids.js
+function idFromNumber(value) {
+ return value;
+}
+function seqFromNumber(value) {
+ return value;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/documents.js
+function defineDoc(definition) {
+ validateDefinition(definition);
+ return { definition };
+}
+function validateDefinition(definition) {
+ if (!Number.isSafeInteger(definition.version) || definition.version < 1) {
+ throw new TypeError(`Document ${definition.kind} version must be a positive integer`);
+ }
+}
+function resolveAddress(definition, args) {
+ let index3 = 0;
+ let scope;
+ switch (definition.scope) {
+ case "session":
+ scope = { kind: "session" };
+ break;
+ case "conversation":
+ scope = { kind: "conversation", conversationId: ownerId(args[index3++], definition) };
+ break;
+ case "task":
+ scope = { kind: "task", taskId: ownerId(args[index3++], definition) };
+ break;
+ }
+ const key = definition.family === true ? args[index3++] : void 0;
+ const address = key === void 0 ? { kind: definition.kind, scope } : { kind: definition.kind, scope, key };
+ return { address, id: addressId(address), nextArgument: index3 };
+}
+function ownerId(value, definition) {
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
+ throw new TypeError(`Document ${definition.kind} requires a ${definition.scope} ID`);
+ }
+ return idFromNumber(value);
+}
+function addressId(address) {
+ const owner = address.scope.kind === "session" ? null : address.scope.kind === "conversation" ? address.scope.conversationId : address.scope.taskId;
+ return JSON.stringify([address.kind, address.scope.kind, owner, address.key ?? null]);
+}
+function documentCreate(definition, address, id) {
+ const key = address.key === void 0 ? {} : { key: address.key };
+ switch (address.scope.kind) {
+ case "session":
+ return { id, kind: address.kind, ...key, scope: address.scope };
+ case "task":
+ return { id, kind: address.kind, ...key, scope: address.scope };
+ case "conversation":
+ return {
+ id,
+ kind: address.kind,
+ ...key,
+ scope: address.scope,
+ history: definition.history,
+ fork: definition.fork
+ };
+ }
+}
+function checkRecordScope(definition, record) {
+ if (record.scope.kind !== definition.scope || record.scope.kind === "conversation" && (record.history !== definition.history || record.fork !== definition.fork)) {
+ throw new TypeError(`Document ${record.id} (${record.kind}) does not match the supplied definition semantics`);
+ }
+}
+function checkRecordVersion(definition, record, version) {
+ if (version > definition.version) {
+ throw new Error(`Document ${record.id} (${record.kind}) has newer version ${version} than ${definition.version}`);
+ }
+ if (version < definition.version && definition.migrate === void 0) {
+ throw new Error(`Document ${record.id} (${record.kind}) requires migration from version ${version}`);
+ }
+}
+function materializeDocument(definition, stored) {
+ return materializeDocumentValue(definition, stored.record, stored.version, stored.value);
+}
+function materializeDocumentValue(definition, record, version, value) {
+ checkRecordScope(definition, record);
+ checkRecordVersion(definition, record, version);
+ if (version === definition.version)
+ return value;
+ return copyJson(definition.migrate(value, version));
+}
+
+// node_modules/@earendil-works/pi-durable/dist/entries.js
+function defineEntry(kind) {
+ if (typeof kind !== "string" || kind.length === 0)
+ throw new TypeError("Entry kind must be a non-empty string");
+ return {
+ kind,
+ is: (entry) => entry !== void 0 && entry.kind === kind
+ };
+}
+var UserEntry = defineEntry("pi.user");
+var AssistantEntry = defineEntry("pi.assistant");
+var SystemEntry = defineEntry("pi.system");
+var ToolResultEntry = defineEntry("pi.tool-result");
+var ResetEntry = defineEntry("pi.reset");
+var CompactionEntry = defineEntry("pi.compaction");
+
+// node_modules/@earendil-works/pi-durable/dist/errors.js
+var ReadAfterWrite = class extends Error {
+ constructor(method) {
+ super(`Tx.${method}() cannot read tables after the first table write`);
+ this.name = "ReadAfterWrite";
+ }
+};
+var StorageRejected = class extends Error {
+ constructor(message, options) {
+ super(message, options);
+ this.name = "StorageRejected";
+ }
+};
+var ConversationBusy = class extends Error {
+ conversationId;
+ constructor(conversationId) {
+ super(`Conversation ${conversationId} is busy`);
+ this.name = "ConversationBusy";
+ this.conversationId = conversationId;
+ }
+};
+
+// node_modules/@earendil-works/pi-durable/dist/harness/agent.js
+var DEFAULT_RETRY_POLICY = {
+ enabled: true,
+ maxRetries: 3,
+ baseDelayMs: 2e3,
+ maxAgentDelayMs: 6e4
+};
+var DEFAULT_COMPACTION_POLICY = {
+ enabled: true,
+ reserveTokens: 16384,
+ keepRecentTokens: 2e4,
+ backgroundTokens: 32768
+};
+var DEFAULT_PROGRESS_POLICY = {
+ partialIntervalMs: 100,
+ outputIntervalMs: 100
+};
+var INSTRUCTIONS_KEY = "instructions";
+var AgentDoc = defineDoc({
+ kind: "pi.agent",
+ version: 1,
+ scope: "conversation",
+ history: "rewindable",
+ fork: "asOf",
+ initial: () => ({}),
+ checkpointWhen: () => true
+});
+function resolveSettings(settings2) {
+ const extensions = settings2?.extensions;
+ return {
+ ...extensions === void 0 ? {} : { extensions },
+ stream: { ...settings2?.stream },
+ retry: { ...DEFAULT_RETRY_POLICY, ...settings2?.retry },
+ compaction: { ...DEFAULT_COMPACTION_POLICY, ...settings2?.compaction },
+ progress: { ...DEFAULT_PROGRESS_POLICY, ...settings2?.progress },
+ toolExecution: settings2?.toolExecution ?? "parallel",
+ steeringMode: settings2?.steeringMode ?? "one-at-a-time",
+ followUpMode: settings2?.followUpMode ?? "one-at-a-time"
+ };
+}
+async function configure(tx, conversationId, change) {
+ const state3 = await tx.doc(AgentDoc, conversationId);
+ applyChange(state3, change);
+}
+async function addTools(tx, conversationId, added) {
+ const state3 = await tx.doc(AgentDoc, conversationId);
+ const tools = state3.tools;
+ if (tools === void 0)
+ return;
+ if (Array.isArray(tools)) {
+ for (const name of added)
+ if (!tools.includes(name))
+ tools.push(name);
+ } else {
+ const remove = tools.remove;
+ if (remove.some((name) => added.includes(name))) {
+ state3.tools = { remove: remove.filter((name) => !added.includes(name)) };
+ }
+ }
+}
+function applyChange(state3, change) {
+ const set = (key, value) => {
+ if (value === void 0)
+ return;
+ if (value === null)
+ delete state3[key];
+ else
+ state3[key] = value;
+ };
+ set("model", change.model === void 0 || change.model === null ? change.model : { ...change.model });
+ set("thinkingLevel", change.thinkingLevel);
+ const extensions = change.extensions;
+ set("extensions", extensions === void 0 || extensions === null ? extensions : isList(extensions) ? names(extensions) : {
+ ...extensions.add === void 0 ? {} : { add: names(extensions.add) },
+ ...extensions.remove === void 0 ? {} : { remove: names(extensions.remove) }
+ });
+ const tools = change.tools;
+ set("tools", tools === void 0 || tools === null ? tools : isList(tools) ? names(tools) : { remove: names(tools.remove) });
+ set("instructions", change.instructions);
+ set("cwd", change.cwd);
+}
+function isList(value) {
+ return Array.isArray(value);
+}
+function names(items) {
+ return items.map((item) => item.name);
+}
+async function createAgent(tx, conversation) {
+ if (conversation.parent !== void 0)
+ return;
+ const agent = await tx.doc(AgentDoc, conversation.id);
+ if (conversation.owner === void 0)
+ return;
+ const owner = await tx.doc(AgentDoc, conversation.owner.conversationId);
+ Object.assign(agent, copyJson(owner));
+}
+function agentHooks(agent, taskName) {
+ const handlers = [];
+ for (const extension of agent.extensions) {
+ for (const hook2 of extension.hooks ?? [])
+ if (hook2.task === taskName)
+ handlers.push(hook2.handlers);
+ }
+ return handlers;
+}
+function resolveAgent(state3, snapshot, settings2, report) {
+ const extensions = selectExtensions(state3?.extensions, snapshot, settings2);
+ const composed = /* @__PURE__ */ new Map();
+ for (const extension of extensions)
+ for (const tool of extension.tools ?? [])
+ composed.set(tool.name, tool);
+ const sections = /* @__PURE__ */ new Map();
+ for (const extension of extensions) {
+ for (const section2 of extension.sections ?? [])
+ sections.set(section2.key, section2);
+ }
+ for (const extension of extensions) {
+ for (const wrap of extension.wraps ?? []) {
+ if ("tool" in wrap)
+ applyWrap(composed, wrap.tool, (tool) => wrap.wrap(tool), (tool) => tool.name, report);
+ else
+ applyWrap(sections, wrap.section, (section2) => wrap.wrap(section2), (section2) => section2.key, report);
+ }
+ }
+ const filter = state3?.tools;
+ let tools;
+ if (filter === void 0)
+ tools = [...composed.values()];
+ else if (Array.isArray(filter)) {
+ tools = [];
+ for (const name of new Set(filter)) {
+ const tool = composed.get(name);
+ if (tool !== void 0)
+ tools.push(tool);
+ }
+ } else {
+ const removed = new Set(filter.remove);
+ tools = [...composed.values()].filter((tool) => !removed.has(tool.name));
+ }
+ const instructions2 = state3?.instructions;
+ const agentSections = [...sections.values()];
+ if (instructions2 !== void 0)
+ agentSections.push({ key: INSTRUCTIONS_KEY, render: () => instructions2 });
+ const agent = {
+ ...state3?.model === void 0 ? {} : { model: state3.model },
+ thinkingLevel: state3?.thinkingLevel ?? "off",
+ extensions,
+ tools,
+ sections: agentSections,
+ ...instructions2 === void 0 ? {} : { instructions: instructions2 },
+ ...state3?.cwd === void 0 ? {} : { cwd: state3.cwd }
+ };
+ return agent;
+}
+function selectExtensions(stored, snapshot, settings2) {
+ let selected;
+ if (Array.isArray(stored))
+ selected = stored;
+ else {
+ const base = settings2.extensions?.map((extension) => extension.name) ?? snapshot.installed().map((e) => e.name);
+ const edit = stored;
+ const removed = new Set(edit?.remove ?? []);
+ selected = [...base, ...edit?.add ?? []].filter((name) => !removed.has(name));
+ }
+ const extensions = [];
+ for (const name of new Set(selected)) {
+ const extension = snapshot.extension(name);
+ if (extension !== void 0)
+ extensions.push(extension);
+ }
+ return extensions;
+}
+function applyWrap(items, target, wrap, nameOf, report) {
+ const item = items.get(target);
+ if (item === void 0)
+ return;
+ try {
+ const wrapped = wrap(item);
+ if (nameOf(wrapped) !== target)
+ throw new Error(`Wrapper renamed ${target} to ${nameOf(wrapped)}`);
+ items.set(target, wrapped);
+ } catch (error) {
+ items.delete(target);
+ report(error);
+ }
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/compaction.js
+init_estimate();
+
+// node_modules/@earendil-works/pi-ai/dist/utils/retry.js
+function buildProviderErrorPattern(patterns) {
+ return new RegExp(patterns.join("|"), "i");
+}
+var NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN = buildProviderErrorPattern([
+ // OpenCode Go/free-tier limits returned as 429 JSON error types by OpenCode's
+ // Zen API. These are subscription/account limits, not transient throttles.
+ "GoUsageLimitError",
+ "FreeUsageLimitError",
+ // OpenCode Go subscription-limit text asks users to enable available-balance
+ // usage after rolling/weekly/monthly limits are reached.
+ "Monthly usage limit reached",
+ "available balance",
+ // Generic quota/budget/billing exhaustion. `insufficient_quota` is OpenAI's
+ // quota/billing error code; the other strings cover common gateway wording.
+ "insufficient_quota",
+ "out of budget",
+ "quota exceeded",
+ "billing",
+ // Sign in with ChatGPT: the subscription's shared usage limit, which resets
+ // after hours rather than seconds.
+ "subscription_sharing_usage_limit_exceeded"
+]);
+var RETRYABLE_PROVIDER_ERROR_PATTERN = buildProviderErrorPattern([
+ // Generic provider load, HTTP status, and server-side transient failures.
+ "overloaded",
+ "currently experiencing high demand",
+ "model is at capacity",
+ "rate.?limit",
+ "too many requests",
+ "429",
+ "500",
+ "502",
+ "503",
+ "504",
+ "520",
+ "524",
+ "service.?unavailable",
+ "server.?error",
+ "internal.?error",
+ // Wrapper/provider text for transient upstream failures, including OpenRouter
+ // "Provider returned error" responses (#2264).
+ "provider.?returned.?error",
+ "exceeded request buffer limit while retrying upstream",
+ // Network, proxy, and fetch transport failures. This includes OpenAI Codex
+ // raw-fetch failures such as "upstream connect", "connection refused", and
+ // "reset before headers" (#733), plus OpenRouter connection drops (#3317).
+ "network.?error",
+ "connection.?error",
+ "connection.?refused",
+ "connection.?lost",
+ "other side closed",
+ "fetch failed",
+ "getaddrinfo",
+ "ENOTFOUND",
+ "EAI_AGAIN",
+ "upstream.?connect",
+ "reset before headers",
+ "socket hang up",
+ "socket connection was closed",
+ "timed? out",
+ "timeout",
+ "terminated",
+ // WebSocket transports can report close/error text instead of HTTP/fetch text.
+ "websocket.?closed",
+ "websocket.?error",
+ // Premature stream endings from SDKs and transports. Anthropic can throw
+ // "stream ended without ..." and "Anthropic stream ended before message_stop"
+ // (#4433); Bedrock/Smithy can throw an HTTP/2 no-response error (#3594).
+ "ended without",
+ "stream ended before message_stop",
+ "stream ended before a terminal response event",
+ "http2 request did not get a response",
+ // Provider-requested retry delay cap failures should flow through the outer
+ // retry policy so callers can surface/abort the backoff (#1123).
+ "retry delay",
+ // Explicit retry guidance emitted mid-stream by OpenAI Responses and Bedrock
+ // stream exceptions (#6019).
+ "you can retry your request",
+ "try your request again",
+ "please retry your request",
+ // gRPC based providers (e.g. NVIDIA NIM)
+ "ResourceExhausted",
+ // Sign in with ChatGPT: usage or user data temporarily unavailable. Usage
+ // failures can arrive mid-stream without an HTTP 503 in the message.
+ "subscription_sharing_usage_unavailable",
+ "subscription_sharing_user_unavailable"
+]);
+var DEFAULT_MAX_AGENT_RETRY_DELAY_MS = 6e4;
+function retryDelayMs(policy, attempt) {
+ const delay2 = policy.baseDelayMs * 2 ** Math.max(0, attempt - 1);
+ const safeDelay = Number.isSafeInteger(delay2) ? delay2 : Number.MAX_SAFE_INTEGER;
+ return Math.min(safeDelay, policy.maxAgentDelayMs ?? DEFAULT_MAX_AGENT_RETRY_DELAY_MS);
+}
+function isRetryableAssistantError(message) {
+ if (message.stopReason !== "error" || !message.errorMessage)
+ return false;
+ const errorMessage = message.errorMessage;
+ if (NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN.test(errorMessage))
+ return false;
+ return RETRYABLE_PROVIDER_ERROR_PATTERN.test(errorMessage);
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tasks.js
+function defineTask(definition) {
+ return { definition };
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/context.js
+var SCAN_PAGE_SIZE = 256;
+var EXCLUDED_STOP_REASONS = /* @__PURE__ */ new Set(["aborted", "error", "deferred"]);
+var MISSING_RESULT_TEXT = "Tool result unavailable: history ends before this call completed.";
+async function captureContextBounds(storage, conversationId, context, at) {
+ let tail;
+ if (at === void 0) {
+ tail = (await storage.scanEntries({ conversationId }, 1, void 0, context)).items[0]?.id;
+ if (tail === void 0)
+ return void 0;
+ } else {
+ if (await storage.entry(conversationId, at, context) === void 0) {
+ throw new Error(`Entry ${at} is not visible from conversation ${conversationId}`);
+ }
+ tail = at;
+ }
+ return { head: await storage.findLatestHeadMarker(conversationId, tail, context), tail };
+}
+async function readContext(session, storage, conversationId, context, at) {
+ const bounds = await session.readOnLine(() => captureContextBounds(storage, conversationId, context, at));
+ return deriveContext(storage, conversationId, bounds, context);
+}
+async function deriveContext(storage, conversationId, bounds, context) {
+ if (bounds === void 0)
+ return { head: void 0, entries: [], contributions: [], messages: [] };
+ const head = bounds.head;
+ const range = await scanRange(storage, conversationId, bounds, context);
+ const edits = /* @__PURE__ */ new Map();
+ for (const entry of range)
+ for (const edit of entry.edits ?? [])
+ edits.set(edit.target, edit);
+ const entries = selectActive(head, range);
+ const contributions = entries.map((entry) => {
+ const edit = edits.get(entry.id);
+ if (edit?.action === "omit")
+ return [];
+ const contributed = edit?.action === "replace" ? edit.messages : entry.model ?? [];
+ return contributed.filter((message) => message.role !== "assistant" || !EXCLUDED_STOP_REASONS.has(message.stopReason));
+ });
+ return { head, entries, contributions, messages: orderToolResults(contributions.flat()) };
+}
+async function activeEntries(storage, conversationId, bounds, context) {
+ if (bounds === void 0)
+ return [];
+ return selectActive(bounds.head, await scanRange(storage, conversationId, bounds, context));
+}
+async function scanRange(storage, conversationId, bounds, context) {
+ const head = bounds.head;
+ const range = [];
+ let cursor;
+ do {
+ const page2 = await storage.scanEntries(head === void 0 ? { conversationId, maxEntryId: bounds.tail } : { conversationId, minEntryId: head.head, maxEntryId: bounds.tail }, SCAN_PAGE_SIZE, cursor, context);
+ range.push(...page2.items);
+ cursor = page2.next;
+ } while (cursor !== void 0);
+ return range.reverse();
+}
+function selectActive(head, range) {
+ return head === void 0 ? range : [head, ...range.filter((entry) => entry.head === void 0)];
+}
+function orderToolResults(messages) {
+ const ordered = [];
+ for (let index3 = 0; index3 < messages.length; index3++) {
+ const message = messages[index3];
+ if (message.role === "toolResult")
+ continue;
+ ordered.push(message);
+ if (message.role !== "assistant")
+ continue;
+ const calls = message.content.filter((content) => content.type === "toolCall");
+ if (calls.length === 0)
+ continue;
+ const results = /* @__PURE__ */ new Map();
+ for (let next = index3 + 1; next < messages.length && messages[next].role !== "assistant"; next++) {
+ const candidate = messages[next];
+ if (candidate.role === "toolResult" && !results.has(candidate.toolCallId)) {
+ results.set(candidate.toolCallId, next);
+ }
+ }
+ for (const call of calls) {
+ const resultIndex = results.get(call.id);
+ ordered.push(resultIndex === void 0 ? missingResult(call, message.timestamp) : messages[resultIndex]);
+ }
+ }
+ return ordered;
+}
+function missingResult(call, timestamp) {
+ return {
+ role: "toolResult",
+ toolCallId: call.id,
+ toolName: call.name,
+ content: [{ type: "text", text: MISSING_RESULT_TEXT }],
+ isError: true,
+ details: { reason: "missing_result" },
+ timestamp
+ };
+}
+
+// node_modules/@earendil-works/pi-ai/dist/utils/overflow.js
+var OVERFLOW_PATTERNS = [
+ /prompt (?:is )?too long/i,
+ // Anthropic and z.ai token overflow
+ /prompt exceeds max length/i,
+ // z.ai CN endpoint token overflow
+ /request_too_large/i,
+ // Anthropic request byte-size overflow (HTTP 413)
+ /input is too long for requested model/i,
+ // Amazon Bedrock
+ /exceeds the context window/i,
+ // OpenAI (Completions & Responses API)
+ /exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,
+ // OpenAI-compatible proxies (LiteLLM)
+ /input token count.*exceeds the maximum/i,
+ // Google (Gemini)
+ /maximum prompt length is \d+/i,
+ // xAI (Grok)
+ /reduce the length of the messages/i,
+ // Groq
+ /maximum context length is \d+ tokens/i,
+ // OpenRouter (most backends)
+ /exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,
+ // OpenRouter/Poolside
+ /input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,
+ // Together AI
+ /exceeds the limit of \d+/i,
+ // GitHub Copilot
+ /exceeds the available context size/i,
+ // llama.cpp server
+ /greater than the context length/i,
+ // LM Studio
+ /context window exceeds limit/i,
+ // MiniMax
+ /exceeded model token limit/i,
+ // Kimi For Coding
+ /too large for model with \d+ maximum context length/i,
+ // Mistral
+ /prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,
+ // DS4 server
+ /model_context_window_exceeded/i,
+ // z.ai non-standard finish_reason surfaced as error text
+ /prompt too long; exceeded (?:max )?context length/i,
+ // Ollama explicit overflow error
+ /range of input length should be/i,
+ // DashScope / Qwen Token Plan
+ /context[_ ]length[_ ]exceeded/i,
+ // Generic fallback
+ /too many tokens/i,
+ // Generic fallback
+ /token limit exceeded/i
+ // Generic fallback
+];
+var CEREBRAS_BODYLESS_OVERFLOW_PATTERN = /^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i;
+var NON_OVERFLOW_PATTERNS = [
+ /^(Throttling error|Service unavailable):/i,
+ // AWS Bedrock non-overflow errors (human-readable prefixes from formatBedrockError)
+ /rate limit/i,
+ // Generic rate limiting
+ /too many requests/i
+ // Generic HTTP 429 style
+];
+function isContextOverflow(message, contextWindow) {
+ if (message.stopReason === "error" && message.errorMessage) {
+ const isNonOverflow = NON_OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage));
+ if (!isNonOverflow) {
+ if (OVERFLOW_PATTERNS.some((p) => p.test(message.errorMessage))) {
+ return true;
+ }
+ if (message.provider === "cerebras" && CEREBRAS_BODYLESS_OVERFLOW_PATTERN.test(message.errorMessage)) {
+ return true;
+ }
+ }
+ }
+ if (contextWindow && message.stopReason === "stop") {
+ const inputTokens = message.usage.input + message.usage.cacheRead;
+ if (inputTokens > contextWindow) {
+ return true;
+ }
+ }
+ if (contextWindow && message.stopReason === "length" && message.usage.output === 0) {
+ const inputTokens = message.usage.input + message.usage.cacheRead;
+ if (inputTokens >= contextWindow * 0.99) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/generation.js
+init_transcript();
+
+// node_modules/@earendil-works/pi-durable/dist/harness/inbox.js
+var InboxDoc = defineDoc({
+ kind: "pi.inbox",
+ version: 1,
+ scope: "conversation",
+ history: "latest",
+ fork: "initial",
+ initial: () => ({ items: [] }),
+ checkpointWhen: (value) => value.items.length === 0
+});
+async function prepareBoundary(tx, conversationId, modes) {
+ const head = (await tx.latestHeadMarker(conversationId))?.head;
+ const inbox = await tx.doc(InboxDoc, conversationId);
+ return {
+ conversationId,
+ inbox,
+ steeringMode: modes.steeringMode,
+ followUpMode: modes.followUpMode,
+ head
+ };
+}
+async function applyBoundary(tx, boundary, at, now) {
+ const { conversationId, inbox } = boundary;
+ const items = inbox.items;
+ const reset = items.some((item) => item.mode === "write" && item.entry.head === "self");
+ const final = at === "final" || reset;
+ const pick = (mode, queueMode) => {
+ const indexes = items.flatMap((item, index3) => item.mode === mode ? [index3] : []);
+ return queueMode === "all" ? indexes : indexes.slice(0, 1);
+ };
+ const writes = items.flatMap((item, index3) => item.mode === "write" ? [index3] : []);
+ const users = [...pick("steer", boundary.steeringMode), ...final ? pick("followUp", boundary.followUpMode) : []];
+ users.sort((a, b) => a - b);
+ for (const index3 of writes) {
+ const item = items[index3];
+ const draft = item.entry;
+ if (isStale(boundary, draft)) {
+ tx.settleSubmission(item.id, { status: "unanswered", reason: "stale" });
+ continue;
+ }
+ const entry = await tx.appendEntry(conversationId, draft);
+ if (draft.head !== void 0)
+ boundary.head = draft.head === "self" ? entry.id : draft.head;
+ tx.placeSubmission(item.id, entry.id);
+ }
+ const placed = [];
+ for (const index3 of users) {
+ const item = items[index3];
+ const message = { role: "user", content: item.content, timestamp: now };
+ const entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });
+ tx.placeSubmission(item.id, entry.id);
+ placed.push(item.id);
+ }
+ const removed = [...writes, ...users].sort((a, b) => b - a);
+ for (const index3 of removed)
+ items.splice(index3, 1);
+ return { users: placed, reset };
+}
+function isStale(boundary, entry) {
+ return typeof entry.head === "number" && boundary.head !== void 0 && entry.head < boundary.head;
+}
+async function removeInboxItem(tx, conversationId, id) {
+ const items = (await tx.doc(InboxDoc, conversationId)).items;
+ const index3 = items.findIndex((item) => item.id === id);
+ if (index3 >= 0)
+ items.splice(index3, 1);
+}
+async function withdrawQueuedInputs(tx, conversationId) {
+ const items = (await tx.doc(InboxDoc, conversationId)).items;
+ for (let index3 = items.length - 1; index3 >= 0; index3--) {
+ const item = items[index3];
+ if (item.mode === "write")
+ continue;
+ tx.settleSubmission(item.id, { status: "unanswered", reason: "aborted" });
+ items.splice(index3, 1);
+ }
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/json.js
+function assignJson(target, key, value) {
+ const slots = target;
+ const current = slots[key];
+ if (isRecord(current) && isRecord(value)) {
+ for (const name of Object.keys(current))
+ if (!Object.hasOwn(value, name))
+ delete current[name];
+ for (const [name, child] of Object.entries(value))
+ assignJson(current, name, child);
+ return;
+ }
+ if (Array.isArray(current) && Array.isArray(value) && current.length <= value.length) {
+ const items = current;
+ for (let index3 = 0; index3 < value.length; index3++) {
+ if (index3 < items.length)
+ assignJson(items, index3, value[index3]);
+ else
+ items.push(value[index3]);
+ }
+ return;
+ }
+ if (current !== value)
+ slots[key] = value;
+}
+function isRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/prompt.js
+init_transcript();
+function replaySections(messages) {
+ const shown = /* @__PURE__ */ new Map();
+ for (const message of messages) {
+ if (message.role !== "system" || message.sections === void 0)
+ continue;
+ for (const [key, value] of Object.entries(message.sections)) {
+ if (value === null)
+ shown.delete(key);
+ else
+ shown.set(key, value);
+ }
+ }
+ return shown;
+}
+async function renderSections(sections, input, shown, report, context) {
+ const desired = /* @__PURE__ */ new Map();
+ for (const section2 of sections) {
+ let text;
+ try {
+ text = await section2.render(input, context);
+ } catch (error) {
+ if (context.abortSignal?.aborted)
+ throw error;
+ report(error);
+ const kept = shown.get(section2.key);
+ if (kept !== void 0)
+ desired.set(section2.key, kept);
+ continue;
+ }
+ if (text === void 0)
+ continue;
+ desired.set(section2.key, section2.tag === false ? text : `<${section2.key}>
+${text}
+${section2.key}>`);
+ }
+ return desired;
+}
+function planSystemEntries(view, desired, tools, timestamp) {
+ const head = view.head;
+ if (head !== void 0 && !view.entries.some((entry) => SystemEntry.is(entry) && entry.id > head.id)) {
+ const edits = view.entries.filter((entry) => SystemEntry.is(entry)).map((entry) => ({ target: entry.id, action: "omit" }));
+ const baseline = systemEntry(Object.fromEntries(desired), { toolsRemoved: [], toolsAdded: tools.map(toToolDeclaration) }, timestamp);
+ return [edits.length === 0 ? baseline : { ...baseline, edits }];
+ }
+ const sections = planSections(replaySections(view.messages), desired);
+ const changes = planTools(getCurrentTools(view.messages), tools);
+ if (changes.toolsRemoved.length === 0 && changes.toolsAdded.length === 0) {
+ return sections.map((patch) => systemEntry(patch, void 0, timestamp));
+ }
+ if (sections.length === 0)
+ return [systemEntry(void 0, changes, timestamp)];
+ return sections.map((patch, index3) => systemEntry(patch, index3 === sections.length - 1 ? changes : void 0, timestamp));
+}
+function planTools(offered, desired) {
+ const wanted = new Map(desired.map((tool) => [tool.name, tool]));
+ const kept = offered.filter((tool) => {
+ const next = wanted.get(tool.name);
+ return next !== void 0 && declarationsEqual(tool, next);
+ });
+ const keptNames = new Set(kept.map((tool) => tool.name));
+ const added = desired.filter((tool) => !keptNames.has(tool.name));
+ const replayed = [...kept, ...added];
+ if (replayed.some((tool, index3) => tool.name !== desired[index3].name)) {
+ return {
+ toolsRemoved: offered.map((tool) => ({ name: tool.name })),
+ toolsAdded: desired.map(toToolDeclaration)
+ };
+ }
+ return {
+ toolsRemoved: offered.filter((tool) => !keptNames.has(tool.name)).map((tool) => ({ name: tool.name })),
+ toolsAdded: added.map(toToolDeclaration)
+ };
+}
+function planSections(shown, desired) {
+ const patchedOrder = [
+ ...[...shown.keys()].filter((key) => desired.has(key)),
+ ...[...desired.keys()].filter((key) => !shown.has(key))
+ ];
+ const desiredOrder = [...desired.keys()];
+ if (patchedOrder.some((key, index3) => key !== desiredOrder[index3])) {
+ return [Object.fromEntries([...shown.keys()].map((key) => [key, null])), Object.fromEntries(desired)];
+ }
+ const patch = {};
+ for (const [key, value] of shown) {
+ const next = desired.get(key);
+ if (next !== value)
+ patch[key] = next ?? null;
+ }
+ for (const [key, value] of desired)
+ if (!shown.has(key))
+ patch[key] = value;
+ return Object.keys(patch).length === 0 ? [] : [patch];
+}
+function systemEntry(sections, tools, timestamp) {
+ const message = {
+ role: "system",
+ content: "",
+ ...sections === void 0 ? {} : { sections },
+ ...tools === void 0 || tools.toolsRemoved.length === 0 ? {} : { toolsRemoved: tools.toolsRemoved },
+ ...tools === void 0 || tools.toolsAdded.length === 0 ? {} : { toolsAdded: tools.toolsAdded },
+ timestamp
+ };
+ return { model: [message] };
+}
+
+// node_modules/@earendil-works/pi-ai/dist/utils/uuid.js
+var MAX_UUID_V7_TIMESTAMP = 281474976710655;
+var MAX_SEQUENCE = (1n << 41n) - 1n;
+var lastOrdinaryTimestamp = -1;
+var sequence;
+function uuidv7(timestampMs) {
+ const requestedTimestamp = timestampMs ?? Date.now();
+ if (!Number.isInteger(requestedTimestamp) || requestedTimestamp < 0 || requestedTimestamp > MAX_UUID_V7_TIMESTAMP) {
+ throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${MAX_UUID_V7_TIMESTAMP}`);
+ }
+ const effectiveTimestamp = timestampMs === void 0 ? Math.max(requestedTimestamp, lastOrdinaryTimestamp) : timestampMs;
+ if (timestampMs === void 0)
+ lastOrdinaryTimestamp = effectiveTimestamp;
+ const bytes = new Uint8Array(16);
+ globalThis.crypto.getRandomValues(bytes);
+ if (sequence === void 0) {
+ sequence = BigInt(bytes[1]) << 32n | BigInt(bytes[2]) << 24n | BigInt(bytes[3]) << 16n | BigInt(bytes[4]) << 8n | BigInt(bytes[5]);
+ } else {
+ if (sequence === MAX_SEQUENCE)
+ throw new RangeError("UUIDv7 generator sequence exhausted");
+ sequence++;
+ }
+ const timestamp = BigInt(effectiveTimestamp);
+ for (let index3 = 5; index3 >= 0; index3--) {
+ bytes[index3] = Number(timestamp >> BigInt((5 - index3) * 8)) & 255;
+ }
+ bytes[6] = 112 | Number(sequence >> 37n & 0x0fn);
+ bytes[7] = Number(sequence >> 29n & 0xffn);
+ bytes[8] = 128 | Number(sequence >> 23n & 0x3fn);
+ bytes[9] = Number(sequence >> 15n & 0xffn);
+ bytes[10] = Number(sequence >> 7n & 0xffn);
+ bytes[11] = Number((sequence & 0x7fn) << 1n) | bytes[11] & 1;
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/provider.js
+var ProviderDoc = defineDoc({
+ kind: "pi.provider",
+ version: 1,
+ scope: "conversation",
+ history: "latest",
+ fork: "initial",
+ initial: () => ({ sessionId: uuidv7() }),
+ checkpointWhen: () => true
+});
+async function ensureProviderSessionId(runtime, context) {
+ const existing = await runtime.snapshot(ProviderDoc, runtime.conversationId, context);
+ if (existing !== void 0)
+ return existing.sessionId;
+ let created;
+ await runtime.commit(async (tx) => {
+ created = (await tx.doc(ProviderDoc, runtime.conversationId)).sessionId;
+ return void 0;
+ }, context);
+ if (created === void 0)
+ throw new Error(`Conversation ${runtime.conversationId} has no provider session ID`);
+ return created;
+}
+
+// node_modules/typebox/build/system/arguments/arguments.mjs
+var arguments_exports = {};
+__export(arguments_exports, {
+ Match: () => Match
+});
+function Match(args, match) {
+ return match[args.length]?.(...args) ?? (() => {
+ throw Error("Invalid Arguments");
+ })();
+}
+
+// node_modules/typebox/build/system/settings/settings.mjs
+var settings_exports = {};
+__export(settings_exports, {
+ Get: () => Get,
+ Reset: () => Reset,
+ Set: () => Set2
+});
+
+// node_modules/typebox/build/guard/emit.mjs
+var emit_exports = {};
+__export(emit_exports, {
+ And: () => And,
+ ArrayLiteral: () => ArrayLiteral,
+ ArrowFunction: () => ArrowFunction,
+ Call: () => Call,
+ ConstDeclaration: () => ConstDeclaration,
+ Constant: () => Constant,
+ Counted: () => Counted2,
+ Entries: () => Entries2,
+ Every: () => Every2,
+ HasPropertyKey: () => HasPropertyKey2,
+ If: () => If,
+ IsArray: () => IsArray2,
+ IsBigInt: () => IsBigInt2,
+ IsBoolean: () => IsBoolean2,
+ IsConstructor: () => IsConstructor2,
+ IsDeepEqual: () => IsDeepEqual2,
+ IsEqual: () => IsEqual2,
+ IsFunction: () => IsFunction2,
+ IsGreaterEqualThan: () => IsGreaterEqualThan2,
+ IsGreaterThan: () => IsGreaterThan2,
+ IsInteger: () => IsInteger2,
+ IsLessEqualThan: () => IsLessEqualThan2,
+ IsLessThan: () => IsLessThan2,
+ IsMaxLength: () => IsMaxLength3,
+ IsMinLength: () => IsMinLength3,
+ IsNull: () => IsNull2,
+ IsNumber: () => IsNumber2,
+ IsObject: () => IsObject2,
+ IsObjectNotArray: () => IsObjectNotArray2,
+ IsString: () => IsString2,
+ IsSymbol: () => IsSymbol2,
+ IsUndefined: () => IsUndefined2,
+ Keys: () => Keys2,
+ Member: () => Member,
+ MultipleOf: () => MultipleOf,
+ New: () => New,
+ Not: () => Not,
+ Or: () => Or,
+ ReduceAnd: () => ReduceAnd,
+ ReduceOr: () => ReduceOr,
+ Return: () => Return,
+ Some: () => Some2,
+ SomeAll: () => SomeAll2,
+ Statements: () => Statements,
+ Ternary: () => Ternary
+});
+
+// node_modules/typebox/build/guard/guard.mjs
+var guard_exports = {};
+__export(guard_exports, {
+ Counted: () => Counted,
+ Entries: () => Entries,
+ EntriesRegExp: () => EntriesRegExp,
+ Every: () => Every,
+ EveryAll: () => EveryAll,
+ GraphemeCount: () => GraphemeCount2,
+ HasPropertyKey: () => HasPropertyKey,
+ IsArray: () => IsArray,
+ IsBigInt: () => IsBigInt,
+ IsBoolean: () => IsBoolean,
+ IsClassInstance: () => IsClassInstance,
+ IsConstructor: () => IsConstructor,
+ IsDeepEqual: () => IsDeepEqual,
+ IsEqual: () => IsEqual,
+ IsFunction: () => IsFunction,
+ IsGreaterEqualThan: () => IsGreaterEqualThan,
+ IsGreaterThan: () => IsGreaterThan,
+ IsInteger: () => IsInteger,
+ IsLessEqualThan: () => IsLessEqualThan,
+ IsLessThan: () => IsLessThan,
+ IsMaxLength: () => IsMaxLength2,
+ IsMinLength: () => IsMinLength2,
+ IsMultipleOf: () => IsMultipleOf,
+ IsNull: () => IsNull,
+ IsNumber: () => IsNumber,
+ IsObject: () => IsObject,
+ IsObjectNotArray: () => IsObjectNotArray,
+ IsString: () => IsString,
+ IsSymbol: () => IsSymbol,
+ IsUndefined: () => IsUndefined,
+ IsUnsafePropertyKey: () => IsUnsafePropertyKey,
+ IsValueLike: () => IsValueLike,
+ Keys: () => Keys,
+ ShiftLeft: () => ShiftLeft,
+ Some: () => Some,
+ SomeAll: () => SomeAll,
+ Symbols: () => Symbols,
+ Values: () => Values
+});
+
+// node_modules/typebox/build/guard/string.mjs
+function IsBetween(value, min, max) {
+ return value >= min && value <= max;
+}
+function IsZeroWidthJoiner(value) {
+ return value === 8205;
+}
+function IsHighSurrogate(value) {
+ return IsBetween(value, 55296, 56319);
+}
+function IsRegionalIndicator(value) {
+ return IsBetween(value, 127462, 127487);
+}
+function IsVariationSelector(value) {
+ return IsBetween(value, 65024, 65039);
+}
+function IsCombiningMark(value) {
+ return IsBetween(value, 768, 879) || IsBetween(value, 6832, 6911) || IsBetween(value, 7616, 7679) || IsBetween(value, 65056, 65071);
+}
+function CodePointLength(value) {
+ return value > 65535 ? 2 : 1;
+}
+function ConsumeModifiers(value, index3) {
+ while (index3 < value.length) {
+ const point = value.codePointAt(index3);
+ if (IsCombiningMark(point) || IsVariationSelector(point)) {
+ index3 += CodePointLength(point);
+ } else {
+ break;
+ }
+ }
+ return index3;
+}
+function NextGraphemeClusterIndex(value, clusterStart) {
+ const startCP = value.codePointAt(clusterStart);
+ let clusterEnd = clusterStart + CodePointLength(startCP);
+ clusterEnd = ConsumeModifiers(value, clusterEnd);
+ while (clusterEnd < value.length - 1 && IsZeroWidthJoiner(value.codePointAt(clusterEnd))) {
+ const nextCP = value.codePointAt(clusterEnd + 1);
+ clusterEnd += 1 + CodePointLength(nextCP);
+ clusterEnd = ConsumeModifiers(value, clusterEnd);
+ }
+ if (IsRegionalIndicator(startCP) && clusterEnd < value.length && IsRegionalIndicator(value.codePointAt(clusterEnd))) {
+ clusterEnd += CodePointLength(value.codePointAt(clusterEnd));
+ }
+ return clusterEnd;
+}
+function IsGraphemeCodePoint(value) {
+ return value >= 768 && // above special range
+ (IsHighSurrogate(value) || IsCombiningMark(value) || IsVariationSelector(value) || IsZeroWidthJoiner(value));
+}
+function GraphemeCount(value) {
+ let count = 0;
+ let index3 = 0;
+ while (index3 < value.length) {
+ index3 = NextGraphemeClusterIndex(value, index3);
+ count++;
+ }
+ return count;
+}
+function IsMinLengthSegmented(value, minLength) {
+ let count = 0;
+ let index3 = 0;
+ while (index3 < value.length) {
+ index3 = NextGraphemeClusterIndex(value, index3);
+ if (++count >= minLength)
+ return true;
+ }
+ return false;
+}
+function IsMaxLengthSegmented(value, maxLength) {
+ let count = 0;
+ let index3 = 0;
+ while (index3 < value.length) {
+ index3 = NextGraphemeClusterIndex(value, index3);
+ if (++count > maxLength)
+ return false;
+ }
+ return true;
+}
+function IsMinLength(value, minLength) {
+ if (minLength === 0)
+ return true;
+ if (value.length < minLength)
+ return false;
+ let index3 = 0;
+ while (true) {
+ if (IsGraphemeCodePoint(value.charCodeAt(index3))) {
+ return IsMinLengthSegmented(value, minLength);
+ }
+ if (++index3 >= minLength)
+ return true;
+ }
+}
+function IsMaxLength(value, maxLength) {
+ if (value.length <= maxLength)
+ return true;
+ let index3 = 0;
+ while (true) {
+ if (IsGraphemeCodePoint(value.charCodeAt(index3))) {
+ return IsMaxLengthSegmented(value, maxLength);
+ }
+ if (++index3 > maxLength)
+ return false;
+ }
+}
+
+// node_modules/typebox/build/guard/guard.mjs
+function IsArray(value) {
+ return Array.isArray(value);
+}
+function IsBigInt(value) {
+ return IsEqual(typeof value, "bigint");
+}
+function IsBoolean(value) {
+ return IsEqual(typeof value, "boolean");
+}
+function IsConstructor(value) {
+ if (IsUndefined(value) || !IsFunction(value))
+ return false;
+ const result = Function.prototype.toString.call(value);
+ if (/^class\s/.test(result))
+ return true;
+ if (/\[native code\]/.test(result))
+ return true;
+ return false;
+}
+function IsFunction(value) {
+ return IsEqual(typeof value, "function");
+}
+function IsInteger(value) {
+ return Number.isInteger(value);
+}
+function IsNull(value) {
+ return IsEqual(value, null);
+}
+function IsNumber(value) {
+ return Number.isFinite(value);
+}
+function IsObjectNotArray(value) {
+ return IsObject(value) && !IsArray(value);
+}
+function IsObject(value) {
+ return IsEqual(typeof value, "object") && !IsNull(value);
+}
+function IsString(value) {
+ return IsEqual(typeof value, "string");
+}
+function IsSymbol(value) {
+ return IsEqual(typeof value, "symbol");
+}
+function IsUndefined(value) {
+ return IsEqual(value, void 0);
+}
+function IsEqual(left, right) {
+ return left === right;
+}
+function IsGreaterThan(left, right) {
+ return left > right;
+}
+function IsLessThan(left, right) {
+ return left < right;
+}
+function IsLessEqualThan(left, right) {
+ return left <= right;
+}
+function IsGreaterEqualThan(left, right) {
+ return left >= right;
+}
+function IsMultipleOf(dividend, divisor) {
+ if (IsBigInt(dividend) || IsBigInt(divisor)) {
+ return BigInt(dividend) % BigInt(divisor) === 0n;
+ }
+ const tolerance = 1e-10;
+ if (!IsNumber(dividend))
+ return true;
+ if (IsInteger(dividend) && 1 / divisor % 1 === 0)
+ return true;
+ const mod = dividend % divisor;
+ return Math.min(Math.abs(mod), Math.abs(mod - divisor), Math.abs(mod + divisor)) < tolerance;
+}
+function IsClassInstance(value) {
+ if (!IsObject(value))
+ return false;
+ const proto = globalThis.Object.getPrototypeOf(value);
+ if (IsNull(proto))
+ return false;
+ return IsEqual(typeof proto.constructor, "function") && !(IsEqual(proto.constructor, globalThis.Object) || IsEqual(proto.constructor.name, "Object"));
+}
+function IsValueLike(value) {
+ return IsBigInt(value) || IsBoolean(value) || IsNull(value) || IsNumber(value) || IsString(value) || IsUndefined(value);
+}
+function GraphemeCount2(value) {
+ return GraphemeCount(value);
+}
+function IsMaxLength2(value, length) {
+ return IsMaxLength(value, length);
+}
+function IsMinLength2(value, length) {
+ return IsMinLength(value, length);
+}
+function Every(value, offset, callback) {
+ return value.every((item, index3) => index3 < offset || callback(item, index3));
+}
+function EveryAll(value, offset, callback) {
+ let result = true;
+ value.forEach((item, index3) => {
+ if (index3 >= offset && !callback(item, index3))
+ result = false;
+ });
+ return result;
+}
+function Some(value, callback) {
+ return value.some((value2, index3) => callback(value2, index3));
+}
+function SomeAll(value, callback) {
+ let result = false;
+ value.forEach((item, index3) => {
+ if (callback(item, index3))
+ result = true;
+ });
+ return result;
+}
+function Counted(value, callback) {
+ return value.reduce((result, value2, index3) => callback(value2, index3) ? ++result : result, 0);
+}
+function ShiftLeft(array, true_, false_) {
+ return IsEqual(array.length, 0) ? false_() : true_(array[0], array.slice(1));
+}
+function IsUnsafePropertyKey(key) {
+ return IsEqual(key, "__proto__") || IsEqual(key, "constructor") || IsEqual(key, "prototype");
+}
+function HasPropertyKey(value, key) {
+ return IsUnsafePropertyKey(key) ? Object.prototype.hasOwnProperty.call(value, key) : key in value;
+}
+function EntriesRegExp(value) {
+ return Keys(value).map((key) => [new RegExp(`^${key}$`), value[key]]);
+}
+function Entries(value) {
+ return Object.entries(value);
+}
+function Keys(value) {
+ return Object.getOwnPropertyNames(value);
+}
+function Symbols(value) {
+ return Object.getOwnPropertySymbols(value);
+}
+function Values(value) {
+ return Object.values(value);
+}
+function DeepEqualObject(left, right) {
+ if (!IsObject(right))
+ return false;
+ const keys = Keys(left);
+ return IsEqual(keys.length, Keys(right).length) && keys.every((key) => IsDeepEqual(left[key], right[key]));
+}
+function DeepEqualArray(left, right) {
+ return IsArray(right) && IsEqual(left.length, right.length) && left.every((_, index3) => IsDeepEqual(left[index3], right[index3]));
+}
+function IsDeepEqual(left, right) {
+ return IsArray(left) ? DeepEqualArray(left, right) : IsObject(left) ? DeepEqualObject(left, right) : IsEqual(left, right);
+}
+
+// node_modules/typebox/build/guard/emit.mjs
+var identifierRegExp = /^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;
+function IsIdentifier(value) {
+ return identifierRegExp.test(value);
+}
+function And(left, right) {
+ return `(${left} && ${right})`;
+}
+function Or(left, right) {
+ return `(${left} || ${right})`;
+}
+function Not(expr) {
+ return `!(${expr})`;
+}
+function IsArray2(value) {
+ return `Array.isArray(${value})`;
+}
+function IsBigInt2(value) {
+ return `typeof ${value} === "bigint"`;
+}
+function IsBoolean2(value) {
+ return `typeof ${value} === "boolean"`;
+}
+function IsInteger2(value) {
+ return `Number.isInteger(${value})`;
+}
+function IsNull2(value) {
+ return `${value} === null`;
+}
+function IsNumber2(value) {
+ return `Number.isFinite(${value})`;
+}
+function IsObjectNotArray2(value) {
+ return And(IsObject2(value), Not(IsArray2(value)));
+}
+function IsObject2(value) {
+ return `typeof ${value} === "object" && ${value} !== null`;
+}
+function IsString2(value) {
+ return `typeof ${value} === "string"`;
+}
+function IsSymbol2(value) {
+ return `typeof ${value} === "symbol"`;
+}
+function IsUndefined2(value) {
+ return `${value} === undefined`;
+}
+function IsFunction2(value) {
+ return `typeof ${value} === "function"`;
+}
+function IsConstructor2(value) {
+ return `Guard.IsConstructor(${value})`;
+}
+function IsEqual2(left, right) {
+ return `${left} === ${right}`;
+}
+function IsGreaterThan2(left, right) {
+ return `${left} > ${right}`;
+}
+function IsLessThan2(left, right) {
+ return `${left} < ${right}`;
+}
+function IsLessEqualThan2(left, right) {
+ return `${left} <= ${right}`;
+}
+function IsGreaterEqualThan2(left, right) {
+ return `${left} >= ${right}`;
+}
+function IsMinLength3(value, length) {
+ return `Guard.IsMinLength(${value}, ${length})`;
+}
+function IsMaxLength3(value, length) {
+ return `Guard.IsMaxLength(${value}, ${length})`;
+}
+function Every2(value, offset, params, expression) {
+ return IsEqual(offset, "0") ? `${value}.every((${params[0]}, ${params[1]}) => (${expression}))` : `${value}.every((${params[0]}, ${params[1]}) => (${params[1]} < ${offset}) || (${expression}))`;
+}
+function Some2(value, params, expression) {
+ return `${value}.some((${params[0]}, ${params[1]}) => ${expression})`;
+}
+function SomeAll2(value, params, expression) {
+ return `((value) => { let result = false; value.forEach((${params[0]}, ${params[1]}) => { if (${expression}) result = true }); return result })(${value})`;
+}
+function Counted2(value, params, expression) {
+ return `${value}.reduce((result, ${params[0]}, ${params[1]}) => (${expression}) ? ++result : result, 0)`;
+}
+function Entries2(value) {
+ return `Object.entries(${value})`;
+}
+function Keys2(value) {
+ return `Object.getOwnPropertyNames(${value})`;
+}
+function HasPropertyKey2(value, key) {
+ const isProtoField = IsEqual(key, '"__proto__"') || IsEqual(key, '"constructor"');
+ return isProtoField ? `Object.prototype.hasOwnProperty.call(${value}, ${key})` : `${key} in ${value}`;
+}
+function IsDeepEqual2(left, right) {
+ return `Guard.IsDeepEqual(${left}, ${right})`;
+}
+function ArrayLiteral(elements) {
+ return `[${elements.join(", ")}]`;
+}
+function ArrowFunction(parameters, body) {
+ return `((${parameters.join(", ")}) => ${body})`;
+}
+function Call(value, arguments_) {
+ return `${value}(${arguments_.join(", ")})`;
+}
+function New(value, arguments_) {
+ return `new ${value}(${arguments_.join(", ")})`;
+}
+function Member(left, right) {
+ return `${left}${IsIdentifier(right) ? `.${right}` : `[${Constant(right)}]`}`;
+}
+function Constant(value) {
+ if (!IsValueLike(value))
+ throw Error("Unsupported Constant");
+ return IsString(value) ? JSON.stringify(value) : `${value}`;
+}
+function Ternary(condition, true_, false_) {
+ return `(${condition} ? ${true_} : ${false_})`;
+}
+function Statements(statements) {
+ return `{ ${statements.join("; ")}; }`;
+}
+function ConstDeclaration(identifier, expression) {
+ return `const ${identifier} = ${expression}`;
+}
+function If(condition, then) {
+ return `if(${condition}) { ${then} }`;
+}
+function Return(expression) {
+ return `return ${expression}`;
+}
+function ReduceAnd(operands) {
+ return IsEqual(operands.length, 0) ? "true" : operands.reduce((left, right) => And(left, right));
+}
+function ReduceOr(operands) {
+ return IsEqual(operands.length, 0) ? "false" : operands.reduce((left, right) => Or(left, right));
+}
+function MultipleOf(dividend, divisor) {
+ return `Guard.IsMultipleOf(${dividend}, ${divisor})`;
+}
+
+// node_modules/typebox/build/guard/globals.mjs
+var globals_exports = {};
+__export(globals_exports, {
+ IsBigInt64Array: () => IsBigInt64Array,
+ IsBigUint64Array: () => IsBigUint64Array,
+ IsBoolean: () => IsBoolean3,
+ IsDate: () => IsDate,
+ IsFloat32Array: () => IsFloat32Array,
+ IsFloat64Array: () => IsFloat64Array,
+ IsInt16Array: () => IsInt16Array,
+ IsInt32Array: () => IsInt32Array,
+ IsInt8Array: () => IsInt8Array,
+ IsMap: () => IsMap,
+ IsNumber: () => IsNumber3,
+ IsRegExp: () => IsRegExp,
+ IsSet: () => IsSet,
+ IsString: () => IsString3,
+ IsTypeArray: () => IsTypeArray,
+ IsUint16Array: () => IsUint16Array,
+ IsUint32Array: () => IsUint32Array,
+ IsUint8Array: () => IsUint8Array,
+ IsUint8ClampedArray: () => IsUint8ClampedArray
+});
+function IsBoolean3(value) {
+ return value instanceof Boolean;
+}
+function IsNumber3(value) {
+ return value instanceof Number;
+}
+function IsString3(value) {
+ return value instanceof String;
+}
+function IsTypeArray(value) {
+ return globalThis.ArrayBuffer.isView(value);
+}
+function IsInt8Array(value) {
+ return value instanceof globalThis.Int8Array;
+}
+function IsUint8Array(value) {
+ return value instanceof globalThis.Uint8Array;
+}
+function IsUint8ClampedArray(value) {
+ return value instanceof globalThis.Uint8ClampedArray;
+}
+function IsInt16Array(value) {
+ return value instanceof globalThis.Int16Array;
+}
+function IsUint16Array(value) {
+ return value instanceof globalThis.Uint16Array;
+}
+function IsInt32Array(value) {
+ return value instanceof globalThis.Int32Array;
+}
+function IsUint32Array(value) {
+ return value instanceof globalThis.Uint32Array;
+}
+function IsFloat32Array(value) {
+ return value instanceof globalThis.Float32Array;
+}
+function IsFloat64Array(value) {
+ return value instanceof globalThis.Float64Array;
+}
+function IsBigInt64Array(value) {
+ return value instanceof globalThis.BigInt64Array;
+}
+function IsBigUint64Array(value) {
+ return value instanceof globalThis.BigUint64Array;
+}
+function IsRegExp(value) {
+ return value instanceof globalThis.RegExp;
+}
+function IsDate(value) {
+ return value instanceof globalThis.Date;
+}
+function IsSet(value) {
+ return value instanceof globalThis.Set;
+}
+function IsMap(value) {
+ return value instanceof globalThis.Map;
+}
+
+// node_modules/typebox/build/guard/index.mjs
+var guard_default = guard_exports;
+
+// node_modules/typebox/build/system/settings/settings.mjs
+var settings = {
+ immutableTypes: false,
+ maxErrors: 8,
+ maxInstantiationCount: 128,
+ useAcceleration: true,
+ exactOptionalPropertyTypes: false,
+ enumerableKind: false,
+ correctiveParse: false,
+ unionPrioritySort: true
+};
+function Reset() {
+ settings.immutableTypes = false;
+ settings.maxErrors = 8;
+ settings.maxInstantiationCount = 128;
+ settings.useAcceleration = true;
+ settings.exactOptionalPropertyTypes = false;
+ settings.enumerableKind = false;
+ settings.correctiveParse = false;
+ settings.unionPrioritySort = true;
+}
+function Set2(options) {
+ for (const key of guard_exports.Keys(options)) {
+ const value = options[key];
+ if (value !== void 0) {
+ Object.defineProperty(settings, key, { value });
+ }
+ }
+}
+function Get() {
+ return settings;
+}
+
+// node_modules/typebox/build/schema/types/_refine.mjs
+function IsRefine(value) {
+ return guard_exports.HasPropertyKey(value, "~refine") && guard_exports.IsArray(value["~refine"]) && guard_exports.Every(value["~refine"], 0, (value2) => guard_exports.IsObject(value2) && guard_exports.HasPropertyKey(value2, "check") && guard_exports.HasPropertyKey(value2, "error") && guard_exports.IsFunction(value2.check) && guard_exports.IsFunction(value2.error));
+}
+
+// node_modules/typebox/build/schema/types/schema.mjs
+function IsSchemaObject(value) {
+ return guard_exports.IsObject(value) && !guard_exports.IsArray(value);
+}
+function IsSchemaBoolean(value) {
+ return guard_exports.IsBoolean(value);
+}
+function IsSchema(value) {
+ return IsSchemaObject(value) || IsSchemaBoolean(value);
+}
+
+// node_modules/typebox/build/schema/types/additionalItems.mjs
+function IsAdditionalItems(schema) {
+ return guard_exports.HasPropertyKey(schema, "additionalItems") && IsSchema(schema.additionalItems);
+}
+
+// node_modules/typebox/build/schema/types/additionalProperties.mjs
+function IsAdditionalProperties(schema) {
+ return guard_exports.HasPropertyKey(schema, "additionalProperties") && IsSchema(schema.additionalProperties);
+}
+
+// node_modules/typebox/build/schema/types/allOf.mjs
+function IsAllOf(schema) {
+ return guard_exports.HasPropertyKey(schema, "allOf") && guard_exports.IsArray(schema.allOf) && schema.allOf.every((value) => IsSchema(value));
+}
+
+// node_modules/typebox/build/schema/types/anchor.mjs
+function IsAnchor(schema) {
+ return guard_exports.HasPropertyKey(schema, "$anchor") && guard_exports.IsString(schema.$anchor);
+}
+
+// node_modules/typebox/build/schema/types/anyOf.mjs
+function IsAnyOf(schema) {
+ return guard_exports.HasPropertyKey(schema, "anyOf") && guard_exports.IsArray(schema.anyOf) && schema.anyOf.every((value) => IsSchema(value));
+}
+
+// node_modules/typebox/build/schema/types/const.mjs
+function IsConst(value) {
+ return guard_exports.HasPropertyKey(value, "const");
+}
+
+// node_modules/typebox/build/schema/types/contains.mjs
+function IsContains(schema) {
+ return guard_exports.HasPropertyKey(schema, "contains") && IsSchema(schema.contains);
+}
+
+// node_modules/typebox/build/schema/types/default.mjs
+function IsDefault(schema) {
+ return guard_exports.HasPropertyKey(schema, "default");
+}
+
+// node_modules/typebox/build/schema/types/dependencies.mjs
+function IsDependencies(schema) {
+ return guard_exports.HasPropertyKey(schema, "dependencies") && guard_exports.IsObject(schema.dependencies) && Object.values(schema.dependencies).every((value) => IsSchema(value) || guard_exports.IsArray(value) && value.every((value2) => guard_exports.IsString(value2)));
+}
+
+// node_modules/typebox/build/schema/types/dependentRequired.mjs
+function IsDependentRequired(schema) {
+ return guard_exports.HasPropertyKey(schema, "dependentRequired") && guard_exports.IsObject(schema.dependentRequired) && Object.values(schema.dependentRequired).every((value) => guard_exports.IsArray(value) && value.every((value2) => guard_exports.IsString(value2)));
+}
+
+// node_modules/typebox/build/schema/types/dependentSchemas.mjs
+function IsDependentSchemas(schema) {
+ return guard_exports.HasPropertyKey(schema, "dependentSchemas") && guard_exports.IsObject(schema.dependentSchemas) && Object.values(schema.dependentSchemas).every((value) => IsSchema(value));
+}
+
+// node_modules/typebox/build/schema/types/dynamicAnchor.mjs
+function IsDynamicAnchor(schema) {
+ return guard_exports.HasPropertyKey(schema, "$dynamicAnchor") && guard_exports.IsString(schema.$dynamicAnchor);
+}
+
+// node_modules/typebox/build/schema/types/dynamicRef.mjs
+function IsDynamicRef(schema) {
+ return guard_exports.HasPropertyKey(schema, "$dynamicRef") && guard_exports.IsString(schema.$dynamicRef);
+}
+
+// node_modules/typebox/build/schema/types/else.mjs
+function IsElse(schema) {
+ return guard_exports.HasPropertyKey(schema, "else") && IsSchema(schema.else);
+}
+
+// node_modules/typebox/build/schema/types/enum.mjs
+function IsEnum(schema) {
+ return guard_exports.HasPropertyKey(schema, "enum") && guard_exports.IsArray(schema.enum);
+}
+
+// node_modules/typebox/build/schema/types/exclusiveMaximum.mjs
+function IsExclusiveMaximum(schema) {
+ return guard_exports.HasPropertyKey(schema, "exclusiveMaximum") && (guard_exports.IsNumber(schema.exclusiveMaximum) || guard_exports.IsBigInt(schema.exclusiveMaximum));
+}
+
+// node_modules/typebox/build/schema/types/exclusiveMinimum.mjs
+function IsExclusiveMinimum(schema) {
+ return guard_exports.HasPropertyKey(schema, "exclusiveMinimum") && (guard_exports.IsNumber(schema.exclusiveMinimum) || guard_exports.IsBigInt(schema.exclusiveMinimum));
+}
+
+// node_modules/typebox/build/schema/types/format.mjs
+function IsFormat(schema) {
+ return guard_exports.HasPropertyKey(schema, "format") && guard_exports.IsString(schema.format);
+}
+
+// node_modules/typebox/build/schema/types/id.mjs
+function IsId(schema) {
+ return guard_exports.HasPropertyKey(schema, "$id") && guard_exports.IsString(schema.$id);
+}
+
+// node_modules/typebox/build/schema/types/if.mjs
+function IsIf(schema) {
+ return guard_exports.HasPropertyKey(schema, "if") && IsSchema(schema.if);
+}
+
+// node_modules/typebox/build/schema/types/items.mjs
+function IsItems(schema) {
+ return guard_exports.HasPropertyKey(schema, "items") && (IsSchema(schema.items) || guard_exports.IsArray(schema.items) && schema.items.every((value) => {
+ return IsSchema(value);
+ }));
+}
+function IsItemsSized(schema) {
+ return IsItems(schema) && guard_exports.IsArray(schema.items);
+}
+
+// node_modules/typebox/build/schema/types/maximum.mjs
+function IsMaximum(schema) {
+ return guard_exports.HasPropertyKey(schema, "maximum") && (guard_exports.IsNumber(schema.maximum) || guard_exports.IsBigInt(schema.maximum));
+}
+
+// node_modules/typebox/build/schema/types/maxContains.mjs
+function IsMaxContains(schema) {
+ return guard_exports.HasPropertyKey(schema, "maxContains") && guard_exports.IsNumber(schema.maxContains);
+}
+
+// node_modules/typebox/build/schema/types/maxItems.mjs
+function IsMaxItems(schema) {
+ return guard_exports.HasPropertyKey(schema, "maxItems") && guard_exports.IsNumber(schema.maxItems);
+}
+
+// node_modules/typebox/build/schema/types/maxLength.mjs
+function IsMaxLength4(schema) {
+ return guard_exports.HasPropertyKey(schema, "maxLength") && guard_exports.IsNumber(schema.maxLength);
+}
+
+// node_modules/typebox/build/schema/types/maxProperties.mjs
+function IsMaxProperties(schema) {
+ return guard_exports.HasPropertyKey(schema, "maxProperties") && guard_exports.IsNumber(schema.maxProperties);
+}
+
+// node_modules/typebox/build/schema/types/minimum.mjs
+function IsMinimum(schema) {
+ return guard_exports.HasPropertyKey(schema, "minimum") && (guard_exports.IsNumber(schema.minimum) || guard_exports.IsBigInt(schema.minimum));
+}
+
+// node_modules/typebox/build/schema/types/minContains.mjs
+function IsMinContains(schema) {
+ return guard_exports.HasPropertyKey(schema, "minContains") && guard_exports.IsNumber(schema.minContains);
+}
+
+// node_modules/typebox/build/schema/types/minItems.mjs
+function IsMinItems(schema) {
+ return guard_exports.HasPropertyKey(schema, "minItems") && guard_exports.IsNumber(schema.minItems);
+}
+
+// node_modules/typebox/build/schema/types/minLength.mjs
+function IsMinLength4(schema) {
+ return guard_exports.HasPropertyKey(schema, "minLength") && guard_exports.IsNumber(schema.minLength);
+}
+
+// node_modules/typebox/build/schema/types/minProperties.mjs
+function IsMinProperties(schema) {
+ return guard_exports.HasPropertyKey(schema, "minProperties") && guard_exports.IsNumber(schema.minProperties);
+}
+
+// node_modules/typebox/build/schema/types/multipleOf.mjs
+function IsMultipleOf2(schema) {
+ return guard_exports.HasPropertyKey(schema, "multipleOf") && (guard_exports.IsNumber(schema.multipleOf) || guard_exports.IsBigInt(schema.multipleOf));
+}
+
+// node_modules/typebox/build/schema/types/not.mjs
+function IsNot(schema) {
+ return guard_exports.HasPropertyKey(schema, "not") && IsSchema(schema.not);
+}
+
+// node_modules/typebox/build/schema/types/oneOf.mjs
+function IsOneOf(schema) {
+ return guard_exports.HasPropertyKey(schema, "oneOf") && guard_exports.IsArray(schema.oneOf) && schema.oneOf.every((value) => IsSchema(value));
+}
+
+// node_modules/typebox/build/schema/types/pattern.mjs
+function IsPattern(schema) {
+ return guard_exports.HasPropertyKey(schema, "pattern") && (guard_exports.IsString(schema.pattern) || schema.pattern instanceof RegExp);
+}
+
+// node_modules/typebox/build/schema/types/patternProperties.mjs
+function IsPatternProperties(schema) {
+ return guard_exports.HasPropertyKey(schema, "patternProperties") && guard_exports.IsObject(schema.patternProperties) && Object.values(schema.patternProperties).every((value) => IsSchema(value));
+}
+
+// node_modules/typebox/build/schema/types/prefixItems.mjs
+function IsPrefixItems(schema) {
+ return guard_exports.HasPropertyKey(schema, "prefixItems") && guard_exports.IsArray(schema.prefixItems) && schema.prefixItems.every((schema2) => IsSchema(schema2));
+}
+
+// node_modules/typebox/build/schema/types/properties.mjs
+function IsProperties(schema) {
+ return guard_exports.HasPropertyKey(schema, "properties") && guard_exports.IsObject(schema.properties) && Object.values(schema.properties).every((value) => IsSchema(value));
+}
+
+// node_modules/typebox/build/schema/types/propertyNames.mjs
+function IsPropertyNames(schema) {
+ return guard_exports.HasPropertyKey(schema, "propertyNames") && (guard_exports.IsObject(schema.propertyNames) || IsSchema(schema.propertyNames));
+}
+
+// node_modules/typebox/build/schema/types/recursiveAnchor.mjs
+function IsRecursiveAnchor(schema) {
+ return guard_exports.HasPropertyKey(schema, "$recursiveAnchor") && guard_exports.IsBoolean(schema.$recursiveAnchor);
+}
+function IsRecursiveAnchorTrue(schema) {
+ return IsRecursiveAnchor(schema) && guard_exports.IsEqual(schema.$recursiveAnchor, true);
+}
+
+// node_modules/typebox/build/schema/types/recursiveRef.mjs
+function IsRecursiveRef(schema) {
+ return guard_exports.HasPropertyKey(schema, "$recursiveRef") && guard_exports.IsString(schema.$recursiveRef);
+}
+
+// node_modules/typebox/build/schema/types/ref.mjs
+function IsRef(schema) {
+ return guard_exports.HasPropertyKey(schema, "$ref") && guard_exports.IsString(schema.$ref);
+}
+
+// node_modules/typebox/build/schema/types/required.mjs
+function IsRequired(schema) {
+ return guard_exports.HasPropertyKey(schema, "required") && guard_exports.IsArray(schema.required) && schema.required.every((value) => guard_exports.IsString(value));
+}
+
+// node_modules/typebox/build/schema/types/then.mjs
+function IsThen(schema) {
+ return guard_exports.HasPropertyKey(schema, "then") && IsSchema(schema.then);
+}
+
+// node_modules/typebox/build/schema/types/type.mjs
+function IsType(schema) {
+ return guard_exports.HasPropertyKey(schema, "type") && (guard_exports.IsString(schema.type) || guard_exports.IsArray(schema.type) && schema.type.every((value) => guard_exports.IsString(value)));
+}
+
+// node_modules/typebox/build/schema/types/uniqueItems.mjs
+function IsUniqueItems(schema) {
+ return guard_exports.HasPropertyKey(schema, "uniqueItems") && guard_exports.IsBoolean(schema.uniqueItems);
+}
+
+// node_modules/typebox/build/schema/types/unevaluatedItems.mjs
+function IsUnevaluatedItems(schema) {
+ return guard_exports.HasPropertyKey(schema, "unevaluatedItems") && IsSchema(schema.unevaluatedItems);
+}
+
+// node_modules/typebox/build/schema/types/unevaluatedProperties.mjs
+function IsUnevaluatedProperties(schema) {
+ return guard_exports.HasPropertyKey(schema, "unevaluatedProperties") && IsSchema(schema.unevaluatedProperties);
+}
+
+// node_modules/typebox/build/schema/engine/_context.mjs
+function HasUnevaluatedFromObject(value) {
+ return IsUnevaluatedItems(value) || IsUnevaluatedProperties(value) || guard_exports.Some(guard_exports.Keys(value), (key) => HasUnevaluatedFromUnknown(value[key]));
+}
+function HasUnevaluatedFromArray(value) {
+ return guard_exports.Some(value, (value2) => HasUnevaluatedFromUnknown(value2));
+}
+function HasUnevaluatedFromUnknown(value) {
+ return guard_exports.IsArray(value) ? HasUnevaluatedFromArray(value) : guard_exports.IsObject(value) ? HasUnevaluatedFromObject(value) : false;
+}
+function HasUnevaluated(context, schema) {
+ return HasUnevaluatedFromUnknown(schema) || guard_exports.Some(guard_exports.Keys(context), (key) => HasUnevaluatedFromUnknown(context[key]));
+}
+var BuildContext = class {
+ constructor(hasUnevaluated) {
+ this.hasUnevaluated = hasUnevaluated;
+ }
+ UseUnevaluated() {
+ return this.hasUnevaluated;
+ }
+ // ----------------------------------------------------------------
+ // Stack
+ // ----------------------------------------------------------------
+ Push() {
+ return emit_exports.Call(emit_exports.Member("context", "Push"), []);
+ }
+ Pop() {
+ return emit_exports.Call(emit_exports.Member("context", "Pop"), []);
+ }
+ // ----------------------------------------------------------------
+ // Top
+ // ----------------------------------------------------------------
+ AddIndex(index3) {
+ return emit_exports.Call(emit_exports.Member("context", "AddIndex"), [index3]);
+ }
+ AddKey(key) {
+ return emit_exports.Call(emit_exports.Member("context", "AddKey"), [key]);
+ }
+ Merge(results) {
+ return emit_exports.Call(emit_exports.Member("context", "Merge"), [results]);
+ }
+};
+var CheckContext = class {
+ constructor() {
+ const indices = /* @__PURE__ */ new Set();
+ const keys = /* @__PURE__ */ new Set();
+ this.stack = [{ indices, keys }];
+ }
+ // ----------------------------------------------------------------
+ // Stack
+ // ----------------------------------------------------------------
+ Push() {
+ const indices = /* @__PURE__ */ new Set();
+ const keys = /* @__PURE__ */ new Set();
+ this.stack.push({ indices, keys });
+ return true;
+ }
+ Pop() {
+ this.stack.pop();
+ return true;
+ }
+ // ----------------------------------------------------------------
+ // Top
+ // ----------------------------------------------------------------
+ AddIndex(index3) {
+ this.GetIndices().add(index3);
+ return true;
+ }
+ AddKey(key) {
+ this.GetKeys().add(key);
+ return true;
+ }
+ GetIndices() {
+ const top = this.stack[this.stack.length - 1];
+ return top.indices;
+ }
+ GetKeys() {
+ const top = this.stack[this.stack.length - 1];
+ return top.keys;
+ }
+ Merge(results) {
+ for (const context of results) {
+ context.GetIndices().forEach((value) => this.GetIndices().add(value));
+ context.GetKeys().forEach((value) => this.GetKeys().add(value));
+ }
+ return true;
+ }
+};
+var ErrorContext = class extends CheckContext {
+ constructor() {
+ super();
+ this.errors = [];
+ }
+ AtCapacity() {
+ return this.errors.length >= settings_exports.Get().maxErrors;
+ }
+ AddError(error) {
+ if (!this.AtCapacity())
+ this.errors.push(error);
+ return false;
+ }
+ GetErrors() {
+ return this.errors;
+ }
+};
+
+// node_modules/typebox/build/schema/engine/_externals.mjs
+var state2 = {
+ identifier: "External",
+ variables: []
+};
+function CreateVariable(value) {
+ const call = `External[${state2.variables.length}]`;
+ state2.variables.push(value);
+ return call;
+}
+function ResetExternal() {
+ state2.variables = [];
+}
+function GetExternal() {
+ return { ...state2 };
+}
+
+// node_modules/typebox/build/schema/engine/_refine.mjs
+function BuildRefine(_stack, _context, schema, value) {
+ const refinements = CreateVariable(schema["~refine"].map((refinement) => refinement));
+ return emit_exports.Every(refinements, emit_exports.Constant(0), ["refinement", "_"], emit_exports.Call(emit_exports.Member("refinement", "check"), [value]));
+}
+function CheckRefine(_stack, _context, schema, value) {
+ return guard_exports.Every(schema["~refine"], 0, (refinement, _) => refinement.check(value));
+}
+function ErrorRefine(_stack, context, schemaPath, instancePath, schema, value) {
+ return guard_exports.EveryAll(schema["~refine"], 0, (refinement, index3) => {
+ return refinement.check(value) || context.AddError({
+ keyword: "~refine",
+ schemaPath,
+ instancePath,
+ params: { index: index3, message: refinement.error(value) }
+ });
+ });
+}
+
+// node_modules/typebox/build/schema/engine/_unique.mjs
+var index = 0;
+function Unique() {
+ return `var_${index++}`;
+}
+
+// node_modules/typebox/build/schema/engine/additionalItems.mjs
+function IsValid(schema) {
+ return IsItems(schema) && guard_exports.IsArray(schema.items);
+}
+function BuildAdditionalItemsStandard(stack, context, schema, value) {
+ const [item, index3] = [Unique(), Unique()];
+ const isSchema = BuildSchemaPushStack(stack, context, schema.additionalItems, item);
+ const isLength = emit_exports.IsLessThan(index3, emit_exports.Constant(schema.items.length));
+ const addIndex = context.AddIndex(index3);
+ return emit_exports.Every(value, emit_exports.Constant(0), [item, index3], emit_exports.Or(isLength, emit_exports.And(isSchema, addIndex)));
+}
+function BuildAdditionalItemsFast(stack, context, schema, value) {
+ const [item, index3] = [Unique(), Unique()];
+ const isSchema = BuildSchemaPushStack(stack, context, schema.additionalItems, item);
+ const isLength = emit_exports.IsLessThan(index3, emit_exports.Constant(schema.items.length));
+ return emit_exports.Every(value, emit_exports.Constant(0), [item, index3], emit_exports.Or(isLength, isSchema));
+}
+function BuildAdditionalItems(stack, context, schema, value) {
+ if (!IsValid(schema))
+ return emit_exports.Constant(true);
+ return context.UseUnevaluated() ? BuildAdditionalItemsStandard(stack, context, schema, value) : BuildAdditionalItemsFast(stack, context, schema, value);
+}
+function CheckAdditionalItems(stack, context, schema, value) {
+ if (!IsValid(schema))
+ return true;
+ const isAdditionalItems = guard_exports.Every(value, 0, (item, index3) => {
+ return guard_exports.IsLessThan(index3, schema.items.length) || CheckSchemaPushStack(stack, context, schema.additionalItems, item) && context.AddIndex(index3);
+ });
+ return isAdditionalItems;
+}
+function ErrorAdditionalItems(stack, context, schemaPath, instancePath, schema, value) {
+ if (!IsValid(schema))
+ return true;
+ const isAdditionalItems = guard_exports.Every(value, 0, (item, index3) => {
+ const nextSchemaPath = `${schemaPath}/additionalItems`;
+ const nextInstancePath = `${instancePath}/${index3}`;
+ return guard_exports.IsLessThan(index3, schema.items.length) || ErrorSchemaPushStack(stack, context, nextSchemaPath, nextInstancePath, schema.additionalItems, item) && context.AddIndex(index3);
+ });
+ return isAdditionalItems;
+}
+
+// node_modules/typebox/build/schema/engine/_regexp.mjs
+function UnicodeRegExp(pattern) {
+ return new RegExp(pattern, "u");
+}
+
+// node_modules/typebox/build/schema/engine/additionalProperties.mjs
+function IsAdditionalPropertiesIgnored(context, additionalProperties) {
+ return !context.UseUnevaluated() && (guard_exports.IsEqual(additionalProperties, true) || guard_exports.IsObject(additionalProperties) && guard_exports.IsEqual(guard_exports.Keys(additionalProperties).length, 0));
+}
+function GetPropertyKeyAsPattern(key) {
+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return `^${escaped}$`;
+}
+function GetPropertiesPattern(schema) {
+ const patterns = [];
+ if (IsPatternProperties(schema))
+ patterns.push(...guard_exports.Keys(schema.patternProperties));
+ if (IsProperties(schema))
+ patterns.push(...guard_exports.Keys(schema.properties).map(GetPropertyKeyAsPattern));
+ return guard_exports.IsEqual(patterns.length, 0) ? "(?!)" : `(${patterns.join("|")})`;
+}
+function CanAdditionalPropertiesFast(_context, schema, _value) {
+ return IsRequired(schema) && IsProperties(schema) && !IsPatternProperties(schema) && guard_exports.IsEqual(schema.additionalProperties, false) && guard_exports.IsEqual(guard_exports.Keys(schema.properties).length, schema.required.length);
+}
+function BuildAdditionalPropertiesFast(_context, schema, value) {
+ return emit_exports.IsEqual(emit_exports.Member(emit_exports.Call(emit_exports.Member("Object", "getOwnPropertyNames"), [value]), "length"), emit_exports.Constant(schema.required.length));
+}
+function BuildAdditionalPropertiesStandard(stack, context, schema, value) {
+ const [key, _index] = [Unique(), Unique()];
+ const regexp = CreateVariable(UnicodeRegExp(GetPropertiesPattern(schema)));
+ const isSchema = BuildSchemaPushStack(stack, context, schema.additionalProperties, `${value}[${key}]`);
+ const isKey = emit_exports.Call(emit_exports.Member(regexp, "test"), [key]);
+ const addKey = context.AddKey(key);
+ const guarded = context.UseUnevaluated() ? emit_exports.Or(isKey, emit_exports.And(isSchema, addKey)) : emit_exports.Or(isKey, isSchema);
+ const result = emit_exports.Every(emit_exports.Keys(value), emit_exports.Constant(0), [key, _index], guarded);
+ return result;
+}
+function BuildAdditionalProperties(stack, context, schema, value) {
+ if (IsAdditionalPropertiesIgnored(context, schema.additionalProperties))
+ return emit_exports.Constant(true);
+ return CanAdditionalPropertiesFast(context, schema, value) ? BuildAdditionalPropertiesFast(context, schema, value) : BuildAdditionalPropertiesStandard(stack, context, schema, value);
+}
+function CheckAdditionalProperties(stack, context, schema, value) {
+ const regexp = UnicodeRegExp(GetPropertiesPattern(schema));
+ const isAdditionalProperties = guard_exports.Every(guard_exports.Keys(value), 0, (key, _index) => {
+ return regexp.test(key) || CheckSchemaPushStack(stack, context, schema.additionalProperties, value[key]) && context.AddKey(key);
+ });
+ return isAdditionalProperties;
+}
+function ErrorAdditionalProperties(stack, context, schemaPath, instancePath, schema, value) {
+ const regexp = UnicodeRegExp(GetPropertiesPattern(schema));
+ const additionalProperties = [];
+ const isAdditionalProperties = guard_exports.EveryAll(guard_exports.Keys(value), 0, (key, _index) => {
+ const nextSchemaPath = `${schemaPath}/additionalProperties`;
+ const nextInstancePath = `${instancePath}/${key}`;
+ const isAdditionalProperty = regexp.test(key) || ErrorSchemaPushStack(stack, context, nextSchemaPath, nextInstancePath, schema.additionalProperties, value[key]) && context.AddKey(key);
+ if (!isAdditionalProperty)
+ additionalProperties.push(key);
+ return isAdditionalProperty;
+ });
+ return isAdditionalProperties || context.AddError({
+ keyword: "additionalProperties",
+ schemaPath,
+ instancePath,
+ params: { additionalProperties }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/_reducer.mjs
+function Reducer(stack, context, schemas, value, check) {
+ const results = emit_exports.ConstDeclaration("results", "[]");
+ const context_n = schemas.map((_schema, index3) => emit_exports.ConstDeclaration(`context_${index3}`, emit_exports.New("CheckContext", [])));
+ const condition_n = schemas.map((schema, index3) => emit_exports.ConstDeclaration(`condition_${index3}`, emit_exports.Call(emit_exports.ArrowFunction(["context"], BuildSchema(stack, context, schema, value)), [`context_${index3}`])));
+ const checks = schemas.map((_schema, index3) => emit_exports.If(`condition_${index3}`, emit_exports.Call(emit_exports.Member("results", "push"), [`context_${index3}`])));
+ const returns = emit_exports.Return(emit_exports.And(check, context.Merge("results")));
+ return emit_exports.Call(emit_exports.ArrowFunction([], emit_exports.Statements([results, ...context_n, ...condition_n, ...checks, returns])), []);
+}
+
+// node_modules/typebox/build/schema/engine/allOf.mjs
+function BuildAllOfStandard(stack, context, schema, value) {
+ return Reducer(stack, context, schema.allOf, value, emit_exports.IsEqual(emit_exports.Member("results", "length"), emit_exports.Constant(schema.allOf.length)));
+}
+function BuildAllOfFast(stack, context, schema, value) {
+ return emit_exports.ReduceAnd(schema.allOf.map((schema2) => BuildSchema(stack, context, schema2, value)));
+}
+function BuildAllOf(stack, context, schema, value) {
+ return context.UseUnevaluated() ? BuildAllOfStandard(stack, context, schema, value) : BuildAllOfFast(stack, context, schema, value);
+}
+function CheckAllOf(stack, context, schema, value) {
+ const results = schema.allOf.reduce((result, schema2) => {
+ const nextContext = new CheckContext();
+ return CheckSchema(stack, nextContext, schema2, value) ? [...result, nextContext] : result;
+ }, []);
+ return guard_exports.IsEqual(results.length, schema.allOf.length) && context.Merge(results);
+}
+function ErrorAllOf(stack, context, schemaPath, instancePath, schema, value) {
+ const failedContexts = [];
+ const results = schema.allOf.reduce((result, schema2, index3) => {
+ const nextSchemaPath = `${schemaPath}/allOf/${index3}`;
+ const nextContext = new ErrorContext();
+ const isSchema = ErrorSchema(stack, nextContext, nextSchemaPath, instancePath, schema2, value);
+ if (!isSchema)
+ failedContexts.push(nextContext);
+ return isSchema ? [...result, nextContext] : result;
+ }, []);
+ const isAllOf = guard_exports.IsEqual(results.length, schema.allOf.length) && context.Merge(results);
+ if (!isAllOf)
+ failedContexts.forEach((failed) => failed.GetErrors().forEach((error) => context.AddError(error)));
+ return isAllOf;
+}
+
+// node_modules/typebox/build/schema/engine/anyOf.mjs
+function BuildAnyOfStandard(stack, context, schema, value) {
+ return Reducer(stack, context, schema.anyOf, value, emit_exports.IsGreaterThan(emit_exports.Member("results", "length"), emit_exports.Constant(0)));
+}
+function BuildAnyOfFast(stack, context, schema, value) {
+ return emit_exports.ReduceOr(schema.anyOf.map((schema2) => BuildSchema(stack, context, schema2, value)));
+}
+function BuildAnyOf(stack, context, schema, value) {
+ return context.UseUnevaluated() ? BuildAnyOfStandard(stack, context, schema, value) : BuildAnyOfFast(stack, context, schema, value);
+}
+function CheckAnyOf(stack, context, schema, value) {
+ const results = schema.anyOf.reduce((result, schema2) => {
+ const nextContext = new CheckContext();
+ return CheckSchema(stack, nextContext, schema2, value) ? [...result, nextContext] : result;
+ }, []);
+ return guard_exports.IsGreaterThan(results.length, 0) && context.Merge(results);
+}
+function ErrorAnyOf(stack, context, schemaPath, instancePath, schema, value) {
+ const failedContexts = [];
+ const results = schema.anyOf.reduce((result, schema2, index3) => {
+ const nextContext = new ErrorContext();
+ const nextSchemaPath = `${schemaPath}/anyOf/${index3}`;
+ const isSchema = ErrorSchema(stack, nextContext, nextSchemaPath, instancePath, schema2, value);
+ if (!isSchema)
+ failedContexts.push(nextContext);
+ return isSchema ? [...result, nextContext] : result;
+ }, []);
+ const isAnyOf = guard_exports.IsGreaterThan(results.length, 0) && context.Merge(results);
+ if (!isAnyOf)
+ failedContexts.forEach((failed) => failed.GetErrors().forEach((error) => context.AddError(error)));
+ return isAnyOf || context.AddError({
+ keyword: "anyOf",
+ schemaPath,
+ instancePath,
+ params: {}
+ });
+}
+
+// node_modules/typebox/build/schema/engine/boolean.mjs
+function BuildSchemaBoolean(_stack, _context, schema, _value) {
+ return schema ? emit_exports.Constant(true) : emit_exports.Constant(false);
+}
+function CheckSchemaBoolean(_stack, _context, schema, _value) {
+ return schema;
+}
+function ErrorSchemaBoolean(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckSchemaBoolean(stack, context, schema, value) || context.AddError({
+ keyword: "boolean",
+ schemaPath,
+ instancePath,
+ params: {}
+ });
+}
+
+// node_modules/typebox/build/schema/engine/const.mjs
+function BuildConst(_stack, _context, schema, value) {
+ return guard_exports.IsValueLike(schema.const) ? emit_exports.IsEqual(value, emit_exports.Constant(schema.const)) : emit_exports.IsDeepEqual(value, CreateVariable(schema.const));
+}
+function CheckConst(_stack, _context, schema, value) {
+ return guard_exports.IsValueLike(schema.const) ? guard_exports.IsEqual(value, schema.const) : guard_exports.IsDeepEqual(value, schema.const);
+}
+function ErrorConst(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckConst(stack, context, schema, value) || context.AddError({
+ keyword: "const",
+ schemaPath,
+ instancePath,
+ params: { allowedValue: schema.const }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/contains.mjs
+function IsValid2(schema) {
+ return !(IsMinContains(schema) && guard_exports.IsEqual(schema.minContains, 0));
+}
+function BuildContainsStandard(stack, context, schema, value) {
+ const [item, index3] = [Unique(), Unique()];
+ const isLength = emit_exports.Not(emit_exports.IsEqual(emit_exports.Member(value, "length"), emit_exports.Constant(0)));
+ const isSome = emit_exports.SomeAll(value, [item, index3], emit_exports.And(BuildSchema(stack, context, schema.contains, item), context.AddIndex(index3)));
+ return emit_exports.And(isLength, isSome);
+}
+function BuildContainsFast(stack, context, schema, value) {
+ const [item] = [Unique()];
+ const isLength = emit_exports.Not(emit_exports.IsEqual(emit_exports.Member(value, "length"), emit_exports.Constant(0)));
+ const isSome = emit_exports.Some(value, [item, "_"], BuildSchema(stack, context, schema.contains, item));
+ return emit_exports.And(isLength, isSome);
+}
+function BuildContains(stack, context, schema, value) {
+ if (!IsValid2(schema))
+ return emit_exports.Constant(true);
+ return context.UseUnevaluated() ? BuildContainsStandard(stack, context, schema, value) : BuildContainsFast(stack, context, schema, value);
+}
+function CheckContains(stack, context, schema, value) {
+ if (!IsValid2(schema))
+ return true;
+ return !guard_exports.IsEqual(value.length, 0) && guard_exports.SomeAll(value, (item, index3) => {
+ return CheckSchema(stack, context, schema.contains, item) && context.AddIndex(index3);
+ });
+}
+function ErrorContains(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckContains(stack, context, schema, value) || context.AddError({
+ keyword: "contains",
+ schemaPath,
+ instancePath,
+ params: { minContains: 1 }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/dependencies.mjs
+function BuildDependencies(stack, context, schema, value) {
+ const isLength = emit_exports.IsEqual(emit_exports.Member(emit_exports.Keys(value), "length"), emit_exports.Constant(0));
+ const isEveryDependency = emit_exports.ReduceAnd(guard_exports.Entries(schema.dependencies).map(([key, schema2]) => {
+ const notKey = emit_exports.Not(emit_exports.HasPropertyKey(value, emit_exports.Constant(key)));
+ const isSchema = BuildSchema(stack, context, schema2, value);
+ const isEveryKey = (schema3) => emit_exports.ReduceAnd(schema3.map((key2) => emit_exports.HasPropertyKey(value, emit_exports.Constant(key2))));
+ return emit_exports.Or(notKey, guard_exports.IsArray(schema2) ? isEveryKey(schema2) : isSchema);
+ }));
+ return emit_exports.Or(isLength, isEveryDependency);
+}
+function CheckDependencies(stack, context, schema, value) {
+ const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);
+ const isEvery = guard_exports.Every(guard_exports.Entries(schema.dependencies), 0, ([key, schema2]) => {
+ return !guard_exports.HasPropertyKey(value, key) || (guard_exports.IsArray(schema2) ? schema2.every((key2) => guard_exports.HasPropertyKey(value, key2)) : CheckSchema(stack, context, schema2, value));
+ });
+ return isLength || isEvery;
+}
+function ErrorDependencies(stack, context, schemaPath, instancePath, schema, value) {
+ const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);
+ const isEvery = guard_exports.EveryAll(guard_exports.Entries(schema.dependencies), 0, ([key, schema2]) => {
+ const nextSchemaPath = `${schemaPath}/dependencies/${key}`;
+ return !guard_exports.HasPropertyKey(value, key) || (guard_exports.IsArray(schema2) ? schema2.every((dependency) => guard_exports.HasPropertyKey(value, dependency) || context.AddError({
+ keyword: "dependencies",
+ schemaPath,
+ instancePath,
+ params: { property: key, dependencies: schema2 }
+ })) : ErrorSchema(stack, context, nextSchemaPath, instancePath, schema2, value));
+ });
+ return isLength || isEvery;
+}
+
+// node_modules/typebox/build/schema/engine/dependentRequired.mjs
+function BuildDependentRequired(_stack, _context, schema, value) {
+ const isLength = emit_exports.IsEqual(emit_exports.Member(emit_exports.Keys(value), "length"), emit_exports.Constant(0));
+ const isEvery = emit_exports.ReduceAnd(guard_exports.Entries(schema.dependentRequired).map(([key, keys]) => {
+ const notKey = emit_exports.Not(emit_exports.HasPropertyKey(value, emit_exports.Constant(key)));
+ const everyKey = emit_exports.ReduceAnd(keys.map((key2) => emit_exports.HasPropertyKey(value, emit_exports.Constant(key2))));
+ return emit_exports.Or(notKey, everyKey);
+ }));
+ return emit_exports.Or(isLength, isEvery);
+}
+function CheckDependentRequired(_stack, _context, schema, value) {
+ const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);
+ const isEvery = guard_exports.Every(guard_exports.Entries(schema.dependentRequired), 0, ([key, keys]) => {
+ return !guard_exports.HasPropertyKey(value, key) || keys.every((key2) => guard_exports.HasPropertyKey(value, key2));
+ });
+ return isLength || isEvery;
+}
+function ErrorDependentRequired(_stack, context, schemaPath, instancePath, schema, value) {
+ const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);
+ const isEveryEntry = guard_exports.EveryAll(guard_exports.Entries(schema.dependentRequired), 0, ([key, keys]) => {
+ return !guard_exports.HasPropertyKey(value, key) || guard_exports.EveryAll(keys, 0, (dependency) => guard_exports.HasPropertyKey(value, dependency) || context.AddError({
+ keyword: "dependentRequired",
+ schemaPath,
+ instancePath,
+ params: { property: key, dependencies: keys }
+ }));
+ });
+ return isLength || isEveryEntry;
+}
+
+// node_modules/typebox/build/schema/engine/dependentSchemas.mjs
+function BuildDependentSchemas(stack, context, schema, value) {
+ const isLength = emit_exports.IsEqual(emit_exports.Member(emit_exports.Keys(value), "length"), emit_exports.Constant(0));
+ const isEvery = emit_exports.ReduceAnd(guard_exports.Entries(schema.dependentSchemas).map(([key, schema2]) => {
+ const notKey = emit_exports.Not(emit_exports.HasPropertyKey(value, emit_exports.Constant(key)));
+ const isSchema = BuildSchema(stack, context, schema2, value);
+ return emit_exports.Or(notKey, isSchema);
+ }));
+ return emit_exports.Or(isLength, isEvery);
+}
+function CheckDependentSchemas(stack, context, schema, value) {
+ const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);
+ const isEvery = guard_exports.Every(guard_exports.Entries(schema.dependentSchemas), 0, ([key, schema2]) => {
+ return !guard_exports.HasPropertyKey(value, key) || CheckSchema(stack, context, schema2, value);
+ });
+ return isLength || isEvery;
+}
+function ErrorDependentSchemas(stack, context, schemaPath, instancePath, schema, value) {
+ const isLength = guard_exports.IsEqual(guard_exports.Keys(value).length, 0);
+ const isEvery = guard_exports.EveryAll(guard_exports.Entries(schema.dependentSchemas), 0, ([key, schema2]) => {
+ const nextSchemaPath = `${schemaPath}/dependentSchemas/${key}`;
+ return !guard_exports.HasPropertyKey(value, key) || ErrorSchema(stack, context, nextSchemaPath, instancePath, schema2, value);
+ });
+ return isLength || isEvery;
+}
+
+// node_modules/typebox/build/schema/engine/dynamicRef.mjs
+function BuildDynamicRef(stack, context, schema, value) {
+ const target = stack.DynamicRef(schema) ?? false;
+ return CreateFunction(stack, context, target, value);
+}
+function CheckDynamicRef(stack, context, schema, value) {
+ const target = stack.DynamicRef(schema) ?? false;
+ return IsSchema(target) && CheckSchema(stack, context, target, value);
+}
+function ErrorDynamicRef(stack, context, _schemaPath, instancePath, schema, value) {
+ const target = stack.DynamicRef(schema) ?? false;
+ return IsSchema(target) && ErrorSchema(stack, context, "#", instancePath, target, value);
+}
+
+// node_modules/typebox/build/schema/engine/enum.mjs
+function BuildEnum(_stack, _context, schema, value) {
+ return emit_exports.ReduceOr(schema.enum.map((option) => {
+ if (guard_exports.IsValueLike(option))
+ return emit_exports.IsEqual(value, emit_exports.Constant(option));
+ const variable = CreateVariable(option);
+ return emit_exports.IsDeepEqual(value, variable);
+ }));
+}
+function CheckEnum(_stack, _context, schema, value) {
+ return guard_exports.Some(schema.enum, (option) => guard_exports.IsValueLike(option) ? guard_exports.IsEqual(value, option) : guard_exports.IsDeepEqual(value, option));
+}
+function ErrorEnum(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckEnum(stack, context, schema, value) || context.AddError({
+ keyword: "enum",
+ schemaPath,
+ instancePath,
+ params: { allowedValues: schema.enum }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/exclusiveMaximum.mjs
+function BuildExclusiveMaximum(_stack, _context, schema, value) {
+ return emit_exports.IsLessThan(value, emit_exports.Constant(schema.exclusiveMaximum));
+}
+function CheckExclusiveMaximum(_stack, _context, schema, value) {
+ return guard_exports.IsLessThan(value, schema.exclusiveMaximum);
+}
+function ErrorExclusiveMaximum(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckExclusiveMaximum(stack, context, schema, value) || context.AddError({
+ keyword: "exclusiveMaximum",
+ schemaPath,
+ instancePath,
+ params: { comparison: "<", limit: schema.exclusiveMaximum }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/exclusiveMinimum.mjs
+function BuildExclusiveMinimum(_stack, _context, schema, value) {
+ return emit_exports.IsGreaterThan(value, emit_exports.Constant(schema.exclusiveMinimum));
+}
+function CheckExclusiveMinimum(_stack, _context, schema, value) {
+ return guard_exports.IsGreaterThan(value, schema.exclusiveMinimum);
+}
+function ErrorExclusiveMinimum(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckExclusiveMinimum(stack, context, schema, value) || context.AddError({
+ keyword: "exclusiveMinimum",
+ schemaPath,
+ instancePath,
+ params: { comparison: ">", limit: schema.exclusiveMinimum }
+ });
+}
+
+// node_modules/typebox/build/format/format.mjs
+var format_exports = {};
+__export(format_exports, {
+ Clear: () => Clear,
+ Entries: () => Entries3,
+ Get: () => Get2,
+ Has: () => Has,
+ IsDate: () => IsDate2,
+ IsDateTime: () => IsDateTime,
+ IsDuration: () => IsDuration,
+ IsEmail: () => IsEmail,
+ IsHostname: () => IsHostname2,
+ IsIPv4: () => IsIPv4,
+ IsIPv6: () => IsIPv6,
+ IsIdnEmail: () => IsIdnEmail,
+ IsIdnHostname: () => IsIdnHostname2,
+ IsIri: () => IsIri,
+ IsIriReference: () => IsIriReference,
+ IsJsonPointer: () => IsJsonPointer,
+ IsJsonPointerUriFragment: () => IsJsonPointerUriFragment,
+ IsRegex: () => IsRegex,
+ IsRelativeJsonPointer: () => IsRelativeJsonPointer,
+ IsTime: () => IsTime,
+ IsUri: () => IsUri,
+ IsUriReference: () => IsUriReference,
+ IsUriTemplate: () => IsUriTemplate,
+ IsUrl: () => IsUrl,
+ IsUuid: () => IsUuid,
+ Reset: () => Reset2,
+ Set: () => Set3,
+ Test: () => Test
+});
+
+// node_modules/typebox/build/format/date.mjs
+var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
+function IsLeapYear(year) {
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
+}
+function IsDate2(value) {
+ const matches = DATE.exec(value);
+ if (!matches)
+ return false;
+ const year = +matches[1];
+ const month = +matches[2];
+ const day = +matches[3];
+ return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && IsLeapYear(year) ? 29 : DAYS[month]);
+}
+
+// node_modules/typebox/build/format/time.mjs
+var TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;
+function IsTime(value, strictTimeZone = true) {
+ const matches = TIME.exec(value);
+ if (!matches)
+ return false;
+ if (strictTimeZone && !matches[4] && !matches[5])
+ return false;
+ const hr = +matches[1];
+ const min = +matches[2];
+ const sec = +matches[3];
+ if (hr > 23 || min > 59 || sec > 60)
+ return false;
+ if (matches[5]) {
+ const tzH2 = +matches[6];
+ const tzM2 = +matches[7];
+ if (tzH2 > 23 || tzM2 > 59)
+ return false;
+ }
+ if (sec < 60)
+ return true;
+ const tzSign = matches[5] === "-" ? -1 : 1;
+ const tzH = +(matches[6] || 0);
+ const tzM = +(matches[7] || 0);
+ const totalUtcMin = hr * 60 + min - tzSign * (tzH * 60 + tzM);
+ return (totalUtcMin % 1440 + 1440) % 1440 === 1439;
+}
+
+// node_modules/typebox/build/format/date_time.mjs
+function IsDateTime(value) {
+ const dateTime = value.split(/T/i);
+ return dateTime.length === 2 && IsDate2(dateTime[0]) && IsTime(dateTime[1]);
+}
+
+// node_modules/typebox/build/format/duration.mjs
+var Duration = /^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;
+function IsDuration(value) {
+ return Duration.test(value);
+}
+
+// node_modules/typebox/build/format/email.mjs
+var Email = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;
+function IsEmail(value) {
+ return Email.test(value);
+}
+
+// node_modules/typebox/build/format/idna/pattern/pattern.mjs
+var RE_RULE_HYPHEN_PLACEMENT = /^(?!-).*(? regexp.source).join("|"), "u");
+var RE_PERMITTED_CATEGORY = new RegExp([
+ RE_LETTER,
+ RE_EUROPEAN_SEPARATOR,
+ RE_COMMON_SEPARATOR,
+ RE_NUMBER_DECIMAL,
+ RE_MARK_NONSPACING,
+ RE_MARK_SPACING_COMBINING,
+ RE_CONTEXTO_EXCEPTIONS,
+ RE_PVALID_EXCEPTIONS
+].map((regexp) => regexp.source).join("|"), "u");
+
+// node_modules/typebox/build/format/idna/label/ascii.mjs
+function IsAsciiLabel(value) {
+ return RE_RULE_HYPHEN_PLACEMENT.test(value) && RE_RULE_NOT_RESERVED_ACE.test(value) && RE_ASCII_LDH.test(value);
+}
+
+// node_modules/typebox/build/format/idna/format/puny.mjs
+var PUNYCODE_BASE = 36;
+var PUNYCODE_TMIN = 1;
+var PUNYCODE_TMAX = 26;
+var PUNYCODE_SKEW = 38;
+var PUNYCODE_DAMP = 700;
+var PUNYCODE_INITIAL_BIAS = 72;
+var PUNYCODE_INITIAL_N = 128;
+function ThrowDontCare() {
+ throw null;
+}
+function IsAcePrefixed(value) {
+ return value.toLowerCase().startsWith("xn--");
+}
+function Adapt(delta, numPoints, firstTime) {
+ delta = firstTime ? Math.floor(delta / PUNYCODE_DAMP) : delta >> 1;
+ delta += Math.floor(delta / numPoints);
+ let k = 0;
+ while (delta > (PUNYCODE_BASE - PUNYCODE_TMIN) * PUNYCODE_TMAX >> 1) {
+ delta = Math.floor(delta / (PUNYCODE_BASE - PUNYCODE_TMIN));
+ k += PUNYCODE_BASE;
+ }
+ return k + Math.floor((PUNYCODE_BASE - PUNYCODE_TMIN + 1) * delta / (delta + PUNYCODE_SKEW));
+}
+function Decode(value) {
+ const output = [];
+ let n = PUNYCODE_INITIAL_N;
+ let i = 0;
+ let bias = PUNYCODE_INITIAL_BIAS;
+ const delimIdx = value.lastIndexOf("-");
+ if (delimIdx > 0) {
+ for (let j = 0; j < delimIdx; j++) {
+ const cp = value.charCodeAt(j);
+ if (cp >= 128)
+ ThrowDontCare();
+ output.push(cp);
+ }
+ }
+ let inIdx = delimIdx < 0 ? 0 : delimIdx + 1;
+ while (inIdx < value.length) {
+ const oldi = i;
+ let w = 1;
+ let k = PUNYCODE_BASE;
+ while (true) {
+ if (inIdx >= value.length)
+ ThrowDontCare();
+ const ch = value.charCodeAt(inIdx++);
+ let digit;
+ if (ch >= 97 && ch <= 122)
+ digit = ch - 97;
+ else if (ch >= 48 && ch <= 57)
+ digit = ch - 48 + 26;
+ else
+ ThrowDontCare();
+ i += digit * w;
+ const t = k <= bias ? PUNYCODE_TMIN : k >= bias + PUNYCODE_TMAX ? PUNYCODE_TMAX : k - bias;
+ if (digit < t)
+ break;
+ w *= PUNYCODE_BASE - t;
+ k += PUNYCODE_BASE;
+ }
+ const outLen = output.length + 1;
+ bias = Adapt(i - oldi, outLen, oldi === 0);
+ n += Math.floor(i / outLen);
+ i %= outLen;
+ output.splice(i, 0, n);
+ i++;
+ }
+ return String.fromCodePoint(...output);
+}
+function DigitToChar(digit) {
+ return digit < 26 ? String.fromCharCode(digit + 97) : String.fromCharCode(digit - 26 + 48);
+}
+var RE_REPLACE_NON_ASCII = new RegExp(RE_NON_ASCII.source, "gu");
+function Encode(input) {
+ const basic = input.replace(RE_REPLACE_NON_ASCII, "");
+ const basicLength = basic.length;
+ const result = basicLength > 0 ? [basic, "-"] : [];
+ const codePoints = Array.from(input, (char) => char.codePointAt(0));
+ let n = PUNYCODE_INITIAL_N;
+ let delta = 0;
+ let bias = PUNYCODE_INITIAL_BIAS;
+ let handledCPCount = basicLength;
+ while (handledCPCount < codePoints.length) {
+ let m = Infinity;
+ for (const cp of codePoints) {
+ if (cp >= n && cp < m)
+ m = cp;
+ }
+ delta += (m - n) * (handledCPCount + 1);
+ n = m;
+ for (const cp of codePoints) {
+ if (cp < n)
+ delta++;
+ if (cp === n) {
+ let q = delta;
+ for (let k = PUNYCODE_BASE; ; k += PUNYCODE_BASE) {
+ const t = k <= bias ? PUNYCODE_TMIN : k >= bias + PUNYCODE_TMAX ? PUNYCODE_TMAX : k - bias;
+ if (q < t)
+ break;
+ const digit = t + (q - t) % (PUNYCODE_BASE - t);
+ result.push(DigitToChar(digit));
+ q = Math.floor((q - t) / (PUNYCODE_BASE - t));
+ }
+ result.push(DigitToChar(q));
+ bias = Adapt(delta, handledCPCount + 1, handledCPCount === basicLength);
+ delta = 0;
+ handledCPCount++;
+ }
+ }
+ delta++;
+ n++;
+ }
+ return result.join("");
+}
+
+// node_modules/typebox/build/format/idna/format/bidi.mjs
+var RE_RTL_ALLOWED = /^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/;
+var RE_LTR_ALLOWED = /^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/;
+var RE_RTL_CLASSES = /^(?:R|AL|AN)$/;
+function HasBidiChars(value) {
+ if (IsAcePrefixed(value)) {
+ try {
+ return HasRightToLeftCharacters(Decode(value.slice(4).toLowerCase()));
+ } catch {
+ return false;
+ }
+ }
+ return HasRightToLeftCharacters(value);
+}
+function GetBidiClass(codePoint) {
+ const char = String.fromCodePoint(codePoint);
+ return RE_EUROPEAN_NUMBER.test(char) ? "EN" : RE_ARABIC_INDIC_DIGIT.test(char) ? "AN" : (
+ // Pattern.RE_EUROPEAN_SEPARATOR.test(char) ? 'ES' : // (no-spec-coverage)
+ // Pattern.RE_COMMON_SEPARATOR.test(char) ? 'CS' : // (no-spec-coverage)
+ RE_MARK_NONSPACING.test(char) ? "NSM" : RE_SCRIPT_HEBREW.test(char) ? "R" : RE_SCRIPT_ARABIC_LETTER.test(char) ? "AL" : RE_LETTER.test(char) ? "L" : "ON"
+ );
+}
+function HasRightToLeftCharacters(value) {
+ for (const ch of value)
+ if (RE_RTL_CLASSES.test(GetBidiClass(ch.codePointAt(0))))
+ return true;
+ return false;
+}
+function SatisfiesBidiRule(value) {
+ let isRtl = false;
+ let allowed = RE_LTR_ALLOWED;
+ let sawEN = false;
+ let sawAN = false;
+ let isFirst = true;
+ for (const ch of value) {
+ const bidiClass = GetBidiClass(ch.codePointAt(0));
+ if (isFirst) {
+ if (bidiClass !== "L" && bidiClass !== "R" && bidiClass !== "AL")
+ return false;
+ isRtl = bidiClass === "R" || bidiClass === "AL";
+ allowed = isRtl ? RE_RTL_ALLOWED : RE_LTR_ALLOWED;
+ isFirst = false;
+ }
+ if (!allowed.test(bidiClass))
+ return false;
+ if (bidiClass === "EN")
+ sawEN = true;
+ else if (bidiClass === "AN")
+ sawAN = true;
+ }
+ if (isRtl && sawEN && sawAN)
+ return false;
+ return true;
+}
+
+// node_modules/typebox/build/format/idna/label/unicode.mjs
+function ExceedsMaxALabelLength(value) {
+ return RE_NON_ASCII.test(value) && Encode(value).length + 4 > 63;
+}
+function HasInvalidHyphens(chars) {
+ if (chars[0] === "-" || chars[chars.length - 1] === "-")
+ return true;
+ return chars.slice(2).join("").startsWith("--");
+}
+function IsUnicodeLabel(value) {
+ if (ExceedsMaxALabelLength(value))
+ return false;
+ if (HasRightToLeftCharacters(value) && !SatisfiesBidiRule(value))
+ return false;
+ const chars = [...value];
+ const codePoints = chars.map((c) => c.codePointAt(0));
+ const length = codePoints.length;
+ if (HasInvalidHyphens(chars))
+ return false;
+ if (RE_COMBINING_MARK.test(chars[0]))
+ return false;
+ let hasJapanese = false;
+ for (let i = 0; i < length; i++) {
+ const codePoint = codePoints[i];
+ const char = chars[i];
+ if (RE_RFC5892_DISALLOWED.test(char))
+ return false;
+ if (!RE_PERMITTED_CATEGORY.test(char))
+ return false;
+ if (RE_SCRIPT_JAPANESE.test(char))
+ hasJapanese = true;
+ const prev = codePoints[i - 1], next = codePoints[i + 1];
+ switch (codePoint) {
+ case 183:
+ if (prev !== 108 || next !== 108)
+ return false;
+ break;
+ // MIDDLE DOT (Catalan)
+ case 885:
+ if (!next || !RE_SCRIPT_GREEK.test(chars[i + 1]))
+ return false;
+ break;
+ // Greek KERAIA
+ case 1523:
+ case 1524:
+ if (!prev || !RE_SCRIPT_HEBREW.test(chars[i - 1]))
+ return false;
+ break;
+ // Hebrew GERESH
+ case 8204:
+ if (!prev || prev < 128 && !RE_VIRAMA.test(chars[i - 1]))
+ return false;
+ break;
+ case 8205:
+ if (!prev || !RE_VIRAMA.test(chars[i - 1]))
+ return false;
+ break;
+ case 12539:
+ break;
+ }
+ }
+ if (value.includes("\u30FB") && !hasJapanese)
+ return false;
+ return true;
+}
+
+// node_modules/typebox/build/format/idna/label/puny.mjs
+function IsPunyLabel(value) {
+ if (!IsAcePrefixed(value))
+ return false;
+ try {
+ const body = value.slice(4).toLowerCase();
+ if (body.lastIndexOf("-") === 0)
+ return false;
+ const decoded = Decode(body);
+ if (!RE_NON_ASCII.test(decoded))
+ return false;
+ return IsUnicodeLabel(decoded);
+ } catch {
+ return false;
+ }
+}
+
+// node_modules/typebox/build/format/idna/hostname.mjs
+function IsValidLabelLength(value) {
+ return value.length > 0 && value.length <= 63;
+}
+function IsLabel(value) {
+ return IsValidLabelLength(value) && (IsPunyLabel(value) || IsAsciiLabel(value));
+}
+function IsHostname(value) {
+ if (value.length === 0 || value.length > 253)
+ return false;
+ if (value.charCodeAt(value.length - 1) === 46)
+ return false;
+ return value.split(".").every((label) => IsLabel(label));
+}
+
+// node_modules/typebox/build/format/idna/idn-hostname.mjs
+function IsValidLabelLength2(value) {
+ return value.length > 0 && value.length <= 63;
+}
+function IsLabel2(value) {
+ return IsValidLabelLength2(value) && (IsPunyLabel(value) || IsUnicodeLabel(value));
+}
+function NormalizeHostname(value) {
+ return value.replace(/[\uff01-\uff5e]/g, (char) => String.fromCharCode(char.charCodeAt(0) - 65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu, "").replace(/[\u002E\u3002\uFF0E\uFF61]/g, ".");
+}
+function IsIdnHostname(value) {
+ if (value.length === 0 || value.includes(" "))
+ return false;
+ const normalized = NormalizeHostname(value);
+ if (normalized.length > 253)
+ return false;
+ const labels = normalized.split(".");
+ const hasBidiChars = labels.some((label) => HasBidiChars(label));
+ return labels.every((label) => IsLabel2(label) && (!hasBidiChars || SatisfiesBidiRule(label)));
+}
+
+// node_modules/typebox/build/format/hostname.mjs
+function IsHostname2(value) {
+ return IsHostname(value);
+}
+
+// node_modules/typebox/build/format/idn_email.mjs
+var IdnEmail = /^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?\^`{|}\\]/;
+var InvalidPercentEncoding = /%(?![0-9a-fA-F]{2})/;
+function NarrowIpvFuture(value) {
+ return value.length < IpvFutureMatchMaxLength ? value.replace(IpvFutureMatch, "[::1]") : value;
+}
+function IsIri(value) {
+ if (InvalidIriChars2.test(value))
+ return false;
+ if (InvalidPercentEncoding.test(value))
+ return false;
+ return URL.canParse(NarrowIpvFuture(value));
+}
+
+// node_modules/typebox/build/format/json_pointer_uri_fragment.mjs
+var JsonPointerUriFragment = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
+function IsJsonPointerUriFragment(value) {
+ return JsonPointerUriFragment.test(value);
+}
+
+// node_modules/typebox/build/format/json_pointer.mjs
+var JsonPointer = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
+function IsJsonPointer(value) {
+ return JsonPointer.test(value);
+}
+
+// node_modules/typebox/build/format/regex.mjs
+function IsRegex(value) {
+ try {
+ new RegExp(value, "u");
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// node_modules/typebox/build/format/relative_json_pointer.mjs
+var RelativeJsonPointer = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
+function IsRelativeJsonPointer(value) {
+ return RelativeJsonPointer.test(value);
+}
+
+// node_modules/typebox/build/format/uri_reference.mjs
+var UriReference = /^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
+function IsUriReference(value) {
+ return UriReference.test(value);
+}
+
+// node_modules/typebox/build/format/uri_template.mjs
+var UriTemplate = /^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;
+function IsUriTemplate(value) {
+ return UriTemplate.test(value);
+}
+
+// node_modules/typebox/build/format/uri.mjs
+var Uri = /^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
+function IsUri(value) {
+ return Uri.test(value);
+}
+
+// node_modules/typebox/build/format/url.mjs
+function IsUrl(value) {
+ return URL.canParse(value);
+}
+
+// node_modules/typebox/build/format/uuid.mjs
+var Uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
+function IsUuid(value) {
+ return Uuid.test(value);
+}
+
+// node_modules/typebox/build/format/_registry.mjs
+var formats = /* @__PURE__ */ new Map();
+function Clear() {
+ formats.clear();
+}
+function Entries3() {
+ return [...formats.entries()];
+}
+function Set3(format, check) {
+ formats.set(format, check);
+}
+function Has(format) {
+ return formats.has(format);
+}
+function Get2(format) {
+ return formats.get(format);
+}
+function Test(format, value) {
+ return formats.get(format)?.(value) ?? true;
+}
+function Reset2() {
+ Clear();
+ formats.set("date-time", IsDateTime);
+ formats.set("date", IsDate2);
+ formats.set("duration", IsDuration);
+ formats.set("email", IsEmail);
+ formats.set("hostname", IsHostname2);
+ formats.set("idn-email", IsIdnEmail);
+ formats.set("idn-hostname", IsIdnHostname2);
+ formats.set("ipv4", IsIPv4);
+ formats.set("ipv6", IsIPv6);
+ formats.set("iri-reference", IsIriReference);
+ formats.set("iri", IsIri);
+ formats.set("json-pointer-uri-fragment", IsJsonPointerUriFragment);
+ formats.set("json-pointer", IsJsonPointer);
+ formats.set("regex", IsRegex);
+ formats.set("relative-json-pointer", IsRelativeJsonPointer);
+ formats.set("time", IsTime);
+ formats.set("uri-reference", IsUriReference);
+ formats.set("uri-template", IsUriTemplate);
+ formats.set("uri", IsUri);
+ formats.set("url", IsUrl);
+ formats.set("uuid", IsUuid);
+}
+Reset2();
+
+// node_modules/typebox/build/schema/engine/format.mjs
+function BuildFormat(_stack, _context, schema, value) {
+ return emit_exports.Call(emit_exports.Member("Format", "Test"), [emit_exports.Constant(schema.format), value]);
+}
+function CheckFormat(_stack, _context, schema, value) {
+ return format_exports.Test(schema.format, value);
+}
+function ErrorFormat(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckFormat(stack, context, schema, value) || context.AddError({
+ keyword: "format",
+ schemaPath,
+ instancePath,
+ params: { format: schema.format }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/if.mjs
+function BuildIf(stack, context, schema, value) {
+ const thenSchema = IsThen(schema) ? schema.then : true;
+ const elseSchema = IsElse(schema) ? schema.else : true;
+ return emit_exports.Ternary(BuildSchema(stack, context, schema.if, value), BuildSchema(stack, context, thenSchema, value), BuildSchema(stack, context, elseSchema, value));
+}
+function CheckIf(stack, context, schema, value) {
+ const thenSchema = IsThen(schema) ? schema.then : true;
+ const elseSchema = IsElse(schema) ? schema.else : true;
+ return CheckSchema(stack, context, schema.if, value) ? CheckSchema(stack, context, thenSchema, value) : CheckSchema(stack, context, elseSchema, value);
+}
+function ErrorIf(stack, context, schemaPath, instancePath, schema, value) {
+ const thenSchema = IsThen(schema) ? schema.then : true;
+ const elseSchema = IsElse(schema) ? schema.else : true;
+ const trueContext = new ErrorContext();
+ const isIf = ErrorSchema(stack, trueContext, `${schemaPath}/if`, instancePath, schema.if, value) ? ErrorSchema(stack, trueContext, `${schemaPath}/then`, instancePath, thenSchema, value) || context.AddError({
+ keyword: "if",
+ schemaPath,
+ instancePath,
+ params: { failingKeyword: "then" }
+ }) : ErrorSchema(stack, context, `${schemaPath}/else`, instancePath, elseSchema, value) || context.AddError({
+ keyword: "if",
+ schemaPath,
+ instancePath,
+ params: { failingKeyword: "else" }
+ });
+ if (isIf)
+ context.Merge([trueContext]);
+ return isIf;
+}
+
+// node_modules/typebox/build/schema/engine/items.mjs
+function BuildItemsSizedStandard(stack, context, schema, value) {
+ return emit_exports.ReduceAnd(schema.items.map((schema2, index3) => {
+ const isLength = emit_exports.IsLessEqualThan(emit_exports.Member(value, "length"), emit_exports.Constant(index3));
+ const isSchema = BuildSchemaPushStack(stack, context, schema2, `${value}[${index3}]`);
+ const addIndex = context.AddIndex(emit_exports.Constant(index3));
+ return emit_exports.Or(isLength, emit_exports.And(isSchema, addIndex));
+ }));
+}
+function BuildItemsSizedFast(stack, context, schema, value) {
+ return emit_exports.ReduceAnd(schema.items.map((schema2, index3) => {
+ const isLength = emit_exports.IsLessEqualThan(emit_exports.Member(value, "length"), emit_exports.Constant(index3));
+ const isSchema = BuildSchemaPushStack(stack, context, schema2, `${value}[${index3}]`);
+ return emit_exports.Or(isLength, isSchema);
+ }));
+}
+function BuildItemsSized(stack, context, schema, value) {
+ return context.UseUnevaluated() ? BuildItemsSizedStandard(stack, context, schema, value) : BuildItemsSizedFast(stack, context, schema, value);
+}
+function CheckItemsSized(stack, context, schema, value) {
+ return guard_exports.Every(schema.items, 0, (schema2, index3) => {
+ return guard_exports.IsLessEqualThan(value.length, index3) || CheckSchemaPushStack(stack, context, schema2, value[index3]) && context.AddIndex(index3);
+ });
+}
+function ErrorItemsSized(stack, context, schemaPath, instancePath, schema, value) {
+ return guard_exports.EveryAll(schema.items, 0, (schema2, index3) => {
+ const nextSchemaPath = `${schemaPath}/items/${index3}`;
+ const nextInstancePath = `${instancePath}/${index3}`;
+ return guard_exports.IsLessEqualThan(value.length, index3) || ErrorSchemaPushStack(stack, context, nextSchemaPath, nextInstancePath, schema2, value[index3]) && context.AddIndex(index3);
+ });
+}
+function BuildItemsUnsizedStandard(stack, context, schema, value) {
+ const offset = IsPrefixItems(schema) ? schema.prefixItems.length : 0;
+ const isSchema = BuildSchemaPushStack(stack, context, schema.items, "element");
+ const addIndex = context.AddIndex("index");
+ return emit_exports.Every(value, emit_exports.Constant(offset), ["element", "index"], emit_exports.And(isSchema, addIndex));
+}
+function BuildItemsUnsizedFast(stack, context, schema, value) {
+ const offset = IsPrefixItems(schema) ? schema.prefixItems.length : 0;
+ const isSchema = BuildSchemaPushStack(stack, context, schema.items, "element");
+ return emit_exports.Every(value, emit_exports.Constant(offset), ["element", "index"], isSchema);
+}
+function BuildItemsUnsized(stack, context, schema, value) {
+ return context.UseUnevaluated() ? BuildItemsUnsizedStandard(stack, context, schema, value) : BuildItemsUnsizedFast(stack, context, schema, value);
+}
+function CheckItemsUnsized(stack, context, schema, value) {
+ const offset = IsPrefixItems(schema) ? schema.prefixItems.length : 0;
+ return guard_exports.Every(value, offset, (element, index3) => {
+ return CheckSchemaPushStack(stack, context, schema.items, element) && context.AddIndex(index3);
+ });
+}
+function ErrorItemsUnsized(stack, context, schemaPath, instancePath, schema, value) {
+ const offset = IsPrefixItems(schema) ? schema.prefixItems.length : 0;
+ return guard_exports.EveryAll(value, offset, (element, index3) => {
+ const nextSchemaPath = `${schemaPath}/items`;
+ const nextInstancePath = `${instancePath}/${index3}`;
+ return ErrorSchemaPushStack(stack, context, nextSchemaPath, nextInstancePath, schema.items, element) && context.AddIndex(index3);
+ });
+}
+function BuildItems(stack, context, schema, value) {
+ return IsItemsSized(schema) ? BuildItemsSized(stack, context, schema, value) : BuildItemsUnsized(stack, context, schema, value);
+}
+function CheckItems(stack, context, schema, value) {
+ return IsItemsSized(schema) ? CheckItemsSized(stack, context, schema, value) : CheckItemsUnsized(stack, context, schema, value);
+}
+function ErrorItems(stack, context, schemaPath, instancePath, schema, value) {
+ return IsItemsSized(schema) ? ErrorItemsSized(stack, context, schemaPath, instancePath, schema, value) : ErrorItemsUnsized(stack, context, schemaPath, instancePath, schema, value);
+}
+
+// node_modules/typebox/build/schema/engine/maxContains.mjs
+function IsValid3(schema) {
+ return IsContains(schema);
+}
+function BuildMaxContains(stack, context, schema, value) {
+ if (!IsValid3(schema))
+ return emit_exports.Constant(true);
+ const [item] = [Unique()];
+ const count = emit_exports.Counted(value, [item, "_"], BuildSchema(stack, context, schema.contains, item));
+ return emit_exports.IsLessEqualThan(count, emit_exports.Constant(schema.maxContains));
+}
+function CheckMaxContains(stack, context, schema, value) {
+ if (!IsValid3(schema))
+ return true;
+ const count = guard_exports.Counted(value, (item) => CheckSchema(stack, context, schema.contains, item));
+ return guard_exports.IsLessEqualThan(count, schema.maxContains);
+}
+function ErrorMaxContains(stack, context, schemaPath, instancePath, schema, value) {
+ const minContains = IsMinContains(schema) ? schema.minContains : 1;
+ return CheckMaxContains(stack, context, schema, value) || context.AddError({
+ keyword: "contains",
+ schemaPath,
+ instancePath,
+ params: { minContains, maxContains: schema.maxContains }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/maximum.mjs
+function BuildMaximum(_stack, _context, schema, value) {
+ return emit_exports.IsLessEqualThan(value, emit_exports.Constant(schema.maximum));
+}
+function CheckMaximum(_stack, _context, schema, value) {
+ return guard_exports.IsLessEqualThan(value, schema.maximum);
+}
+function ErrorMaximum(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMaximum(stack, context, schema, value) || context.AddError({
+ keyword: "maximum",
+ schemaPath,
+ instancePath,
+ params: { comparison: "<=", limit: schema.maximum }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/maxItems.mjs
+function BuildMaxItems(_stack, _context, schema, value) {
+ return emit_exports.IsLessEqualThan(emit_exports.Member(value, "length"), emit_exports.Constant(schema.maxItems));
+}
+function CheckMaxItems(_stack, _context, schema, value) {
+ return guard_exports.IsLessEqualThan(value.length, schema.maxItems);
+}
+function ErrorMaxItems(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMaxItems(stack, context, schema, value) || context.AddError({
+ keyword: "maxItems",
+ schemaPath,
+ instancePath,
+ params: { limit: schema.maxItems }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/maxLength.mjs
+function BuildMaxLength(_stack, _context, schema, value) {
+ return emit_exports.IsMaxLength(value, emit_exports.Constant(schema.maxLength));
+}
+function CheckMaxLength(_stack, _context, schema, value) {
+ return guard_exports.IsMaxLength(value, schema.maxLength);
+}
+function ErrorMaxLength(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMaxLength(stack, context, schema, value) || context.AddError({
+ keyword: "maxLength",
+ schemaPath,
+ instancePath,
+ params: { limit: schema.maxLength }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/maxProperties.mjs
+function BuildMaxProperties(_stack, _context, schema, value) {
+ return emit_exports.IsLessEqualThan(emit_exports.Member(emit_exports.Keys(value), "length"), emit_exports.Constant(schema.maxProperties));
+}
+function CheckMaxProperties(_stack, _context, schema, value) {
+ return guard_exports.IsLessEqualThan(guard_exports.Keys(value).length, schema.maxProperties);
+}
+function ErrorMaxProperties(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMaxProperties(stack, context, schema, value) || context.AddError({
+ keyword: "maxProperties",
+ schemaPath,
+ instancePath,
+ params: { limit: schema.maxProperties }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/minContains.mjs
+function IsValid4(schema) {
+ return IsContains(schema);
+}
+function BuildMinContainsStandard(stack, context, schema, value) {
+ const [item, index3] = [Unique(), Unique()];
+ const count = emit_exports.Counted(value, [item, index3], emit_exports.And(BuildSchema(stack, context, schema.contains, item), context.AddIndex(index3)));
+ return emit_exports.IsGreaterEqualThan(count, emit_exports.Constant(schema.minContains));
+}
+function BuildMinContainsFast(stack, context, schema, value) {
+ const [item] = [Unique()];
+ const count = emit_exports.Counted(value, [item, "_"], BuildSchema(stack, context, schema.contains, item));
+ return emit_exports.IsGreaterEqualThan(count, emit_exports.Constant(schema.minContains));
+}
+function BuildMinContains(stack, context, schema, value) {
+ if (!IsValid4(schema))
+ return emit_exports.Constant(true);
+ return context.UseUnevaluated() ? BuildMinContainsStandard(stack, context, schema, value) : BuildMinContainsFast(stack, context, schema, value);
+}
+function CheckMinContains(stack, context, schema, value) {
+ if (!IsValid4(schema))
+ return true;
+ const count = guard_exports.Counted(value, (item, index3) => CheckSchema(stack, context, schema.contains, item) && context.AddIndex(index3));
+ return guard_exports.IsGreaterEqualThan(count, schema.minContains);
+}
+function ErrorMinContains(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMinContains(stack, context, schema, value) || context.AddError({
+ keyword: "contains",
+ schemaPath,
+ instancePath,
+ params: { minContains: schema.minContains }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/minimum.mjs
+function BuildMinimum(_stack, _context, schema, value) {
+ return emit_exports.IsGreaterEqualThan(value, emit_exports.Constant(schema.minimum));
+}
+function CheckMinimum(_stack, _context, schema, value) {
+ return guard_exports.IsGreaterEqualThan(value, schema.minimum);
+}
+function ErrorMinimum(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMinimum(stack, context, schema, value) || context.AddError({
+ keyword: "minimum",
+ schemaPath,
+ instancePath,
+ params: { comparison: ">=", limit: schema.minimum }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/minItems.mjs
+function BuildMinItems(_stack, _context, schema, value) {
+ return emit_exports.IsGreaterEqualThan(emit_exports.Member(value, "length"), emit_exports.Constant(schema.minItems));
+}
+function CheckMinItems(_stack, _context, schema, value) {
+ return guard_exports.IsGreaterEqualThan(value.length, schema.minItems);
+}
+function ErrorMinItems(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMinItems(stack, context, schema, value) || context.AddError({
+ keyword: "minItems",
+ schemaPath,
+ instancePath,
+ params: { limit: schema.minItems }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/minLength.mjs
+function BuildMinLength(_stack, _context, schema, value) {
+ return emit_exports.IsMinLength(value, emit_exports.Constant(schema.minLength));
+}
+function CheckMinLength(_stack, _context, schema, value) {
+ return guard_exports.IsMinLength(value, schema.minLength);
+}
+function ErrorMinLength(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMinLength(stack, context, schema, value) || context.AddError({
+ keyword: "minLength",
+ schemaPath,
+ instancePath,
+ params: { limit: schema.minLength }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/minProperties.mjs
+function BuildMinProperties(_stack, _context, schema, value) {
+ return emit_exports.IsGreaterEqualThan(emit_exports.Member(emit_exports.Keys(value), "length"), emit_exports.Constant(schema.minProperties));
+}
+function CheckMinProperties(_stack, _context, schema, value) {
+ return guard_exports.IsGreaterEqualThan(guard_exports.Keys(value).length, schema.minProperties);
+}
+function ErrorMinProperties(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMinProperties(stack, context, schema, value) || context.AddError({
+ keyword: "minProperties",
+ schemaPath,
+ instancePath,
+ params: { limit: schema.minProperties }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/multipleOf.mjs
+function BuildMultipleOf(_stack, _context, schema, value) {
+ return emit_exports.MultipleOf(value, emit_exports.Constant(schema.multipleOf));
+}
+function CheckMultipleOf(_stack, _context, schema, value) {
+ return guard_exports.IsMultipleOf(value, schema.multipleOf);
+}
+function ErrorMultipleOf(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckMultipleOf(stack, context, schema, value) || context.AddError({
+ keyword: "multipleOf",
+ schemaPath,
+ instancePath,
+ params: { multipleOf: schema.multipleOf }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/not.mjs
+function BuildNotStandard(stack, context, schema, value) {
+ return Reducer(stack, context, [schema.not], value, emit_exports.Not(emit_exports.IsEqual(emit_exports.Member("results", "length"), emit_exports.Constant(1))));
+}
+function BuildNotFast(stack, context, schema, value) {
+ return emit_exports.Not(BuildSchema(stack, context, schema.not, value));
+}
+function BuildNot(stack, context, schema, value) {
+ return context.UseUnevaluated() ? BuildNotStandard(stack, context, schema, value) : BuildNotFast(stack, context, schema, value);
+}
+function CheckNot(stack, context, schema, value) {
+ const nextContext = new CheckContext();
+ const isSchema = !CheckSchema(stack, nextContext, schema.not, value);
+ const isNot = isSchema && context.Merge([nextContext]);
+ return isNot;
+}
+function ErrorNot(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckNot(stack, context, schema, value) || context.AddError({
+ keyword: "not",
+ schemaPath,
+ instancePath,
+ params: {}
+ });
+}
+
+// node_modules/typebox/build/schema/engine/oneOf.mjs
+function BuildOneOfStandard(stack, context, schema, value) {
+ return Reducer(stack, context, schema.oneOf, value, emit_exports.IsEqual(emit_exports.Member("results", "length"), emit_exports.Constant(1)));
+}
+function BuildOneOfFast(stack, context, schema, value) {
+ const [result] = [Unique()];
+ const results = emit_exports.ArrayLiteral(schema.oneOf.map((schema2) => BuildSchema(stack, context, schema2, value)));
+ const count = emit_exports.Counted(results, [result, "_"], emit_exports.IsEqual(result, emit_exports.Constant(true)));
+ return emit_exports.IsEqual(count, emit_exports.Constant(1));
+}
+function BuildOneOf(stack, context, schema, value) {
+ return context.UseUnevaluated() ? BuildOneOfStandard(stack, context, schema, value) : BuildOneOfFast(stack, context, schema, value);
+}
+function CheckOneOf(stack, context, schema, value) {
+ const passedContexts = schema.oneOf.reduce((result, schema2) => {
+ const nextContext = new CheckContext();
+ return CheckSchema(stack, nextContext, schema2, value) ? [...result, nextContext] : result;
+ }, []);
+ return guard_exports.IsEqual(passedContexts.length, 1) && context.Merge(passedContexts);
+}
+function ErrorOneOf(stack, context, schemaPath, instancePath, schema, value) {
+ const failedContexts = [];
+ const passingSchemas = [];
+ const passedContexts = schema.oneOf.reduce((result, schema2, index3) => {
+ const nextContext = new ErrorContext();
+ const nextSchemaPath = `${schemaPath}/oneOf/${index3}`;
+ const isSchema = ErrorSchema(stack, nextContext, nextSchemaPath, instancePath, schema2, value);
+ if (isSchema)
+ passingSchemas.push(index3);
+ if (!isSchema)
+ failedContexts.push(nextContext);
+ return isSchema ? [...result, nextContext] : result;
+ }, []);
+ const isOneOf = guard_exports.IsEqual(passedContexts.length, 1) && context.Merge(passedContexts);
+ if (!isOneOf && guard_exports.IsEqual(passingSchemas.length, 0))
+ failedContexts.forEach((failed) => failed.GetErrors().forEach((error) => context.AddError(error)));
+ return isOneOf || context.AddError({
+ keyword: "oneOf",
+ schemaPath,
+ instancePath,
+ params: { passingSchemas }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/pattern.mjs
+function BuildPattern(_stack, _context, schema, value) {
+ const regexp = CreateVariable(guard_exports.IsString(schema.pattern) ? UnicodeRegExp(schema.pattern) : schema.pattern);
+ return emit_exports.Call(emit_exports.Member(regexp, "test"), [value]);
+}
+function CheckPattern(_stack, _context, schema, value) {
+ const regexp = guard_exports.IsString(schema.pattern) ? UnicodeRegExp(schema.pattern) : schema.pattern;
+ return regexp.test(value);
+}
+function ErrorPattern(stack, context, schemaPath, instancePath, schema, value) {
+ return CheckPattern(stack, context, schema, value) || context.AddError({
+ keyword: "pattern",
+ schemaPath,
+ instancePath,
+ params: { pattern: schema.pattern }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/patternProperties.mjs
+function BuildPatternProperties(stack, context, schema, value) {
+ return emit_exports.ReduceAnd(guard_exports.Entries(schema.patternProperties).map(([pattern, schema2]) => {
+ const [key, prop] = [Unique(), Unique()];
+ const regexp = CreateVariable(UnicodeRegExp(pattern));
+ const notKey = emit_exports.Not(emit_exports.Call(emit_exports.Member(regexp, "test"), [key]));
+ const isSchema = BuildSchemaPushStack(stack, context, schema2, prop);
+ const addKey = context.AddKey(key);
+ const guarded = context.UseUnevaluated() ? emit_exports.Or(notKey, emit_exports.And(isSchema, addKey)) : emit_exports.Or(notKey, isSchema);
+ return emit_exports.Every(emit_exports.Entries(value), emit_exports.Constant(0), [`[${key}, ${prop}]`, "_"], guarded);
+ }));
+}
+function CheckPatternProperties(stack, context, schema, value) {
+ return guard_exports.Every(guard_exports.Entries(schema.patternProperties), 0, ([pattern, schema2]) => {
+ const regexp = UnicodeRegExp(pattern);
+ return guard_exports.Every(guard_exports.Entries(value), 0, ([key, prop]) => {
+ return !regexp.test(key) || CheckSchemaPushStack(stack, context, schema2, prop) && context.AddKey(key);
+ });
+ });
+}
+function ErrorPatternProperties(stack, context, schemaPath, instancePath, schema, value) {
+ return guard_exports.EveryAll(guard_exports.Entries(schema.patternProperties), 0, ([pattern, schema2]) => {
+ const nextSchemaPath = `${schemaPath}/patternProperties/${pattern}`;
+ const regexp = UnicodeRegExp(pattern);
+ return guard_exports.EveryAll(guard_exports.Entries(value), 0, ([key, value2]) => {
+ const nextInstancePath = `${instancePath}/${key}`;
+ const notKey = !regexp.test(key);
+ return notKey || ErrorSchemaPushStack(stack, context, nextSchemaPath, nextInstancePath, schema2, value2) && context.AddKey(key);
+ });
+ });
+}
+
+// node_modules/typebox/build/schema/engine/prefixItems.mjs
+function BuildPrefixItems(stack, context, schema, value) {
+ return emit_exports.ReduceAnd(schema.prefixItems.map((schema2, index3) => {
+ const isLength = emit_exports.IsLessEqualThan(emit_exports.Member(value, "length"), emit_exports.Constant(index3));
+ const isSchema = BuildSchemaPushStack(stack, context, schema2, `${value}[${index3}]`);
+ const addIndex = context.AddIndex(emit_exports.Constant(index3));
+ const guarded = context.UseUnevaluated() ? emit_exports.And(isSchema, addIndex) : isSchema;
+ return emit_exports.Or(isLength, guarded);
+ }));
+}
+function CheckPrefixItems(stack, context, schema, value) {
+ return guard_exports.IsEqual(value.length, 0) || guard_exports.Every(schema.prefixItems, 0, (schema2, index3) => {
+ return guard_exports.IsLessEqualThan(value.length, index3) || CheckSchemaPushStack(stack, context, schema2, value[index3]) && context.AddIndex(index3);
+ });
+}
+function ErrorPrefixItems(stack, context, schemaPath, instancePath, schema, value) {
+ return guard_exports.IsEqual(value.length, 0) || guard_exports.EveryAll(schema.prefixItems, 0, (schema2, index3) => {
+ const nextSchemaPath = `${schemaPath}/prefixItems/${index3}`;
+ const nextInstancePath = `${instancePath}/${index3}`;
+ return guard_exports.IsLessEqualThan(value.length, index3) || ErrorSchemaPushStack(stack, context, nextSchemaPath, nextInstancePath, schema2, value[index3]) && context.AddIndex(index3);
+ });
+}
+
+// node_modules/typebox/build/schema/engine/_exact_optional.mjs
+function IsExactOptional(required, key) {
+ return required.includes(key) || settings_exports.Get().exactOptionalPropertyTypes;
+}
+function InexactOptionalBuild(value, key) {
+ return emit_exports.IsUndefined(emit_exports.Member(value, key));
+}
+function InexactOptionalCheck(value, key) {
+ return guard_exports.IsUndefined(value[key]);
+}
+
+// node_modules/typebox/build/schema/engine/properties.mjs
+function BuildProperties(stack, context, schema, value) {
+ const required = IsRequired(schema) ? schema.required : [];
+ const everyKey = guard_exports.Entries(schema.properties).map(([key, schema2]) => {
+ const notKey = emit_exports.Not(emit_exports.HasPropertyKey(value, emit_exports.Constant(key)));
+ const isSchema = BuildSchemaPushStack(stack, context, schema2, emit_exports.Member(value, key));
+ const addKey = context.AddKey(emit_exports.Constant(key));
+ const guarded = context.UseUnevaluated() ? emit_exports.And(isSchema, addKey) : isSchema;
+ const isProperty = required.includes(key) ? guarded : emit_exports.Or(notKey, guarded);
+ return IsExactOptional(required, key) ? isProperty : emit_exports.Or(InexactOptionalBuild(value, key), isProperty);
+ });
+ return emit_exports.ReduceAnd(everyKey);
+}
+function CheckProperties(stack, context, schema, value) {
+ const required = IsRequired(schema) ? schema.required : [];
+ const isProperties = guard_exports.Every(guard_exports.Entries(schema.properties), 0, ([key, schema2]) => {
+ const isProperty = !guard_exports.HasPropertyKey(value, key) || CheckSchemaPushStack(stack, context, schema2, value[key]) && context.AddKey(key);
+ return IsExactOptional(required, key) ? isProperty : InexactOptionalCheck(value, key) || isProperty;
+ });
+ return isProperties;
+}
+function ErrorProperties(stack, context, schemaPath, instancePath, schema, value) {
+ const required = IsRequired(schema) ? schema.required : [];
+ const isProperties = guard_exports.EveryAll(guard_exports.Entries(schema.properties), 0, ([key, schema2]) => {
+ const nextSchemaPath = `${schemaPath}/properties/${key}`;
+ const nextInstancePath = `${instancePath}/${key}`;
+ const isProperty = () => !guard_exports.HasPropertyKey(value, key) || ErrorSchemaPushStack(stack, context, nextSchemaPath, nextInstancePath, schema2, value[key]) && context.AddKey(key);
+ return IsExactOptional(required, key) ? isProperty() : InexactOptionalCheck(value, key) || isProperty();
+ });
+ return isProperties;
+}
+
+// node_modules/typebox/build/schema/engine/propertyNames.mjs
+function BuildPropertyNames(stack, context, schema, value) {
+ const [key, _index] = [Unique(), Unique()];
+ return emit_exports.Every(emit_exports.Keys(value), emit_exports.Constant(0), [key, _index], BuildSchema(stack, context, schema.propertyNames, key));
+}
+function CheckPropertyNames(stack, context, schema, value) {
+ return guard_exports.Every(guard_exports.Keys(value), 0, (key, _index) => CheckSchema(stack, context, schema.propertyNames, key));
+}
+function ErrorPropertyNames(stack, context, schemaPath, instancePath, schema, value) {
+ const propertyNames = [];
+ const isPropertyNames = guard_exports.EveryAll(guard_exports.Keys(value), 0, (key, _index) => {
+ const nextInstancePath = `${instancePath}/${key}`;
+ const nextSchemaPath = `${schemaPath}/propertyNames`;
+ const isPropertyName = ErrorSchema(stack, context, nextSchemaPath, nextInstancePath, schema.propertyNames, key);
+ if (!isPropertyName)
+ propertyNames.push(key);
+ return isPropertyName;
+ });
+ return isPropertyNames || context.AddError({
+ keyword: "propertyNames",
+ schemaPath,
+ instancePath,
+ params: { propertyNames }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/recursiveRef.mjs
+function BuildRecursiveRef(stack, context, schema, value) {
+ const target = stack.RecursiveRef(schema) ?? false;
+ return CreateFunction(stack, context, target, value);
+}
+function CheckRecursiveRef(stack, context, schema, value) {
+ const target = stack.RecursiveRef(schema) ?? false;
+ return IsSchema(target) && CheckSchema(stack, context, target, value);
+}
+function ErrorRecursiveRef(stack, context, _schemaPath, instancePath, schema, value) {
+ const target = stack.RecursiveRef(schema) ?? false;
+ return IsSchema(target) && ErrorSchema(stack, context, "#", instancePath, target, value);
+}
+
+// node_modules/typebox/build/schema/engine/ref.mjs
+function BuildRefStandard(stack, context, target, value) {
+ const interior = emit_exports.ArrowFunction(["context", "value"], CreateFunction(stack, context, target, "value"));
+ const exterior = emit_exports.ArrowFunction(["context", "value"], emit_exports.Statements([
+ emit_exports.ConstDeclaration("nextContext", emit_exports.New("CheckContext", [])),
+ emit_exports.ConstDeclaration("result", emit_exports.Call(interior, ["nextContext", "value"])),
+ emit_exports.If("result", context.Merge("[nextContext]")),
+ emit_exports.Return("result")
+ ]));
+ return emit_exports.Call(exterior, ["context", value]);
+}
+function BuildRefFast(stack, context, target, value) {
+ return CreateFunction(stack, context, target, value);
+}
+function BuildRef(stack, context, schema, value) {
+ const target = stack.Ref(schema) ?? false;
+ return context.UseUnevaluated() ? BuildRefStandard(stack, context, target, value) : BuildRefFast(stack, context, target, value);
+}
+function CheckRef(stack, context, schema, value) {
+ const target = stack.Ref(schema) ?? false;
+ const nextContext = new CheckContext();
+ const result = IsSchema(target) && CheckSchema(stack, nextContext, target, value);
+ if (result)
+ context.Merge([nextContext]);
+ return result;
+}
+function ErrorRef(stack, context, _schemaPath, instancePath, schema, value) {
+ const target = stack.Ref(schema) ?? false;
+ const nextContext = new ErrorContext();
+ const result = IsSchema(target) && ErrorSchema(stack, nextContext, "#", instancePath, target, value);
+ if (result)
+ context.Merge([nextContext]);
+ if (!result)
+ nextContext.GetErrors().forEach((error) => context.AddError(error));
+ return result;
+}
+
+// node_modules/typebox/build/schema/engine/required.mjs
+function BuildRequired(_stack, _context, schema, value) {
+ return emit_exports.ReduceAnd(schema.required.map((key) => emit_exports.HasPropertyKey(value, emit_exports.Constant(key))));
+}
+function CheckRequired(_stack, _context, schema, value) {
+ return guard_exports.Every(schema.required, 0, (key) => guard_exports.HasPropertyKey(value, key));
+}
+function ErrorRequired(_stack, context, schemaPath, instancePath, schema, value) {
+ const requiredProperties = [];
+ const isRequired = guard_exports.EveryAll(schema.required, 0, (key) => {
+ const hasKey = guard_exports.HasPropertyKey(value, key);
+ if (!hasKey)
+ requiredProperties.push(key);
+ return hasKey;
+ });
+ return isRequired || context.AddError({
+ keyword: "required",
+ schemaPath,
+ instancePath,
+ params: { requiredProperties }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/type.mjs
+function BuildTypeName(_stack, _context, type, value) {
+ return (
+ // jsonschema
+ guard_exports.IsEqual(type, "object") ? emit_exports.IsObjectNotArray(value) : guard_exports.IsEqual(type, "array") ? emit_exports.IsArray(value) : guard_exports.IsEqual(type, "boolean") ? emit_exports.IsBoolean(value) : guard_exports.IsEqual(type, "integer") ? emit_exports.IsInteger(value) : guard_exports.IsEqual(type, "number") ? emit_exports.IsNumber(value) : guard_exports.IsEqual(type, "null") ? emit_exports.IsNull(value) : guard_exports.IsEqual(type, "string") ? emit_exports.IsString(value) : (
+ // xschema
+ guard_exports.IsEqual(type, "bigint") ? emit_exports.IsBigInt(value) : guard_exports.IsEqual(type, "constructor") ? emit_exports.IsConstructor(value) : guard_exports.IsEqual(type, "function") ? emit_exports.IsFunction(value) : guard_exports.IsEqual(type, "symbol") ? emit_exports.IsSymbol(value) : guard_exports.IsEqual(type, "undefined") ? emit_exports.IsUndefined(value) : guard_exports.IsEqual(type, "void") ? emit_exports.IsUndefined(value) : emit_exports.Constant(true)
+ )
+ );
+}
+function CheckTypeName(_stack, _context, type, _schema, value) {
+ return (
+ // jsonschema
+ guard_exports.IsEqual(type, "object") ? guard_exports.IsObjectNotArray(value) : guard_exports.IsEqual(type, "array") ? guard_exports.IsArray(value) : guard_exports.IsEqual(type, "boolean") ? guard_exports.IsBoolean(value) : guard_exports.IsEqual(type, "integer") ? guard_exports.IsInteger(value) : guard_exports.IsEqual(type, "number") ? guard_exports.IsNumber(value) : guard_exports.IsEqual(type, "null") ? guard_exports.IsNull(value) : guard_exports.IsEqual(type, "string") ? guard_exports.IsString(value) : (
+ // xschema
+ guard_exports.IsEqual(type, "bigint") ? guard_exports.IsBigInt(value) : guard_exports.IsEqual(type, "constructor") ? guard_exports.IsConstructor(value) : guard_exports.IsEqual(type, "function") ? guard_exports.IsFunction(value) : guard_exports.IsEqual(type, "symbol") ? guard_exports.IsSymbol(value) : guard_exports.IsEqual(type, "undefined") ? guard_exports.IsUndefined(value) : guard_exports.IsEqual(type, "void") ? guard_exports.IsUndefined(value) : true
+ )
+ );
+}
+function BuildTypeNames(stack, context, typenames, value) {
+ return emit_exports.ReduceOr(typenames.map((type) => BuildTypeName(stack, context, type, value)));
+}
+function CheckTypeNames(stack, context, types, schema, value) {
+ return guard_exports.Some(types, (type) => CheckTypeName(stack, context, type, schema, value));
+}
+function BuildType(stack, context, schema, value) {
+ return guard_exports.IsArray(schema.type) ? BuildTypeNames(stack, context, schema.type, value) : BuildTypeName(stack, context, schema.type, value);
+}
+function CheckType(stack, context, schema, value) {
+ return guard_exports.IsArray(schema.type) ? CheckTypeNames(stack, context, schema.type, schema, value) : CheckTypeName(stack, context, schema.type, schema, value);
+}
+function ErrorType(stack, context, schemaPath, instancePath, schema, value) {
+ const isType = guard_exports.IsArray(schema.type) ? CheckTypeNames(stack, context, schema.type, schema, value) : CheckTypeName(stack, context, schema.type, schema, value);
+ return isType || context.AddError({
+ keyword: "type",
+ schemaPath,
+ instancePath,
+ params: { type: schema.type }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/unevaluatedItems.mjs
+function BuildUnevaluatedItems(stack, context, schema, value) {
+ const [index3, item] = [Unique(), Unique()];
+ const indices = emit_exports.Call(emit_exports.Member("context", "GetIndices"), []);
+ const hasIndex = emit_exports.Call(emit_exports.Member("indices", "has"), [index3]);
+ const isSchema = BuildSchema(stack, context, schema.unevaluatedItems, item);
+ const addIndex = emit_exports.Call(emit_exports.Member("context", "AddIndex"), [index3]);
+ const isEvery = emit_exports.Every(value, emit_exports.Constant(0), [item, index3], emit_exports.And(emit_exports.Or(hasIndex, isSchema), addIndex));
+ return emit_exports.Call(emit_exports.ArrowFunction(["context"], emit_exports.Statements([
+ emit_exports.ConstDeclaration("indices", indices),
+ emit_exports.Return(isEvery)
+ ])), ["context"]);
+}
+function CheckUnevaluatedItems(stack, context, schema, value) {
+ const indices = context.GetIndices();
+ return guard_exports.Every(value, 0, (item, index3) => {
+ return (indices.has(index3) || CheckSchema(stack, context, schema.unevaluatedItems, item)) && context.AddIndex(index3);
+ });
+}
+function ErrorUnevaluatedItems(stack, context, schemaPath, instancePath, schema, value) {
+ const indices = context.GetIndices();
+ const unevaluatedItems = [];
+ const isUnevaluatedItems = guard_exports.EveryAll(value, 0, (item, index3) => {
+ const nextContext = new ErrorContext();
+ const isEvaluatedItem = (indices.has(index3) || ErrorSchema(stack, nextContext, schemaPath, instancePath, schema.unevaluatedItems, item)) && context.AddIndex(index3);
+ if (!isEvaluatedItem)
+ unevaluatedItems.push(index3);
+ return isEvaluatedItem;
+ });
+ return isUnevaluatedItems || context.AddError({
+ keyword: "unevaluatedItems",
+ schemaPath,
+ instancePath,
+ params: { unevaluatedItems }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/unevaluatedProperties.mjs
+function BuildUnevaluatedProperties(stack, context, schema, value) {
+ const [key, prop] = [Unique(), Unique()];
+ const keys = emit_exports.Call(emit_exports.Member("context", "GetKeys"), []);
+ const hasKey = emit_exports.Call(emit_exports.Member("keys", "has"), [key]);
+ const addKey = emit_exports.Call(emit_exports.Member("context", "AddKey"), [key]);
+ const isSchema = BuildSchema(stack, context, schema.unevaluatedProperties, prop);
+ const isEvery = emit_exports.Every(emit_exports.Entries(value), emit_exports.Constant(0), [`[${key}, ${prop}]`, "_"], emit_exports.Or(hasKey, emit_exports.And(isSchema, addKey)));
+ return emit_exports.Call(emit_exports.ArrowFunction(["context"], emit_exports.Statements([
+ emit_exports.ConstDeclaration("keys", keys),
+ emit_exports.Return(isEvery)
+ ])), ["context"]);
+}
+function CheckUnevaluatedProperties(stack, context, schema, value) {
+ const keys = context.GetKeys();
+ return guard_exports.Every(guard_exports.Entries(value), 0, ([key, prop]) => {
+ return keys.has(key) || CheckSchema(stack, context, schema.unevaluatedProperties, prop) && context.AddKey(key);
+ });
+}
+function ErrorUnevaluatedProperties(stack, context, schemaPath, instancePath, schema, value) {
+ const keys = context.GetKeys();
+ const unevaluatedProperties = [];
+ const isUnevaluatedProperties = guard_exports.EveryAll(guard_exports.Entries(value), 0, ([key, prop]) => {
+ const nextContext = new ErrorContext();
+ const isEvaluatedProperty = keys.has(key) || ErrorSchema(stack, nextContext, schemaPath, instancePath, schema.unevaluatedProperties, prop) && context.AddKey(key);
+ if (!isEvaluatedProperty)
+ unevaluatedProperties.push(key);
+ return isEvaluatedProperty;
+ });
+ return isUnevaluatedProperties || context.AddError({
+ keyword: "unevaluatedProperties",
+ schemaPath,
+ instancePath,
+ params: { unevaluatedProperties }
+ });
+}
+
+// node_modules/typebox/build/system/hashing/hash.mjs
+var hash_exports = {};
+__export(hash_exports, {
+ Hash: () => Hash,
+ HashCode: () => HashCode
+});
+
+// node_modules/typebox/build/system/unreachable/unreachable.mjs
+function Unreachable() {
+ throw new Error("Unreachable");
+}
+
+// node_modules/typebox/build/system/hashing/hash.mjs
+function InstanceKeys(value) {
+ const propertyKeys = /* @__PURE__ */ new Set();
+ let current = value;
+ while (current && current !== Object.prototype) {
+ for (const key of Reflect.ownKeys(current)) {
+ if (key !== "constructor" && typeof key !== "symbol")
+ propertyKeys.add(key);
+ }
+ current = Object.getPrototypeOf(current);
+ }
+ return [...propertyKeys];
+}
+function IsIEEE754(value) {
+ return typeof value === "number";
+}
+var ByteMarker;
+(function(ByteMarker2) {
+ ByteMarker2[ByteMarker2["Array"] = 0] = "Array";
+ ByteMarker2[ByteMarker2["BigInt"] = 1] = "BigInt";
+ ByteMarker2[ByteMarker2["Boolean"] = 2] = "Boolean";
+ ByteMarker2[ByteMarker2["Date"] = 3] = "Date";
+ ByteMarker2[ByteMarker2["Constructor"] = 4] = "Constructor";
+ ByteMarker2[ByteMarker2["Function"] = 5] = "Function";
+ ByteMarker2[ByteMarker2["Null"] = 6] = "Null";
+ ByteMarker2[ByteMarker2["Number"] = 7] = "Number";
+ ByteMarker2[ByteMarker2["Object"] = 8] = "Object";
+ ByteMarker2[ByteMarker2["RegExp"] = 9] = "RegExp";
+ ByteMarker2[ByteMarker2["String"] = 10] = "String";
+ ByteMarker2[ByteMarker2["Symbol"] = 11] = "Symbol";
+ ByteMarker2[ByteMarker2["TypeArray"] = 12] = "TypeArray";
+ ByteMarker2[ByteMarker2["Undefined"] = 13] = "Undefined";
+})(ByteMarker || (ByteMarker = {}));
+var Accumulator = BigInt("14695981039346656037");
+var [Prime, Size] = [BigInt("1099511628211"), BigInt(
+ "18446744073709551616"
+ /* 2 ^ 64 */
+)];
+var Bytes = Array.from({ length: 256 }).map((_, i) => BigInt(i));
+var F64 = new Float64Array(1);
+var F64In = new DataView(F64.buffer);
+var F64Out = new Uint8Array(F64.buffer);
+function FNV1A64_OP(byte) {
+ Accumulator = Accumulator ^ Bytes[byte];
+ Accumulator = Accumulator * Prime % Size;
+}
+function FromArray(value) {
+ FNV1A64_OP(ByteMarker.Array);
+ for (const item of value) {
+ FromValue(item);
+ }
+}
+function FromBigInt(value) {
+ FNV1A64_OP(ByteMarker.BigInt);
+ F64In.setBigInt64(0, value);
+ for (const byte of F64Out) {
+ FNV1A64_OP(byte);
+ }
+}
+function FromBoolean(value) {
+ FNV1A64_OP(ByteMarker.Boolean);
+ FNV1A64_OP(value ? 1 : 0);
+}
+function FromConstructor(value) {
+ FNV1A64_OP(ByteMarker.Constructor);
+ FromValue(value.toString());
+}
+function FromDate(value) {
+ FNV1A64_OP(ByteMarker.Date);
+ FromValue(value.getTime());
+}
+function FromFunction(value) {
+ FNV1A64_OP(ByteMarker.Function);
+ FromValue(value.toString());
+}
+function FromNull(_value) {
+ FNV1A64_OP(ByteMarker.Null);
+}
+function FromNumber(value) {
+ FNV1A64_OP(ByteMarker.Number);
+ F64In.setFloat64(
+ 0,
+ value,
+ true
+ /* little-endian */
+ );
+ for (const byte of F64Out) {
+ FNV1A64_OP(byte);
+ }
+}
+function FromObject(value) {
+ FNV1A64_OP(ByteMarker.Object);
+ for (const key of InstanceKeys(value).sort()) {
+ FromValue(key);
+ FromValue(value[key]);
+ }
+}
+function FromRegExp(value) {
+ FNV1A64_OP(ByteMarker.RegExp);
+ FromString(value.toString());
+}
+var encoder = new TextEncoder();
+function FromString(value) {
+ FNV1A64_OP(ByteMarker.String);
+ for (const byte of encoder.encode(value)) {
+ FNV1A64_OP(byte);
+ }
+}
+function FromSymbol(value) {
+ FNV1A64_OP(ByteMarker.Symbol);
+ FromValue(value.toString());
+}
+function FromTypeArray(value) {
+ FNV1A64_OP(ByteMarker.TypeArray);
+ const buffer = new Uint8Array(value.buffer);
+ for (let i = 0; i < buffer.length; i++) {
+ FNV1A64_OP(buffer[i]);
+ }
+}
+function FromUndefined(_value) {
+ return FNV1A64_OP(ByteMarker.Undefined);
+}
+function FromValue(value) {
+ return globals_exports.IsTypeArray(value) ? FromTypeArray(value) : globals_exports.IsDate(value) ? FromDate(value) : globals_exports.IsRegExp(value) ? FromRegExp(value) : globals_exports.IsBoolean(value) ? FromBoolean(value.valueOf()) : globals_exports.IsString(value) ? FromString(value.valueOf()) : globals_exports.IsNumber(value) ? FromNumber(value.valueOf()) : IsIEEE754(value) ? FromNumber(value) : guard_exports.IsArray(value) ? FromArray(value) : guard_exports.IsBoolean(value) ? FromBoolean(value) : guard_exports.IsBigInt(value) ? FromBigInt(value) : guard_exports.IsConstructor(value) ? FromConstructor(value) : guard_exports.IsNull(value) ? FromNull(value) : guard_exports.IsObject(value) ? FromObject(value) : guard_exports.IsString(value) ? FromString(value) : guard_exports.IsSymbol(value) ? FromSymbol(value) : guard_exports.IsUndefined(value) ? FromUndefined(value) : guard_exports.IsFunction(value) ? FromFunction(value) : Unreachable();
+}
+function HashCode(value) {
+ Accumulator = BigInt("14695981039346656037");
+ FromValue(value);
+ return Accumulator;
+}
+function Hash(value) {
+ return HashCode(value).toString(16).padStart(16, "0");
+}
+
+// node_modules/typebox/build/schema/engine/uniqueItems.mjs
+function IsValid5(schema) {
+ return !guard_exports.IsEqual(schema.uniqueItems, false);
+}
+function BuildUniqueItems(_stack, _context, schema, value) {
+ if (!IsValid5(schema))
+ return emit_exports.Constant(true);
+ const set = emit_exports.Member(emit_exports.New("Set", [emit_exports.Call(emit_exports.Member(value, "map"), [emit_exports.Member("Hashing", "Hash")])]), "size");
+ const isLength = emit_exports.Member(value, "length");
+ return emit_exports.IsEqual(set, isLength);
+}
+function CheckUniqueItems(_stack, _context, schema, value) {
+ if (!IsValid5(schema))
+ return true;
+ const set = new Set(value.map(hash_exports.Hash)).size;
+ const isLength = value.length;
+ return guard_exports.IsEqual(set, isLength);
+}
+function ErrorUniqueItems(_stack, context, schemaPath, instancePath, schema, value) {
+ if (!IsValid5(schema))
+ return true;
+ const set = /* @__PURE__ */ new Set();
+ const duplicateItems = value.reduce((result, value2, index3) => {
+ const hash = hash_exports.Hash(value2);
+ if (set.has(hash))
+ return [...result, index3];
+ set.add(hash);
+ return result;
+ }, []);
+ const isUniqueItems = guard_exports.IsEqual(duplicateItems.length, 0);
+ return isUniqueItems || context.AddError({
+ keyword: "uniqueItems",
+ schemaPath,
+ instancePath,
+ params: { duplicateItems }
+ });
+}
+
+// node_modules/typebox/build/schema/engine/schema.mjs
+function HasTypeName(schema, typename) {
+ return IsType(schema) && (guard_exports.IsArray(schema.type) && guard_exports.IsGreaterThan(schema.type.length, 0) && guard_exports.Every(schema.type, 0, (type) => guard_exports.IsEqual(type, typename)) || guard_exports.IsEqual(schema.type, typename));
+}
+function HasObjectType(schema) {
+ return HasTypeName(schema, "object");
+}
+function HasObjectKeywords(schema) {
+ return IsSchemaObject(schema) && (IsAdditionalProperties(schema) || IsDependencies(schema) || IsDependentRequired(schema) || IsDependentSchemas(schema) || IsProperties(schema) || IsPatternProperties(schema) || IsPropertyNames(schema) || IsMinProperties(schema) || IsMaxProperties(schema) || IsRequired(schema) || IsUnevaluatedProperties(schema));
+}
+function HasArrayType(schema) {
+ return HasTypeName(schema, "array");
+}
+function HasArrayKeywords(schema) {
+ return IsSchemaObject(schema) && (IsAdditionalItems(schema) || IsItems(schema) || IsContains(schema) || IsMaxContains(schema) || IsMaxItems(schema) || IsMinContains(schema) || IsMinItems(schema) || IsPrefixItems(schema) || IsUnevaluatedItems(schema) || IsUniqueItems(schema));
+}
+function HasStringType(schema) {
+ return HasTypeName(schema, "string");
+}
+function HasStringKeywords(schema) {
+ return IsSchemaObject(schema) && (IsMinLength4(schema) || IsMaxLength4(schema) || IsFormat(schema) || IsPattern(schema));
+}
+function HasNumberType(schema) {
+ return HasTypeName(schema, "number") || HasTypeName(schema, "bigint");
+}
+function HasNumberKeywords(schema) {
+ return IsSchemaObject(schema) && (IsMinimum(schema) || IsMaximum(schema) || IsExclusiveMaximum(schema) || IsExclusiveMinimum(schema) || IsMultipleOf2(schema));
+}
+function BuildSchemaPushStack(stack, context, schema, value) {
+ return context.UseUnevaluated() ? emit_exports.And(emit_exports.And(context.Push(), BuildSchema(stack, context, schema, value)), context.Pop()) : BuildSchema(stack, context, schema, value);
+}
+function BuildSchema(stack, context, schema, value) {
+ stack.Push(schema);
+ const conditions = [];
+ if (IsSchemaBoolean(schema))
+ return BuildSchemaBoolean(stack, context, schema, value);
+ if (IsType(schema))
+ conditions.push(BuildType(stack, context, schema, value));
+ if (HasObjectKeywords(schema)) {
+ const constraints = [];
+ if (IsRequired(schema))
+ constraints.push(BuildRequired(stack, context, schema, value));
+ if (IsAdditionalProperties(schema))
+ constraints.push(BuildAdditionalProperties(stack, context, schema, value));
+ if (IsDependencies(schema))
+ constraints.push(BuildDependencies(stack, context, schema, value));
+ if (IsDependentRequired(schema))
+ constraints.push(BuildDependentRequired(stack, context, schema, value));
+ if (IsDependentSchemas(schema))
+ constraints.push(BuildDependentSchemas(stack, context, schema, value));
+ if (IsPatternProperties(schema))
+ constraints.push(BuildPatternProperties(stack, context, schema, value));
+ if (IsProperties(schema))
+ constraints.push(BuildProperties(stack, context, schema, value));
+ if (IsPropertyNames(schema))
+ constraints.push(BuildPropertyNames(stack, context, schema, value));
+ if (IsMinProperties(schema))
+ constraints.push(BuildMinProperties(stack, context, schema, value));
+ if (IsMaxProperties(schema))
+ constraints.push(BuildMaxProperties(stack, context, schema, value));
+ const reduced = emit_exports.ReduceAnd(constraints);
+ const guarded = emit_exports.Or(emit_exports.Not(emit_exports.IsObjectNotArray(value)), reduced);
+ conditions.push(HasObjectType(schema) ? reduced : guarded);
+ }
+ if (HasArrayKeywords(schema)) {
+ const constraints = [];
+ if (IsAdditionalItems(schema))
+ constraints.push(BuildAdditionalItems(stack, context, schema, value));
+ if (IsContains(schema))
+ constraints.push(BuildContains(stack, context, schema, value));
+ if (IsItems(schema))
+ constraints.push(BuildItems(stack, context, schema, value));
+ if (IsMaxContains(schema))
+ constraints.push(BuildMaxContains(stack, context, schema, value));
+ if (IsMaxItems(schema))
+ constraints.push(BuildMaxItems(stack, context, schema, value));
+ if (IsMinContains(schema))
+ constraints.push(BuildMinContains(stack, context, schema, value));
+ if (IsMinItems(schema))
+ constraints.push(BuildMinItems(stack, context, schema, value));
+ if (IsPrefixItems(schema))
+ constraints.push(BuildPrefixItems(stack, context, schema, value));
+ if (IsUniqueItems(schema))
+ constraints.push(BuildUniqueItems(stack, context, schema, value));
+ const reduced = emit_exports.ReduceAnd(constraints);
+ const guarded = emit_exports.Or(emit_exports.Not(emit_exports.IsArray(value)), reduced);
+ conditions.push(HasArrayType(schema) ? reduced : guarded);
+ }
+ if (HasStringKeywords(schema)) {
+ const constraints = [];
+ if (IsMaxLength4(schema))
+ constraints.push(BuildMaxLength(stack, context, schema, value));
+ if (IsMinLength4(schema))
+ constraints.push(BuildMinLength(stack, context, schema, value));
+ if (IsFormat(schema))
+ constraints.push(BuildFormat(stack, context, schema, value));
+ if (IsPattern(schema))
+ constraints.push(BuildPattern(stack, context, schema, value));
+ const reduced = emit_exports.ReduceAnd(constraints);
+ const guarded = emit_exports.Or(emit_exports.Not(emit_exports.IsString(value)), reduced);
+ conditions.push(HasStringType(schema) ? reduced : guarded);
+ }
+ if (HasNumberKeywords(schema)) {
+ const constraints = [];
+ if (IsExclusiveMaximum(schema))
+ constraints.push(BuildExclusiveMaximum(stack, context, schema, value));
+ if (IsExclusiveMinimum(schema))
+ constraints.push(BuildExclusiveMinimum(stack, context, schema, value));
+ if (IsMaximum(schema))
+ constraints.push(BuildMaximum(stack, context, schema, value));
+ if (IsMinimum(schema))
+ constraints.push(BuildMinimum(stack, context, schema, value));
+ if (IsMultipleOf2(schema))
+ constraints.push(BuildMultipleOf(stack, context, schema, value));
+ const reduced = emit_exports.ReduceAnd(constraints);
+ const guarded = emit_exports.Or(emit_exports.Not(emit_exports.Or(emit_exports.IsNumber(value), emit_exports.IsBigInt(value))), reduced);
+ conditions.push(HasNumberType(schema) ? reduced : guarded);
+ }
+ if (IsRef(schema))
+ conditions.push(BuildRef(stack, context, schema, value));
+ if (IsRecursiveRef(schema))
+ conditions.push(BuildRecursiveRef(stack, context, schema, value));
+ if (IsDynamicRef(schema))
+ conditions.push(BuildDynamicRef(stack, context, schema, value));
+ if (IsConst(schema))
+ conditions.push(BuildConst(stack, context, schema, value));
+ if (IsEnum(schema))
+ conditions.push(BuildEnum(stack, context, schema, value));
+ if (IsIf(schema))
+ conditions.push(BuildIf(stack, context, schema, value));
+ if (IsNot(schema))
+ conditions.push(BuildNot(stack, context, schema, value));
+ if (IsAllOf(schema))
+ conditions.push(BuildAllOf(stack, context, schema, value));
+ if (IsAnyOf(schema))
+ conditions.push(BuildAnyOf(stack, context, schema, value));
+ if (IsOneOf(schema))
+ conditions.push(BuildOneOf(stack, context, schema, value));
+ if (IsUnevaluatedItems(schema))
+ conditions.push(emit_exports.Or(emit_exports.Not(emit_exports.IsArray(value)), BuildUnevaluatedItems(stack, context, schema, value)));
+ if (IsUnevaluatedProperties(schema))
+ conditions.push(emit_exports.Or(emit_exports.Not(emit_exports.IsObject(value)), BuildUnevaluatedProperties(stack, context, schema, value)));
+ if (IsRefine(schema))
+ conditions.push(BuildRefine(stack, context, schema, value));
+ const result = emit_exports.ReduceAnd(conditions);
+ stack.Pop(schema);
+ return result;
+}
+function CheckSchemaPushStack(stack, context, schema, value) {
+ return context.Push() && CheckSchema(stack, context, schema, value) && context.Pop();
+}
+function CheckSchema(stack, context, schema, value) {
+ stack.Push(schema);
+ const result = IsSchemaBoolean(schema) ? CheckSchemaBoolean(stack, context, schema, value) : (!IsType(schema) || CheckType(stack, context, schema, value)) && (!(guard_exports.IsObject(value) && !guard_exports.IsArray(value)) || (!IsRequired(schema) || CheckRequired(stack, context, schema, value)) && (!IsAdditionalProperties(schema) || CheckAdditionalProperties(stack, context, schema, value)) && (!IsDependencies(schema) || CheckDependencies(stack, context, schema, value)) && (!IsDependentRequired(schema) || CheckDependentRequired(stack, context, schema, value)) && (!IsDependentSchemas(schema) || CheckDependentSchemas(stack, context, schema, value)) && (!IsPatternProperties(schema) || CheckPatternProperties(stack, context, schema, value)) && (!IsProperties(schema) || CheckProperties(stack, context, schema, value)) && (!IsPropertyNames(schema) || CheckPropertyNames(stack, context, schema, value)) && (!IsMinProperties(schema) || CheckMinProperties(stack, context, schema, value)) && (!IsMaxProperties(schema) || CheckMaxProperties(stack, context, schema, value))) && (!guard_exports.IsArray(value) || (!IsAdditionalItems(schema) || CheckAdditionalItems(stack, context, schema, value)) && (!IsContains(schema) || CheckContains(stack, context, schema, value)) && (!IsItems(schema) || CheckItems(stack, context, schema, value)) && (!IsMaxContains(schema) || CheckMaxContains(stack, context, schema, value)) && (!IsMaxItems(schema) || CheckMaxItems(stack, context, schema, value)) && (!IsMinContains(schema) || CheckMinContains(stack, context, schema, value)) && (!IsMinItems(schema) || CheckMinItems(stack, context, schema, value)) && (!IsPrefixItems(schema) || CheckPrefixItems(stack, context, schema, value)) && (!IsUniqueItems(schema) || CheckUniqueItems(stack, context, schema, value))) && (!guard_exports.IsString(value) || (!IsMaxLength4(schema) || CheckMaxLength(stack, context, schema, value)) && (!IsMinLength4(schema) || CheckMinLength(stack, context, schema, value)) && (!IsFormat(schema) || CheckFormat(stack, context, schema, value)) && (!IsPattern(schema) || CheckPattern(stack, context, schema, value))) && (!(guard_exports.IsNumber(value) || guard_exports.IsBigInt(value)) || (!IsExclusiveMaximum(schema) || CheckExclusiveMaximum(stack, context, schema, value)) && (!IsExclusiveMinimum(schema) || CheckExclusiveMinimum(stack, context, schema, value)) && (!IsMaximum(schema) || CheckMaximum(stack, context, schema, value)) && (!IsMinimum(schema) || CheckMinimum(stack, context, schema, value)) && (!IsMultipleOf2(schema) || CheckMultipleOf(stack, context, schema, value))) && (!IsRef(schema) || CheckRef(stack, context, schema, value)) && (!IsRecursiveRef(schema) || CheckRecursiveRef(stack, context, schema, value)) && (!IsDynamicRef(schema) || CheckDynamicRef(stack, context, schema, value)) && (!IsConst(schema) || CheckConst(stack, context, schema, value)) && (!IsEnum(schema) || CheckEnum(stack, context, schema, value)) && (!IsIf(schema) || CheckIf(stack, context, schema, value)) && (!IsNot(schema) || CheckNot(stack, context, schema, value)) && (!IsAllOf(schema) || CheckAllOf(stack, context, schema, value)) && (!IsAnyOf(schema) || CheckAnyOf(stack, context, schema, value)) && (!IsOneOf(schema) || CheckOneOf(stack, context, schema, value)) && (!IsUnevaluatedItems(schema) || (!guard_exports.IsArray(value) || CheckUnevaluatedItems(stack, context, schema, value))) && (!IsUnevaluatedProperties(schema) || (!guard_exports.IsObject(value) || CheckUnevaluatedProperties(stack, context, schema, value))) && (!IsRefine(schema) || CheckRefine(stack, context, schema, value));
+ stack.Pop(schema);
+ return result;
+}
+function ErrorSchemaPushStack(stack, context, schemaPath, instancePath, schema, value) {
+ return context.Push() && ErrorSchema(stack, context, schemaPath, instancePath, schema, value) && context.Pop();
+}
+function ErrorSchema(stack, context, schemaPath, instancePath, schema, value) {
+ if (context.AtCapacity())
+ return false;
+ stack.Push(schema);
+ const result = IsSchemaBoolean(schema) ? ErrorSchemaBoolean(stack, context, schemaPath, instancePath, schema, value) : !!(+(!IsType(schema) || ErrorType(stack, context, schemaPath, instancePath, schema, value)) & +(!(guard_exports.IsObject(value) && !guard_exports.IsArray(value)) || !!(+(!IsRequired(schema) || ErrorRequired(stack, context, schemaPath, instancePath, schema, value)) & +(!IsAdditionalProperties(schema) || ErrorAdditionalProperties(stack, context, schemaPath, instancePath, schema, value)) & +(!IsDependencies(schema) || ErrorDependencies(stack, context, schemaPath, instancePath, schema, value)) & +(!IsDependentRequired(schema) || ErrorDependentRequired(stack, context, schemaPath, instancePath, schema, value)) & +(!IsDependentSchemas(schema) || ErrorDependentSchemas(stack, context, schemaPath, instancePath, schema, value)) & +(!IsPatternProperties(schema) || ErrorPatternProperties(stack, context, schemaPath, instancePath, schema, value)) & +(!IsProperties(schema) || ErrorProperties(stack, context, schemaPath, instancePath, schema, value)) & +(!IsPropertyNames(schema) || ErrorPropertyNames(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMinProperties(schema) || ErrorMinProperties(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMaxProperties(schema) || ErrorMaxProperties(stack, context, schemaPath, instancePath, schema, value)))) & +(!guard_exports.IsArray(value) || !!(+(!IsAdditionalItems(schema) || ErrorAdditionalItems(stack, context, schemaPath, instancePath, schema, value)) & +(!IsContains(schema) || ErrorContains(stack, context, schemaPath, instancePath, schema, value)) & +(!IsItems(schema) || ErrorItems(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMaxContains(schema) || ErrorMaxContains(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMaxItems(schema) || ErrorMaxItems(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMinContains(schema) || ErrorMinContains(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMinItems(schema) || ErrorMinItems(stack, context, schemaPath, instancePath, schema, value)) & +(!IsPrefixItems(schema) || ErrorPrefixItems(stack, context, schemaPath, instancePath, schema, value)) & +(!IsUniqueItems(schema) || ErrorUniqueItems(stack, context, schemaPath, instancePath, schema, value)))) & +(!guard_exports.IsString(value) || !!(+(!IsMaxLength4(schema) || ErrorMaxLength(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMinLength4(schema) || ErrorMinLength(stack, context, schemaPath, instancePath, schema, value)) & +(!IsFormat(schema) || ErrorFormat(stack, context, schemaPath, instancePath, schema, value)) & +(!IsPattern(schema) || ErrorPattern(stack, context, schemaPath, instancePath, schema, value)))) & +(!(guard_exports.IsNumber(value) || guard_exports.IsBigInt(value)) || !!(+(!IsExclusiveMaximum(schema) || ErrorExclusiveMaximum(stack, context, schemaPath, instancePath, schema, value)) & +(!IsExclusiveMinimum(schema) || ErrorExclusiveMinimum(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMaximum(schema) || ErrorMaximum(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMinimum(schema) || ErrorMinimum(stack, context, schemaPath, instancePath, schema, value)) & +(!IsMultipleOf2(schema) || ErrorMultipleOf(stack, context, schemaPath, instancePath, schema, value)))) & +(!IsRef(schema) || ErrorRef(stack, context, schemaPath, instancePath, schema, value)) & +(!IsRecursiveRef(schema) || ErrorRecursiveRef(stack, context, schemaPath, instancePath, schema, value)) & +(!IsDynamicRef(schema) || ErrorDynamicRef(stack, context, schemaPath, instancePath, schema, value)) & +(!IsConst(schema) || ErrorConst(stack, context, schemaPath, instancePath, schema, value)) & +(!IsEnum(schema) || ErrorEnum(stack, context, schemaPath, instancePath, schema, value)) & +(!IsIf(schema) || ErrorIf(stack, context, schemaPath, instancePath, schema, value)) & +(!IsNot(schema) || ErrorNot(stack, context, schemaPath, instancePath, schema, value)) & +(!IsAllOf(schema) || ErrorAllOf(stack, context, schemaPath, instancePath, schema, value)) & +(!IsAnyOf(schema) || ErrorAnyOf(stack, context, schemaPath, instancePath, schema, value)) & +(!IsOneOf(schema) || ErrorOneOf(stack, context, schemaPath, instancePath, schema, value)) & +(!IsUnevaluatedItems(schema) || (!guard_exports.IsArray(value) || ErrorUnevaluatedItems(stack, context, schemaPath, instancePath, schema, value))) & +(!IsUnevaluatedProperties(schema) || (!guard_exports.IsObject(value) || ErrorUnevaluatedProperties(stack, context, schemaPath, instancePath, schema, value)))) && (!IsRefine(schema) || ErrorRefine(stack, context, schemaPath, instancePath, schema, value));
+ stack.Pop(schema);
+ return result;
+}
+
+// node_modules/typebox/build/schema/engine/_functions.mjs
+var index2 = [0];
+var names2 = /* @__PURE__ */ new Map();
+var funcs = /* @__PURE__ */ new Map();
+function NextName() {
+ return `${index2[0]++}`;
+}
+function CreateName(schema, href) {
+ if (!names2.has(schema))
+ names2.set(schema, /* @__PURE__ */ new Map());
+ const hrefs = names2.get(schema);
+ if (hrefs.has(href))
+ return hrefs.get(href);
+ const name = NextName();
+ hrefs.set(href, name);
+ return name;
+}
+function CreateCallExpression(context, _schema, name, value) {
+ return context.UseUnevaluated() ? emit_exports.Call(`check_${name}`, ["context", value]) : emit_exports.Call(`check_${name}`, [value]);
+}
+function CreateFunctionExpression(stack, context, schema, name) {
+ const expression = BuildSchema(stack, context, schema, "value");
+ return context.UseUnevaluated() ? emit_exports.ConstDeclaration(`check_${name}`, emit_exports.ArrowFunction(["context", "value"], expression)) : emit_exports.ConstDeclaration(`check_${name}`, emit_exports.ArrowFunction(["value"], expression));
+}
+function ResetFunctions() {
+ index2[0] = 0;
+ names2.clear();
+ funcs.clear();
+}
+function GetFunctions() {
+ return [...funcs.values()];
+}
+function CreateFunction(stack, context, schema, value) {
+ const name = CreateName(schema, stack.LexicalBaseURL());
+ const call = CreateCallExpression(context, schema, name, value);
+ if (funcs.has(name))
+ return call;
+ funcs.set(name, "");
+ funcs.set(name, CreateFunctionExpression(stack, context, schema, name));
+ return call;
+}
+
+// node_modules/typebox/build/schema/resolve/resolve.mjs
+var resolve_exports = {};
+__export(resolve_exports, {
+ Base: () => Base,
+ DefaultBase: () => DefaultBase,
+ DynamicRef: () => DynamicRef,
+ Ref: () => Ref,
+ ResolveDynamicRef: () => ResolveDynamicRef,
+ ResolveRecursiveRef: () => ResolveRecursiveRef,
+ ResolveRef: () => ResolveRef,
+ Resource: () => Resource
+});
+
+// node_modules/typebox/build/schema/pointer/pointer.mjs
+var pointer_exports = {};
+__export(pointer_exports, {
+ Delete: () => Delete,
+ Get: () => Get3,
+ Has: () => Has2,
+ Indices: () => Indices,
+ Set: () => Set4
+});
+function AssertNotRoot(indices) {
+ if (indices.length === 0)
+ throw Error("Cannot set root");
+}
+function AssertCanSet(value) {
+ if (!guard_exports.IsObject(value))
+ throw Error("Cannot set value");
+}
+function AssertIndex(index3) {
+ if (guard_exports.IsUnsafePropertyKey(index3))
+ throw Error("Pointer contains unsafe property key");
+}
+function AssertIndices(indices) {
+ for (const index3 of indices)
+ AssertIndex(index3);
+}
+function IsNumericIndex(index3) {
+ return /^(0|[1-9]\d*)$/.test(index3);
+}
+function TakeIndexRight(indices) {
+ return [
+ indices.slice(0, indices.length - 1),
+ indices.slice(indices.length - 1)[0]
+ ];
+}
+function HasIndex(index3, value) {
+ return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, index3);
+}
+function GetIndex(index3, value) {
+ return guard_exports.IsObject(value) && !guard_exports.IsUnsafePropertyKey(index3) ? value[index3] : void 0;
+}
+function GetIndices(indices, value) {
+ return indices.reduce((value2, index3) => GetIndex(index3, value2), value);
+}
+function Indices(pointer) {
+ if (guard_exports.IsEqual(pointer.length, 0))
+ return [];
+ const indices = pointer.split("/").map((index3) => index3.replace(/~1/g, "/").replace(/~0/g, "~"));
+ return indices.length > 0 && indices[0] === "" ? indices.slice(1) : indices;
+}
+function Has2(value, pointer) {
+ let current = value;
+ return Indices(pointer).every((index3) => {
+ if (!HasIndex(index3, current))
+ return false;
+ current = current[index3];
+ return true;
+ });
+}
+function Get3(value, pointer) {
+ const indices = Indices(pointer);
+ return GetIndices(indices, value);
+}
+function Set4(value, pointer, next) {
+ const indices = Indices(pointer);
+ AssertNotRoot(indices);
+ AssertIndices(indices);
+ const [head, index3] = TakeIndexRight(indices);
+ const parent = GetIndices(head, value);
+ AssertCanSet(parent);
+ parent[index3] = next;
+ return value;
+}
+function Delete(value, pointer) {
+ const indices = Indices(pointer);
+ AssertNotRoot(indices);
+ AssertIndices(indices);
+ const [head, index3] = TakeIndexRight(indices);
+ const parent = GetIndices(head, value);
+ AssertCanSet(parent);
+ if (guard_exports.IsArray(parent) && IsNumericIndex(index3)) {
+ parent.splice(+index3, 1);
+ } else {
+ delete parent[index3];
+ }
+ return value;
+}
+
+// node_modules/typebox/build/schema/resolve/resolve.mjs
+var DefaultBase = "https://json-schema.org";
+function FindDynamicAnchor(schema, name) {
+ if (guard_exports.IsObject(schema) && IsDynamicAnchor(schema) && guard_exports.IsEqual(schema.$dynamicAnchor, name)) {
+ return schema;
+ }
+ if (guard_exports.IsObject(schema)) {
+ for (const key of guard_exports.Keys(schema)) {
+ const result = FindDynamicAnchor(schema[key], name);
+ if (result)
+ return result;
+ }
+ }
+ return void 0;
+}
+function FindBase(schema, base, target) {
+ if (guard_exports.IsEqual(schema, target))
+ return base.href;
+ const nextBase = IsSchemaObject(schema) && IsId(schema) ? new URL(schema.$id, base.href) : base;
+ if (guard_exports.IsArray(schema)) {
+ for (const item of schema) {
+ const result = FindBase(item, nextBase, target);
+ if (!guard_exports.IsUndefined(result))
+ return result;
+ }
+ } else if (guard_exports.IsObject(schema)) {
+ for (const key of guard_exports.Keys(schema)) {
+ const result = FindBase(schema[key], nextBase, target);
+ if (!guard_exports.IsUndefined(result))
+ return result;
+ }
+ }
+ return void 0;
+}
+function MatchId(schema, base, ref) {
+ if (guard_exports.IsEqual(schema.$id, ref.hash))
+ return schema;
+ const absoluteRef = new URL(ref.href, base.href);
+ if (guard_exports.IsEqual(base.pathname, absoluteRef.pathname))
+ return ref.hash.startsWith("#") ? MatchHash(schema, ref) : schema;
+ return void 0;
+}
+function MatchAnchor(schema, base, ref) {
+ const absoluteAnchor = new URL(`#${schema.$anchor}`, base.href);
+ const absoluteRef = new URL(ref.href, base.href);
+ return guard_exports.IsEqual(absoluteAnchor.href, absoluteRef.href) ? schema : void 0;
+}
+function MatchDynamicAnchor(schema, base, ref) {
+ const absoluteAnchor = new URL(`#${schema.$dynamicAnchor}`, base.href);
+ const absoluteRef = new URL(ref.href, base.href);
+ const isMatch = guard_exports.IsEqual(absoluteAnchor.href, absoluteRef.href);
+ return isMatch ? schema : void 0;
+}
+function MatchHash(schema, ref) {
+ if (ref.href.endsWith("#"))
+ return schema;
+ if (!ref.hash.startsWith("#"))
+ return void 0;
+ const fragment = decodeURIComponent(ref.hash.slice(1));
+ if (!fragment.startsWith("/"))
+ return void 0;
+ const result = pointer_exports.Get(schema, fragment);
+ return result;
+}
+function Match2(schema, base, ref) {
+ if (IsId(schema)) {
+ const result = MatchId(schema, base, ref);
+ if (!guard_exports.IsUndefined(result))
+ return result;
+ }
+ if (IsAnchor(schema)) {
+ const result = MatchAnchor(schema, base, ref);
+ if (!guard_exports.IsUndefined(result))
+ return result;
+ }
+ if (IsDynamicAnchor(schema)) {
+ const result = MatchDynamicAnchor(schema, base, ref);
+ if (!guard_exports.IsUndefined(result))
+ return result;
+ }
+ return MatchHash(schema, ref);
+}
+function FromArray2(schema, base, ref) {
+ return schema.reduce((result, item) => {
+ const match = FromValue2(item, base, ref);
+ return !guard_exports.IsUndefined(match) ? match : result;
+ }, void 0);
+}
+function SkipProperty(key) {
+ return guard_exports.IsEqual(key, "const") || guard_exports.IsEqual(key, "enum");
+}
+function FromObject2(schema, base, ref) {
+ return guard_exports.Keys(schema).reduce((result, key) => {
+ if (SkipProperty(key))
+ return result;
+ const match = FromValue2(schema[key], base, ref);
+ return !guard_exports.IsUndefined(match) ? match : result;
+ }, void 0);
+}
+function FromValue2(schema, base, ref) {
+ const nextBase = IsSchemaObject(schema) && IsId(schema) ? new URL(schema.$id, base.href) : base;
+ if (IsSchemaObject(schema)) {
+ const result = Match2(schema, nextBase, ref);
+ if (!guard_exports.IsUndefined(result))
+ return result;
+ }
+ if (guard_exports.IsArray(schema))
+ return FromArray2(schema, nextBase, ref);
+ if (guard_exports.IsObject(schema))
+ return FromObject2(schema, nextBase, ref);
+ return void 0;
+}
+function Base(schema, base, target) {
+ return FindBase(schema, new URL(base || ".", DefaultBase), target);
+}
+function Resource(context, schema, base, ref) {
+ const result = Ref(context, schema, base, ref, false);
+ return IsSchemaObject(result) && IsId(result) ? result : void 0;
+}
+function CanonicalHref(url) {
+ return url.href.split("#")[0];
+}
+function RefContext(context, ref) {
+ return guard_exports.HasPropertyKey(context, ref) ? context[ref] : void 0;
+}
+function RefLocal(schema, base, ref) {
+ return FromValue2(schema, base, ref);
+}
+function RefRemote(context, base, ref) {
+ const canonicalHref = CanonicalHref(ref);
+ if (guard_exports.IsEqual(canonicalHref, CanonicalHref(base)))
+ return void 0;
+ if (!guard_exports.HasPropertyKey(context, canonicalHref))
+ return void 0;
+ const remoteSchema = context[canonicalHref];
+ const remoteBase = IsSchemaObject(remoteSchema) && IsId(remoteSchema) ? new URL(remoteSchema.$id, canonicalHref) : new URL(canonicalHref);
+ const result = guard_exports.IsEqual(ref.hash, "") ? remoteSchema : FromValue2(remoteSchema, remoteBase, ref);
+ return result;
+}
+function LegacyRetrievedResource(root, lexicalSchema, referenceBase, ref, schema) {
+ if (!ref.$ref.startsWith("#"))
+ return void 0;
+ if (guard_exports.HasPropertyKey(root, "$schema"))
+ return void 0;
+ const targetBase = Base(lexicalSchema, referenceBase, schema);
+ if (guard_exports.IsUndefined(targetBase) || guard_exports.IsEqual(targetBase, referenceBase))
+ return void 0;
+ return { target: schema, base: targetBase, root: lexicalSchema };
+}
+function RemoteRetrievedResource(context, canonical2, schema) {
+ const remoteRoot = context[canonical2];
+ if (!IsSchemaObject(remoteRoot))
+ return void 0;
+ return { target: schema, base: canonical2, root: remoteRoot };
+}
+function FindRetrievedResource(stackframe, ref, schema, canonical2, isRemote) {
+ const remote = isRemote ? RemoteRetrievedResource(stackframe.context, canonical2, schema) : void 0;
+ if (!guard_exports.IsUndefined(remote))
+ return remote;
+ return LegacyRetrievedResource(stackframe.root, stackframe.lexicalSchema, stackframe.referenceBase, ref, schema);
+}
+function FindResolvedResource(context, root, referenceBase, canonical2, schema, ids) {
+ if (IsId(schema))
+ return void 0;
+ const resource = Resource(context, root, referenceBase, canonical2);
+ if (!resource || ids.includes(resource))
+ return void 0;
+ return { target: schema, resource };
+}
+function Ref(remotes, schema, base, ref, applySchemaId = true) {
+ const initialBase = new URL(base || ".", DefaultBase);
+ const resolvedBase = applySchemaId && IsId(schema) ? new URL(schema.$id, initialBase) : initialBase;
+ const initialRef = new URL(ref, resolvedBase.href);
+ return RefContext(remotes, ref) ?? RefLocal(schema, resolvedBase, initialRef) ?? RefRemote(remotes, resolvedBase, initialRef);
+}
+function DynamicRef(context, root, base, schema, dynamicRef, dynamicAnchors) {
+ const initialBase = new URL(base || ".", DefaultBase);
+ const fragmentRoot = dynamicRef.$dynamicRef.startsWith("#") ? schema : root;
+ const fragmentTarget = Ref(context, fragmentRoot, base, dynamicRef.$dynamicRef, false);
+ if (guard_exports.IsUndefined(fragmentTarget)) {
+ const fragment2 = new URL(dynamicRef.$dynamicRef, initialBase).hash;
+ if (!fragment2.startsWith("#/") && fragment2.startsWith("#")) {
+ const name = decodeURIComponent(fragment2.slice(1));
+ const anchorTarget2 = dynamicAnchors.find((anchor) => guard_exports.IsEqual(anchor.$dynamicAnchor, name)) ?? FindDynamicAnchor(root, name);
+ return anchorTarget2;
+ }
+ return void 0;
+ }
+ if (!IsSchemaObject(fragmentTarget) || !IsDynamicAnchor(fragmentTarget))
+ return fragmentTarget;
+ const fragment = new URL(dynamicRef.$dynamicRef, initialBase).hash;
+ if (fragment.startsWith("#/"))
+ return fragmentTarget;
+ const anchorTarget = dynamicAnchors.find((anchor) => guard_exports.IsEqual(anchor.$dynamicAnchor, fragmentTarget.$dynamicAnchor));
+ return anchorTarget ?? fragmentTarget;
+}
+function ResolveRef(stackframe, ref) {
+ const source = stackframe.inRetrievedFrame ? stackframe.lexicalSchema : stackframe.root;
+ const refRoot = ref.$ref.startsWith("#") ? stackframe.lexicalSchema : source;
+ const schema = Ref(stackframe.context, refRoot, stackframe.referenceBase, ref.$ref, false);
+ if (!schema || !IsSchemaObject(schema))
+ return { schema };
+ const canonical2 = new URL(ref.$ref, stackframe.referenceBase).href.split("#")[0];
+ const isRemote = !guard_exports.IsEqual(canonical2, stackframe.resourceBase);
+ const retrievedResource = FindRetrievedResource(stackframe, ref, schema, canonical2, isRemote);
+ const resolvedResource = isRemote ? FindResolvedResource(stackframe.context, stackframe.root, stackframe.referenceBase, canonical2, schema, stackframe.ids) : void 0;
+ return { schema, retrievedResource, resolvedResource };
+}
+function ResolveRecursiveRef(stackframe, recursiveRef) {
+ const refRoot = IsRecursiveAnchorTrue(stackframe.lexicalSchema) ? stackframe.recursiveAnchors[0] : stackframe.lexicalSchema;
+ return Ref(stackframe.context, refRoot, stackframe.lexicalBase, recursiveRef.$recursiveRef, false);
+}
+function ResolveDynamicRef(stackframe, dynamicRef) {
+ return DynamicRef(stackframe.context, stackframe.root, stackframe.lexicalBase, stackframe.lexicalSchema, dynamicRef, stackframe.dynamicAnchors);
+}
+
+// node_modules/typebox/build/schema/engine/_stack.mjs
+var __classPrivateFieldGet2 = function(receiver, state3, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state3 === "function" ? receiver !== state3 || !f : !state3.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state3.get(receiver);
+};
+var _Stack_instances;
+var _Stack_StackFrame;
+var _Stack_ApplyRefResult;
+var _Stack_BuildBase;
+var _Stack_ResourceBaseURL;
+var _Stack_ReferenceBaseURL;
+var _Stack_LexicalSchema;
+var _Stack_RegisterResourceAnchorArray;
+var _Stack_UnregisterResourceAnchorArray;
+var _Stack_RegisterResourceAnchors;
+var _Stack_UnregisterResourceAnchors;
+var _Stack_RegisterResource;
+var _Stack_UnregisterResource;
+var _Stack_EnterResolvedResource;
+var _Stack_ExitResolvedResource;
+var Stack = class {
+ constructor(context, schema) {
+ _Stack_instances.add(this);
+ this.context = context;
+ this.schema = schema;
+ this.ids = [];
+ this.resourceIds = [];
+ this.anchors = [];
+ this.recursiveAnchors = [];
+ this.dynamicAnchors = [];
+ this.retrievedResources = /* @__PURE__ */ new Map();
+ this.retrievedFrames = [];
+ this.resolvedResources = /* @__PURE__ */ new Map();
+ this.pendingResource = true;
+ }
+ // ----------------------------------------------------------------
+ // LexicalBaseURL
+ // ----------------------------------------------------------------
+ LexicalBaseURL() {
+ return __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_BuildBase).call(this, this.ids);
+ }
+ // ----------------------------------------------------------------
+ // Push
+ // ----------------------------------------------------------------
+ Push(schema) {
+ if (!IsSchemaObject(schema))
+ return;
+ if (IsId(schema))
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_RegisterResource).call(this, schema);
+ if (IsAnchor(schema))
+ this.anchors.push(schema);
+ if (IsRecursiveAnchorTrue(schema))
+ this.recursiveAnchors.push(schema);
+ if (IsDynamicAnchor(schema))
+ this.dynamicAnchors.push(schema);
+ const retrievedResource = this.retrievedResources.get(schema);
+ if (retrievedResource) {
+ this.retrievedFrames.push({
+ schema: retrievedResource.root,
+ base: retrievedResource.base,
+ idDepth: this.ids.length,
+ resourceDepth: this.resourceIds.length
+ });
+ }
+ }
+ // ----------------------------------------------------------------
+ // Pop
+ // ----------------------------------------------------------------
+ Pop(schema) {
+ if (!IsSchemaObject(schema))
+ return;
+ if (IsId(schema))
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_UnregisterResource).call(this, schema);
+ if (IsAnchor(schema))
+ this.anchors.pop();
+ if (IsRecursiveAnchorTrue(schema))
+ this.recursiveAnchors.pop();
+ if (IsDynamicAnchor(schema))
+ this.dynamicAnchors.pop();
+ if (this.retrievedResources.has(schema))
+ this.retrievedFrames.pop();
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_ExitResolvedResource).call(this, schema);
+ }
+ // ----------------------------------------------------------------
+ // Ref
+ // ----------------------------------------------------------------
+ Ref(ref) {
+ const result = resolve_exports.ResolveRef(__classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_StackFrame).call(this), ref);
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_ApplyRefResult).call(this, result);
+ return result.schema;
+ }
+ // ----------------------------------------------------------------
+ // RecursiveRef
+ // ----------------------------------------------------------------
+ RecursiveRef(recursiveRef) {
+ const result = resolve_exports.ResolveRecursiveRef(__classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_StackFrame).call(this), recursiveRef);
+ if (result)
+ this.pendingResource = true;
+ return result;
+ }
+ // ----------------------------------------------------------------
+ // DynamicRef
+ // ----------------------------------------------------------------
+ DynamicRef(dynamicRef) {
+ const result = resolve_exports.ResolveDynamicRef(__classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_StackFrame).call(this), dynamicRef);
+ if (result)
+ this.pendingResource = true;
+ return result;
+ }
+};
+_Stack_instances = /* @__PURE__ */ new WeakSet(), _Stack_StackFrame = function _Stack_StackFrame2() {
+ return {
+ context: this.context,
+ root: this.schema,
+ ids: this.ids,
+ lexicalSchema: __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_LexicalSchema).call(this),
+ lexicalBase: this.LexicalBaseURL(),
+ referenceBase: __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_ReferenceBaseURL).call(this),
+ resourceBase: __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_ResourceBaseURL).call(this),
+ recursiveAnchors: this.recursiveAnchors,
+ dynamicAnchors: this.dynamicAnchors,
+ inRetrievedFrame: this.retrievedFrames.length > 0
+ };
+}, _Stack_ApplyRefResult = function _Stack_ApplyRefResult2(result) {
+ if (!guard_exports.IsUndefined(result.schema))
+ this.pendingResource = true;
+ if (!guard_exports.IsUndefined(result.resolvedResource)) {
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_EnterResolvedResource).call(this, result.resolvedResource.target, result.resolvedResource.resource);
+ }
+ if (!guard_exports.IsUndefined(result.retrievedResource)) {
+ this.retrievedResources.set(result.retrievedResource.target, {
+ base: result.retrievedResource.base,
+ root: result.retrievedResource.root
+ });
+ }
+}, _Stack_BuildBase = function _Stack_BuildBase2(stack) {
+ const frame = this.retrievedFrames[this.retrievedFrames.length - 1];
+ const base = frame ? new URL(frame.base) : new URL(resolve_exports.DefaultBase);
+ const scoped = frame ? stack.slice(frame.idDepth) : stack;
+ return scoped.reduce((result, schema) => new URL(schema.$id, result), base).href;
+}, _Stack_ResourceBaseURL = function _Stack_ResourceBaseURL2() {
+ const frame = this.retrievedFrames[this.retrievedFrames.length - 1];
+ if (!frame)
+ return __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_BuildBase).call(this, this.resourceIds);
+ return this.resourceIds.slice(frame.resourceDepth).reduce((result, schema) => new URL(schema.$id, result), new URL(frame.base)).href;
+}, _Stack_ReferenceBaseURL = function _Stack_ReferenceBaseURL2() {
+ if (this.retrievedFrames.length > 0)
+ return __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_ResourceBaseURL).call(this);
+ const lexical = this.ids[this.ids.length - 1];
+ if (lexical && !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(lexical.$id))
+ return this.LexicalBaseURL();
+ return __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_ResourceBaseURL).call(this);
+}, _Stack_LexicalSchema = function _Stack_LexicalSchema2() {
+ const frame = this.retrievedFrames[this.retrievedFrames.length - 1];
+ if (frame)
+ return this.ids.length > frame.idDepth ? this.ids[this.ids.length - 1] : frame.schema;
+ return this.ids.length > 0 ? this.ids[this.ids.length - 1] : this.schema;
+}, _Stack_RegisterResourceAnchorArray = function _Stack_RegisterResourceAnchorArray2(schema) {
+ schema.forEach((schema2) => __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_RegisterResourceAnchors).call(this, schema2, false));
+}, _Stack_UnregisterResourceAnchorArray = function _Stack_UnregisterResourceAnchorArray2(schema) {
+ schema.forEach((schema2) => __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_UnregisterResourceAnchors).call(this, schema2, false));
+}, _Stack_RegisterResourceAnchors = function _Stack_RegisterResourceAnchors2(schema, isRoot = true) {
+ if (IsSchemaBoolean(schema))
+ return;
+ if (guard_exports.IsArray(schema))
+ return __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_RegisterResourceAnchorArray).call(this, schema);
+ if (!IsSchemaObject(schema))
+ return;
+ const current = schema;
+ if (!isRoot && IsId(current))
+ return;
+ if (!isRoot && IsDynamicAnchor(current))
+ this.dynamicAnchors.push(current);
+ for (const key of guard_exports.Keys(current))
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_RegisterResourceAnchors2).call(this, current[key], false);
+}, _Stack_UnregisterResourceAnchors = function _Stack_UnregisterResourceAnchors2(schema, isRoot = true) {
+ if (IsSchemaBoolean(schema))
+ return;
+ if (guard_exports.IsArray(schema))
+ return __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_UnregisterResourceAnchorArray).call(this, schema);
+ if (!IsSchemaObject(schema))
+ return;
+ const current = schema;
+ if (!isRoot && IsId(current))
+ return;
+ if (!isRoot && IsDynamicAnchor(current))
+ this.dynamicAnchors.pop();
+ for (const key of guard_exports.Keys(current))
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_UnregisterResourceAnchors2).call(this, current[key], false);
+}, _Stack_RegisterResource = function _Stack_RegisterResource2(schema) {
+ this.ids.push(schema);
+ const isResource = this.pendingResource;
+ this.pendingResource = false;
+ if (isResource)
+ this.resourceIds.push(schema);
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_RegisterResourceAnchors).call(this, schema, true);
+}, _Stack_UnregisterResource = function _Stack_UnregisterResource2(schema) {
+ this.ids.pop();
+ const isResource = this.resourceIds.length > 0 && guard_exports.IsEqual(this.resourceIds[this.resourceIds.length - 1], schema);
+ if (isResource)
+ this.resourceIds.pop();
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_UnregisterResourceAnchors).call(this, schema, true);
+}, _Stack_EnterResolvedResource = function _Stack_EnterResolvedResource2(target, resource) {
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_RegisterResource).call(this, resource);
+ this.resolvedResources.set(target, resource);
+}, _Stack_ExitResolvedResource = function _Stack_ExitResolvedResource2(target) {
+ if (!this.resolvedResources.has(target))
+ return;
+ const resource = this.resolvedResources.get(target);
+ __classPrivateFieldGet2(this, _Stack_instances, "m", _Stack_UnregisterResource).call(this, resource);
+ this.resolvedResources.delete(target);
+};
+
+// node_modules/typebox/build/system/environment/environment.mjs
+var environment_exports = {};
+__export(environment_exports, {
+ CanEvaluate: () => CanEvaluate,
+ Evaluate: () => Evaluate
+});
+
+// node_modules/typebox/build/system/environment/evaluate.mjs
+var supported = void 0;
+function TryEvaluate() {
+ try {
+ Evaluate("null")();
+ return true;
+ } catch {
+ return false;
+ }
+}
+function CanEvaluate() {
+ if (guard_exports.IsUndefined(supported))
+ supported = TryEvaluate();
+ return supported && settings_exports.Get().useAcceleration;
+}
+function Evaluate(...args) {
+ return new globalThis.Function(...args);
+}
+
+// node_modules/typebox/build/system/locale/en_US.mjs
+function en_US(error) {
+ switch (error.keyword) {
+ case "additionalProperties":
+ return "must not have additional properties";
+ case "anyOf":
+ return "must match a schema in anyOf";
+ case "boolean":
+ return "schema is false";
+ case "const":
+ return "must be equal to constant";
+ case "contains":
+ return "must contain at least 1 valid item";
+ case "dependencies":
+ return `must have properties ${error.params.dependencies.join(", ")} when property ${error.params.property} is present`;
+ case "dependentRequired":
+ return `must have properties ${error.params.dependencies.join(", ")} when property ${error.params.property} is present`;
+ case "enum":
+ return "must be equal to one of the allowed values";
+ case "exclusiveMaximum":
+ return `must be ${error.params.comparison} ${error.params.limit}`;
+ case "exclusiveMinimum":
+ return `must be ${error.params.comparison} ${error.params.limit}`;
+ case "format":
+ return `must match format "${error.params.format}"`;
+ case "if":
+ return `must match "${error.params.failingKeyword}" schema`;
+ case "maxItems":
+ return `must not have more than ${error.params.limit} items`;
+ case "maxLength":
+ return `must not have more than ${error.params.limit} characters`;
+ case "maxProperties":
+ return `must not have more than ${error.params.limit} properties`;
+ case "maximum":
+ return `must be ${error.params.comparison} ${error.params.limit}`;
+ case "minItems":
+ return `must not have fewer than ${error.params.limit} items`;
+ case "minLength":
+ return `must not have fewer than ${error.params.limit} characters`;
+ case "minProperties":
+ return `must not have fewer than ${error.params.limit} properties`;
+ case "minimum":
+ return `must be ${error.params.comparison} ${error.params.limit}`;
+ case "multipleOf":
+ return `must be multiple of ${error.params.multipleOf}`;
+ case "not":
+ return "must not be valid";
+ case "oneOf":
+ return "must match exactly one schema in oneOf";
+ case "pattern":
+ return `must match pattern "${error.params.pattern}"`;
+ case "propertyNames":
+ return `property names ${error.params.propertyNames.join(", ")} are invalid`;
+ case "required":
+ return `must have required properties ${error.params.requiredProperties.join(", ")}`;
+ case "type":
+ return typeof error.params.type === "string" ? `must be ${error.params.type}` : `must be either ${error.params.type.join(" or ")}`;
+ case "unevaluatedItems":
+ return "must not have unevaluated items";
+ case "unevaluatedProperties":
+ return "must not have unevaluated properties";
+ case "uniqueItems":
+ return `must not have duplicate items`;
+ case "~refine":
+ return error.params.message;
+ // deno-coverage-ignore - unreachable
+ default:
+ return "an unknown validation error occurred";
+ }
+}
+
+// node_modules/typebox/build/system/locale/_config.mjs
+var locale = en_US;
+function Get4() {
+ return locale;
+}
+
+// node_modules/typebox/build/system/memory/memory.mjs
+var memory_exports = {};
+__export(memory_exports, {
+ Assign: () => Assign,
+ Clone: () => Clone,
+ Create: () => Create,
+ Discard: () => Discard,
+ Metrics: () => Metrics,
+ Update: () => Update
+});
+
+// node_modules/typebox/build/system/memory/metrics.mjs
+var Metrics = {
+ assign: 0,
+ create: 0,
+ clone: 0,
+ discard: 0,
+ update: 0
+};
+
+// node_modules/typebox/build/system/memory/freeze.mjs
+function Freeze(value) {
+ return settings_exports.Get().immutableTypes ? Object.freeze(value) : value;
+}
+
+// node_modules/typebox/build/system/memory/assign.mjs
+function Assign(left, right) {
+ Metrics.assign += 1;
+ return Freeze({ ...left, ...right });
+}
+
+// node_modules/typebox/build/system/memory/clone.mjs
+function FromClassInstance(value) {
+ return value;
+}
+function IsSchemaObject2(value) {
+ return guard_exports.HasPropertyKey(value, "~kind") || guard_exports.HasPropertyKey(value, "~unsafe");
+}
+function FromSchemaObject(value) {
+ const result = {};
+ for (const key of guard_exports.Keys(value)) {
+ if (guard_exports.IsUnsafePropertyKey(key))
+ continue;
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
+ descriptor.value = FromValue3(descriptor.value);
+ if (guard_exports.IsEqual(descriptor.enumerable, true)) {
+ result[key] = descriptor.value;
+ } else {
+ Object.defineProperty(result, key, descriptor);
+ }
+ }
+ return result;
+}
+function FromPlainObject(value) {
+ const result = {};
+ for (const key of guard_exports.Keys(value)) {
+ if (guard_exports.IsUnsafePropertyKey(key))
+ continue;
+ result[key] = FromValue3(value[key]);
+ }
+ for (const key of guard_exports.Symbols(value)) {
+ result[key] = FromValue3(value[key]);
+ }
+ return result;
+}
+function FromObject3(value) {
+ return guard_exports.IsClassInstance(value) ? FromClassInstance(value) : IsSchemaObject2(value) ? FromSchemaObject(value) : FromPlainObject(value);
+}
+function FromArray3(value) {
+ return value.map((element) => FromValue3(element));
+}
+function FromTypedArray(value) {
+ return value.slice();
+}
+function FromRegExp2(value) {
+ return new RegExp(value.source, value.flags);
+}
+function FromMap(value) {
+ return new Map(FromValue3([...value.entries()]));
+}
+function FromSet(value) {
+ return new Set(FromValue3([...value.values()]));
+}
+function FromValue3(value) {
+ return globals_exports.IsTypeArray(value) ? FromTypedArray(value) : globals_exports.IsRegExp(value) ? FromRegExp2(value) : globals_exports.IsMap(value) ? FromMap(value) : globals_exports.IsSet(value) ? FromSet(value) : guard_exports.IsArray(value) ? FromArray3(value) : guard_exports.IsObject(value) ? FromObject3(value) : value;
+}
+function Clone(value) {
+ Metrics.clone += 1;
+ return FromValue3(value);
+}
+
+// node_modules/typebox/build/system/memory/create.mjs
+function MergeHidden(left, right) {
+ for (const key of Object.keys(right)) {
+ Object.defineProperty(left, key, {
+ configurable: true,
+ writable: true,
+ enumerable: false,
+ value: right[key]
+ });
+ }
+ return left;
+}
+function Merge(left, right) {
+ return { ...left, ...right };
+}
+function Create(hidden, enumerable, options = {}) {
+ Metrics.create += 1;
+ const withOptions = Merge(enumerable, options);
+ const withHidden = settings_exports.Get().enumerableKind ? Merge(withOptions, hidden) : MergeHidden(withOptions, hidden);
+ return Freeze(withHidden);
+}
+
+// node_modules/typebox/build/system/memory/discard.mjs
+function Discard(value, propertyKeys) {
+ Metrics.discard += 1;
+ const result = {};
+ for (const key of guard_exports.Keys(value)) {
+ if (propertyKeys.includes(key))
+ continue;
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
+ descriptor.value = Clone(descriptor.value);
+ Object.defineProperty(result, key, descriptor);
+ }
+ return Freeze(result);
+}
+
+// node_modules/typebox/build/system/memory/update.mjs
+function Update(current, hidden, enumerable) {
+ Metrics.update += 1;
+ const settings2 = settings_exports.Get();
+ const result = Clone(current);
+ for (const key of Object.keys(hidden)) {
+ Object.defineProperty(result, key, {
+ configurable: true,
+ writable: true,
+ enumerable: settings2.enumerableKind,
+ value: hidden[key]
+ });
+ }
+ for (const key of Object.keys(enumerable)) {
+ Object.defineProperty(result, key, {
+ configurable: true,
+ enumerable: true,
+ writable: true,
+ value: enumerable[key]
+ });
+ }
+ return Freeze(result);
+}
+
+// node_modules/typebox/build/schema/build.mjs
+function CreateCode(build) {
+ const functions = build.Functions().join(";\n");
+ const statements = build.UseUnevaluated() ? ["const context = new CheckContext({}, {})", `return ${build.Entry()}`] : [`return ${build.Entry()}`];
+ return `${functions}; return (value) => { ${statements.join("; ")} }`;
+}
+function CreateEvaluatedCheck(build, code) {
+ const factory = environment_exports.Evaluate("CheckContext", "Guard", "Format", "Hashing", build.External().identifier, code);
+ return factory(CheckContext, guard_exports, format_exports, hash_exports, build.External().variables);
+}
+function CreateDynamicCheck(build) {
+ const stack = new Stack(build.Context(), build.Schema());
+ const context = new CheckContext();
+ return (value) => CheckSchema(stack, context, build.Schema(), value);
+}
+function CreateCheck(build, code) {
+ return environment_exports.CanEvaluate() ? CreateEvaluatedCheck(build, code) : CreateDynamicCheck(build);
+}
+var EvaluateResult = class {
+ constructor(isAccelerated, code, check) {
+ this.isAccelerated = isAccelerated;
+ this.code = code;
+ this.check = check;
+ }
+ IsAccelerated() {
+ return this.isAccelerated;
+ }
+ Code() {
+ return this.code;
+ }
+ Check(value) {
+ return this.check(value);
+ }
+};
+var BuildResult = class {
+ constructor(context, schema, external, functions, entry, useUnevaluated) {
+ this.context = context;
+ this.schema = schema;
+ this.external = external;
+ this.functions = functions;
+ this.entry = entry;
+ this.useUnevaluated = useUnevaluated;
+ }
+ /** Returns the Context used for this build */
+ Context() {
+ return this.context;
+ }
+ /** Returns the Schema used for this build */
+ Schema() {
+ return this.schema;
+ }
+ /** Returns true if this build requires a Unevaluated context */
+ UseUnevaluated() {
+ return this.useUnevaluated;
+ }
+ /** Returns external variables */
+ External() {
+ return this.external;
+ }
+ /** Returns check functions */
+ Functions() {
+ return this.functions;
+ }
+ /** Return entry function call. */
+ Entry() {
+ return this.entry;
+ }
+ /** Evaluates the build into a validation function */
+ Evaluate() {
+ const code = CreateCode(this);
+ const check = CreateCheck(this, code);
+ return new EvaluateResult(environment_exports.CanEvaluate(), code, check);
+ }
+};
+function Build(...args) {
+ const [context, schema] = arguments_exports.Match(args, {
+ 2: (context2, schema2) => [context2, schema2],
+ 1: (schema2) => [{}, schema2]
+ });
+ ResetExternal();
+ ResetFunctions();
+ const stack = new Stack(context, schema);
+ const build = new BuildContext(HasUnevaluated(context, schema));
+ const call = CreateFunction(stack, build, schema, "value");
+ const functions = GetFunctions();
+ const externals = GetExternal();
+ return new BuildResult(context, schema, externals, functions, call, build.UseUnevaluated());
+}
+
+// node_modules/typebox/build/schema/errors.mjs
+function Errors(...args) {
+ const [context, schema, value] = arguments_exports.Match(args, {
+ 3: (context2, schema2, value2) => [context2, schema2, value2],
+ 2: (schema2, value2) => [{}, schema2, value2]
+ });
+ const stack = new Stack(context, schema);
+ const errorContext = new ErrorContext();
+ const result = ErrorSchema(stack, errorContext, "#", "", schema, value);
+ const errors = errorContext.GetErrors();
+ const locale2 = Get4();
+ const localized = errors.map((error) => ({ ...error, message: locale2(error) }));
+ return [result, localized];
+}
+
+// node_modules/typebox/build/schema/check.mjs
+function Check(...args) {
+ const [context, schema, value] = arguments_exports.Match(args, {
+ 3: (context2, schema2, value2) => [context2, schema2, value2],
+ 2: (schema2, value2) => [{}, schema2, value2]
+ });
+ const stack = new Stack(context, schema);
+ const checkContext = new CheckContext();
+ return CheckSchema(stack, checkContext, schema, value);
+}
+
+// node_modules/typebox/build/value/check/check.mjs
+function Check2(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ return Check(context, type, value);
+}
+
+// node_modules/typebox/build/value/errors/errors.mjs
+function Errors2(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ const [_, errors] = Errors(context, type, value);
+ return errors;
+}
+
+// node_modules/typebox/build/value/assert/assert.mjs
+var AssertError = class extends Error {
+ constructor(source, value, errors) {
+ super(source);
+ Object.defineProperty(this, "cause", {
+ value: { source, errors, value },
+ writable: false,
+ configurable: false,
+ enumerable: false
+ });
+ }
+};
+function Assert(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ const check = Check2(context, type, value);
+ if (!check)
+ throw new AssertError("Assert", value, Errors2(context, type, value));
+}
+
+// node_modules/typebox/build/type/types/schema.mjs
+function IsKind(value, kind) {
+ return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, "~kind") && guard_exports.IsEqual(value["~kind"], kind);
+}
+function IsSchema2(value) {
+ return guard_exports.IsObject(value);
+}
+
+// node_modules/typebox/build/type/types/deferred.mjs
+function Deferred(action, parameters, options) {
+ return memory_exports.Create({ "~kind": "Deferred" }, { type: "deferred", action, parameters, options }, {});
+}
+function IsDeferred(value) {
+ return IsKind(value, "Deferred");
+}
+
+// node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs
+function AddReadonlyOperation(type) {
+ return memory_exports.Update(type, { "~readonly": true }, {});
+}
+function AddReadonlyAction(type, options) {
+ const result = memory_exports.Update(AddReadonlyOperation(type), {}, options);
+ return result;
+}
+function AddReadonlyInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return AddReadonlyAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/engine/optional/instantiate_add.mjs
+function AddOptionalOperation(type) {
+ return memory_exports.Update(type, { "~optional": true }, {});
+}
+function AddOptionalAction(type, options) {
+ const result = memory_exports.Update(AddOptionalOperation(type), {}, options);
+ return result;
+}
+function AddOptionalInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return AddOptionalAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/types/array.mjs
+function _Array_(items, options) {
+ return memory_exports.Create({ "~kind": "Array" }, { type: "array", items }, options);
+}
+function IsArray3(value) {
+ return IsKind(value, "Array");
+}
+function ArrayOptions(type) {
+ return memory_exports.Discard(type, ["~kind", "type", "items"]);
+}
+
+// node_modules/typebox/build/type/types/constructor.mjs
+function Constructor(parameters, instanceType, options = {}) {
+ return memory_exports.Create({ "~kind": "Constructor" }, { type: "constructor", parameters, instanceType }, options);
+}
+function IsConstructor3(value) {
+ return IsKind(value, "Constructor");
+}
+function ConstructorOptions(type) {
+ return memory_exports.Discard(type, ["~kind", "type", "parameters", "instanceType"]);
+}
+
+// node_modules/typebox/build/type/types/function.mjs
+function _Function_(parameters, returnType, options = {}) {
+ return memory_exports.Create({ ["~kind"]: "Function" }, { type: "function", parameters, returnType }, options);
+}
+function IsFunction3(value) {
+ return IsKind(value, "Function");
+}
+function FunctionOptions(type) {
+ return memory_exports.Discard(type, ["~kind", "type", "parameters", "returnType"]);
+}
+
+// node_modules/typebox/build/type/types/ref.mjs
+function Ref2(ref, options) {
+ return memory_exports.Create({ ["~kind"]: "Ref" }, { $ref: ref }, options);
+}
+function IsRef2(value) {
+ return IsKind(value, "Ref");
+}
+
+// node_modules/typebox/build/type/types/generic.mjs
+function Generic(parameters, expression) {
+ return memory_exports.Create({ "~kind": "Generic" }, { type: "generic", parameters, expression });
+}
+function IsGeneric(value) {
+ return IsKind(value, "Generic");
+}
+
+// node_modules/typebox/build/type/types/any.mjs
+function Any(options) {
+ return memory_exports.Create({ ["~kind"]: "Any" }, {}, options);
+}
+function IsAny(value) {
+ return IsKind(value, "Any");
+}
+
+// node_modules/typebox/build/type/types/never.mjs
+var NeverPattern = "(?!)";
+function Never(options) {
+ return memory_exports.Create({ "~kind": "Never" }, { not: {} }, options);
+}
+function IsNever(value) {
+ return IsKind(value, "Never");
+}
+
+// node_modules/typebox/build/type/action/_add_optional.mjs
+function AddOptionalDeferred(type, options = {}) {
+ return Deferred("AddOptional", [type], options);
+}
+function AddOptional(type, options = {}) {
+ return AddOptionalAction(type, options);
+}
+
+// node_modules/typebox/build/type/types/_optional.mjs
+function Optional(type) {
+ return AddOptional(type);
+}
+function IsOptional(value) {
+ return IsSchema2(value) && guard_exports.HasPropertyKey(value, "~optional");
+}
+
+// node_modules/typebox/build/type/types/properties.mjs
+function RequiredArray(properties) {
+ return guard_exports.Keys(properties).filter((key) => !IsOptional(properties[key]));
+}
+function PropertyKeys(properties) {
+ return guard_exports.Keys(properties);
+}
+function PropertyValues(properties) {
+ return guard_exports.Values(properties);
+}
+
+// node_modules/typebox/build/type/types/object.mjs
+function _Object_(properties, options = {}) {
+ const requiredKeys = RequiredArray(properties);
+ const required = requiredKeys.length > 0 ? { required: requiredKeys } : {};
+ return memory_exports.Create({ "~kind": "Object" }, { type: "object", ...required, properties }, options);
+}
+function IsObject3(value) {
+ return IsKind(value, "Object");
+}
+function ObjectOptions(type) {
+ return memory_exports.Discard(type, ["~kind", "type", "properties", "required"]);
+}
+
+// node_modules/typebox/build/type/types/unknown.mjs
+function Unknown(options) {
+ return memory_exports.Create({ ["~kind"]: "Unknown" }, {}, options);
+}
+function IsUnknown(value) {
+ return IsKind(value, "Unknown");
+}
+
+// node_modules/typebox/build/type/types/cyclic.mjs
+function Cyclic($defs, $ref, options) {
+ const defs = guard_exports.Keys($defs).reduce((result, key) => {
+ return { ...result, [key]: memory_exports.Update($defs[key], {}, { $id: key }) };
+ }, {});
+ return memory_exports.Create({ ["~kind"]: "Cyclic" }, { $defs: defs, $ref }, options);
+}
+function IsCyclic(value) {
+ return IsKind(value, "Cyclic");
+}
+
+// node_modules/typebox/build/type/types/unsafe.mjs
+function Unsafe(schema) {
+ return memory_exports.Update(schema, { ["~unsafe"]: null }, {});
+}
+function IsUnsafe(value) {
+ return guard_exports.IsObjectNotArray(value) && guard_exports.HasPropertyKey(value, "~unsafe") && guard_exports.IsNull(value["~unsafe"]);
+}
+
+// node_modules/typebox/build/type/types/infer.mjs
+function Infer(...args) {
+ const [name, extends_] = arguments_exports.Match(args, {
+ 2: (name2, extends_2) => [name2, extends_2, extends_2],
+ 1: (name2) => [name2, Unknown(), Unknown()]
+ });
+ return memory_exports.Create({ ["~kind"]: "Infer" }, { type: "infer", name, extends: extends_ }, {});
+}
+function IsInfer(value) {
+ return IsKind(value, "Infer");
+}
+
+// node_modules/typebox/build/type/types/dependent.mjs
+function Dependent(if_, then_, else_, options = {}) {
+ return memory_exports.Create({ "~kind": "Dependent" }, { if: if_, then: then_, else: else_ }, options);
+}
+function IsDependent(value) {
+ return IsKind(value, "Dependent");
+}
+function DependentOptions(type) {
+ return memory_exports.Discard(type, ["~kind", "if", "then", "else"]);
+}
+
+// node_modules/typebox/build/type/engine/enum/typescript_enum_to_enum_values.mjs
+function IsTypeScriptEnumLike(value) {
+ return guard_exports.IsObjectNotArray(value);
+}
+function TypeScriptEnumToEnumValues(type) {
+ const keys = guard_exports.Keys(type).filter((key) => isNaN(key));
+ return keys.reduce((result, key) => [...result, type[key]], []);
+}
+
+// node_modules/typebox/build/type/types/enum.mjs
+function IsEnumValue(value) {
+ return guard_exports.IsString(value) || guard_exports.IsNumber(value);
+}
+function Enum(value, options) {
+ const values = IsTypeScriptEnumLike(value) ? TypeScriptEnumToEnumValues(value) : value;
+ return memory_exports.Create({ "~kind": "Enum" }, { enum: values }, options);
+}
+function IsEnum2(value) {
+ return IsKind(value, "Enum");
+}
+
+// node_modules/typebox/build/type/types/intersect.mjs
+function Intersect(types, options = {}) {
+ return memory_exports.Create({ "~kind": "Intersect" }, { allOf: types }, options);
+}
+function IsIntersect(value) {
+ return IsKind(value, "Intersect");
+}
+function IntersectOptions(type) {
+ return memory_exports.Discard(type, ["~kind", "allOf"]);
+}
+
+// node_modules/typebox/build/type/types/_codec.mjs
+var EncodeBuilder = class {
+ constructor(type, decode) {
+ this.type = type;
+ this.decode = decode;
+ }
+ Encode(callback) {
+ const type = this.type;
+ const decode = IsCodec(type) ? (value) => this.decode(type["~codec"].decode(value)) : this.decode;
+ const encode2 = IsCodec(type) ? (value) => type["~codec"].encode(callback(value)) : callback;
+ const codec = { decode, encode: encode2 };
+ return memory_exports.Update(this.type, { "~codec": codec }, {});
+ }
+};
+var DecodeBuilder = class {
+ constructor(type) {
+ this.type = type;
+ }
+ Decode(callback) {
+ return new EncodeBuilder(this.type, callback);
+ }
+};
+function Codec(type) {
+ return new DecodeBuilder(type);
+}
+function Decode2(type, callback) {
+ return Codec(type).Decode(callback).Encode(() => {
+ throw Error("Encode not implemented");
+ });
+}
+function Encode2(type, callback) {
+ return Codec(type).Decode(() => {
+ throw Error("Decode not implemented");
+ }).Encode(callback);
+}
+function IsCodec(value) {
+ return IsSchema2(value) && guard_exports.HasPropertyKey(value, "~codec") && guard_exports.IsObject(value["~codec"]) && guard_exports.HasPropertyKey(value["~codec"], "encode") && guard_exports.HasPropertyKey(value["~codec"], "decode");
+}
+
+// node_modules/typebox/build/type/types/_immutable.mjs
+function Immutable(type) {
+ return AddImmutable(type);
+}
+function IsImmutable(value) {
+ return IsSchema2(value) && guard_exports.HasPropertyKey(value, "~immutable");
+}
+
+// node_modules/typebox/build/type/action/_add_readonly.mjs
+function AddReadonlyDeferred(type, options = {}) {
+ return Deferred("AddReadonly", [type], options);
+}
+function AddReadonly(type, options = {}) {
+ return AddReadonlyAction(type, options);
+}
+
+// node_modules/typebox/build/type/types/_readonly.mjs
+function Readonly(type) {
+ return AddReadonly(type);
+}
+function IsReadonly(value) {
+ return IsSchema2(value) && guard_exports.HasPropertyKey(value, "~readonly");
+}
+
+// node_modules/typebox/build/type/types/_refine.mjs
+function RefineAdd(type, refinement) {
+ const refinements = IsRefine2(type) ? [...type["~refine"], refinement] : [refinement];
+ return memory_exports.Update(type, { "~refine": refinements }, {});
+}
+function Refine(...args) {
+ const [type, check, error] = arguments_exports.Match(args, {
+ 3: (type2, check2, error2) => [type2, check2, error2],
+ 2: (type2, check2) => [type2, check2, () => "Refine Error"]
+ });
+ return RefineAdd(type, { check, error });
+}
+function IsRefinement(value) {
+ return guard_exports.IsObjectNotArray(value) && guard_exports.HasPropertyKey(value, "check") && guard_exports.HasPropertyKey(value, "error") && guard_exports.IsFunction(value.check) && guard_exports.IsFunction(value.error);
+}
+function IsRefine2(value) {
+ return IsSchema2(value) && guard_exports.HasPropertyKey(value, "~refine") && guard_exports.IsArray(value["~refine"]) && guard_exports.Every(value["~refine"], 0, (value2) => IsRefinement(value2));
+}
+
+// node_modules/typebox/build/type/types/bigint.mjs
+var BigIntPattern = "-?(?:0|[1-9][0-9]*)n";
+function BigInt2(options) {
+ return memory_exports.Create({ "~kind": "BigInt" }, { type: "bigint" }, options);
+}
+function IsBigInt3(value) {
+ return IsKind(value, "BigInt");
+}
+
+// node_modules/typebox/build/type/types/boolean.mjs
+function Boolean2(options) {
+ return memory_exports.Create({ "~kind": "Boolean" }, { type: "boolean" }, options);
+}
+function IsBoolean4(value) {
+ return IsKind(value, "Boolean");
+}
+
+// node_modules/typebox/build/type/types/identifier.mjs
+function Identifier(name) {
+ return memory_exports.Create({ "~kind": "Identifier" }, { name });
+}
+function IsIdentifier2(value) {
+ return IsKind(value, "Identifier");
+}
+
+// node_modules/typebox/build/type/types/integer.mjs
+var IntegerPattern = "-?(?:0|[1-9][0-9]*)";
+function Integer(options) {
+ return memory_exports.Create({ "~kind": "Integer" }, { type: "integer" }, options);
+}
+function IsInteger3(value) {
+ return IsKind(value, "Integer");
+}
+
+// node_modules/typebox/build/type/types/literal.mjs
+var InvalidLiteralValue = class extends Error {
+ constructor(value) {
+ super(`Invalid Literal value`);
+ Object.defineProperty(this, "cause", {
+ value: { value },
+ writable: false,
+ configurable: false,
+ enumerable: false
+ });
+ }
+};
+function LiteralTypeName(value) {
+ return guard_exports.IsBigInt(value) ? "bigint" : guard_exports.IsBoolean(value) ? "boolean" : guard_exports.IsNumber(value) ? "number" : guard_exports.IsString(value) ? "string" : (() => {
+ throw new InvalidLiteralValue(value);
+ })();
+}
+function Literal(value, options) {
+ return memory_exports.Create({ "~kind": "Literal" }, { type: LiteralTypeName(value), const: value }, options);
+}
+function IsLiteralValue(value) {
+ return guard_exports.IsBigInt(value) || guard_exports.IsBoolean(value) || guard_exports.IsNumber(value) || guard_exports.IsString(value);
+}
+function IsLiteralBigInt(value) {
+ return IsLiteral(value) && guard_exports.IsBigInt(value.const);
+}
+function IsLiteralBoolean(value) {
+ return IsLiteral(value) && guard_exports.IsBoolean(value.const);
+}
+function IsLiteralNumber(value) {
+ return IsLiteral(value) && guard_exports.IsNumber(value.const);
+}
+function IsLiteralString(value) {
+ return IsLiteral(value) && guard_exports.IsString(value.const);
+}
+function IsLiteral(value) {
+ return IsKind(value, "Literal");
+}
+
+// node_modules/typebox/build/type/types/null.mjs
+function Null(options) {
+ return memory_exports.Create({ "~kind": "Null" }, { type: "null" }, options);
+}
+function IsNull3(value) {
+ return IsKind(value, "Null");
+}
+
+// node_modules/typebox/build/type/types/number.mjs
+var NumberPattern = "-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";
+function Number2(options) {
+ return memory_exports.Create({ "~kind": "Number" }, { type: "number" }, options);
+}
+function IsNumber4(value) {
+ return IsKind(value, "Number");
+}
+
+// node_modules/typebox/build/type/types/symbol.mjs
+function Symbol2(options) {
+ return memory_exports.Create({ "~kind": "Symbol" }, { type: "symbol" }, options);
+}
+function IsSymbol3(value) {
+ return IsKind(value, "Symbol");
+}
+
+// node_modules/typebox/build/type/types/parameter.mjs
+function Parameter(...args) {
+ const [name, extends_, equals] = arguments_exports.Match(args, {
+ 3: (name2, extends_2, equals2) => [name2, extends_2, equals2],
+ 2: (name2, extends_2) => [name2, extends_2, extends_2],
+ 1: (name2) => [name2, Unknown(), Unknown()]
+ });
+ return memory_exports.Create({ "~kind": "Parameter" }, { name, extends: extends_, equals }, {});
+}
+function IsParameter(value) {
+ return IsKind(value, "Parameter");
+}
+
+// node_modules/typebox/build/type/types/string.mjs
+var StringPattern = ".*";
+function String2(options) {
+ return memory_exports.Create({ "~kind": "String" }, { type: "string" }, options);
+}
+function IsString4(value) {
+ return IsKind(value, "String");
+}
+
+// node_modules/typebox/build/type/types/union.mjs
+function Union(anyOf, options = {}) {
+ return memory_exports.Create({ "~kind": "Union" }, { anyOf }, options);
+}
+function IsUnion(value) {
+ return IsKind(value, "Union");
+}
+function UnionOptions(type) {
+ return memory_exports.Discard(type, ["~kind", "anyOf"]);
+}
+
+// node_modules/typebox/build/type/engine/patterns/pattern.mjs
+function ParsePatternIntoTypes(pattern) {
+ const parsed = Pattern(pattern);
+ const result = guard_exports.IsEqual(parsed.length, 2) ? parsed[0] : [];
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/template_literal/is_finite.mjs
+function FromLiteral(_value) {
+ return true;
+}
+function FromTypesReduce(types) {
+ return guard_exports.ShiftLeft(types, (left, right) => FromType(left) ? FromTypesReduce(right) : false, () => true);
+}
+function FromTypes(types) {
+ const result = guard_exports.IsEqual(types.length, 0) ? false : FromTypesReduce(types);
+ return result;
+}
+function FromType(type) {
+ return IsUnion(type) ? FromTypes(type.anyOf) : IsLiteral(type) ? FromLiteral(type.const) : false;
+}
+function IsTemplateLiteralFinite(types) {
+ const result = FromTypes(types);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/template_literal/create.mjs
+function TemplateLiteralCreate(pattern) {
+ return memory_exports.Create({ ["~kind"]: "TemplateLiteral" }, { type: "string", pattern }, {});
+}
+
+// node_modules/typebox/build/type/engine/template_literal/decode.mjs
+function FromLiteralPush(variants, value, result = []) {
+ return guard_exports.ShiftLeft(variants, (left, right) => FromLiteralPush(right, value, [...result, `${left}${value}`]), () => result);
+}
+function FromLiteral2(variants, value) {
+ return guard_exports.IsEqual(variants.length, 0) ? [`${value}`] : FromLiteralPush(variants, value);
+}
+function FromUnion(variants, types, result = []) {
+ return guard_exports.ShiftLeft(types, (left, right) => FromUnion(variants, right, [...result, ...FromType2(variants, left)]), () => result);
+}
+function FromType2(variants, type) {
+ const result = IsUnion(type) ? FromUnion(variants, type.anyOf) : IsLiteral(type) ? FromLiteral2(variants, type.const) : Unreachable();
+ return result;
+}
+function DecodeFromSpan(variants, types) {
+ return guard_exports.ShiftLeft(types, (left, right) => DecodeFromSpan(FromType2(variants, left), right), () => variants);
+}
+function VariantsToLiterals(variants) {
+ return variants.map((variant) => Literal(variant));
+}
+function DecodeTypesAsUnion(types) {
+ const variants = DecodeFromSpan([], types);
+ const literals = VariantsToLiterals(variants);
+ const result = Union(literals);
+ return result;
+}
+function DecodeTypes(types) {
+ return guard_exports.IsEqual(types.length, 0) ? Unreachable() : (
+ // Literal('') :
+ guard_exports.IsEqual(types.length, 1) && IsLiteral(types[0]) ? types[0] : DecodeTypesAsUnion(types)
+ );
+}
+function TemplateLiteralDecodeUnsafe(pattern) {
+ const types = ParsePatternIntoTypes(pattern);
+ const result = guard_exports.IsEqual(types.length, 0) ? String2() : IsTemplateLiteralFinite(types) ? DecodeTypes(types) : TemplateLiteralCreate(pattern);
+ return result;
+}
+function TemplateLiteralDecode(pattern) {
+ const decoded = TemplateLiteralDecodeUnsafe(pattern);
+ const result = IsTemplateLiteral(decoded) ? String2() : decoded;
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/record/record_create.mjs
+function CreateRecord(key, value) {
+ const type = "object";
+ const patternProperties = { [key]: value };
+ return memory_exports.Create({ ["~kind"]: "Record" }, { type, patternProperties });
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_any.mjs
+function FromAnyKey(value) {
+ return CreateRecord(StringKey, value);
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_boolean.mjs
+function FromBooleanKey(value) {
+ return _Object_({ true: value, false: value });
+}
+
+// node_modules/typebox/build/type/types/tuple.mjs
+function Tuple(types, options = {}) {
+ const [items, minItems, additionalItems] = [types, types.length, false];
+ return memory_exports.Create({ ["~kind"]: "Tuple" }, { type: "array", additionalItems, items, minItems }, options);
+}
+function IsTuple(value) {
+ return IsKind(value, "Tuple");
+}
+function TupleOptions(type) {
+ return memory_exports.Discard(type, ["~kind", "type", "items", "minItems", "additionalItems"]);
+}
+
+// node_modules/typebox/build/type/engine/readonly/instantiate_remove.mjs
+function RemoveReadonlyOperation(type) {
+ return memory_exports.Discard(type, ["~readonly"]);
+}
+function RemoveReadonlyAction(type, options) {
+ const result = memory_exports.Update(RemoveReadonlyOperation(type), {}, options);
+ return result;
+}
+function RemoveReadonlyInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return RemoveReadonlyAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/_remove_readonly.mjs
+function RemoveReadonlyDeferred(type, options = {}) {
+ return Deferred("RemoveReadonly", [type], options);
+}
+function RemoveReadonly(type, options = {}) {
+ return RemoveReadonlyAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/optional/instantiate_remove.mjs
+function RemoveOptionalOperation(type) {
+ return memory_exports.Discard(type, ["~optional"]);
+}
+function RemoveOptionalAction(type, options) {
+ const result = memory_exports.Update(RemoveOptionalOperation(type), {}, options);
+ return result;
+}
+function RemoveOptionalInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return RemoveOptionalAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/_remove_optional.mjs
+function RemoveOptionalDeferred(type, options = {}) {
+ return Deferred("RemoveOptional", [type], options);
+}
+function RemoveOptional(type, options = {}) {
+ return RemoveOptionalAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/tuple/to_object.mjs
+function TupleElementsToProperties(types) {
+ const result = types.reduceRight((result2, right, index3) => {
+ return { [index3]: right, ...result2 };
+ }, {});
+ return result;
+}
+function TupleToObject(type) {
+ const properties = TupleElementsToProperties(type.items);
+ const result = _Object_(properties);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/evaluate/composite.mjs
+function CanComposite(type) {
+ return IsObject3(type) || IsTuple(type);
+}
+function IsReadonlyProperty(left, right) {
+ return IsReadonly(left) ? IsReadonly(right) ? true : false : false;
+}
+function IsOptionalProperty(left, right) {
+ return IsOptional(left) ? IsOptional(right) ? true : false : false;
+}
+function CompositeProperty(left, right) {
+ const isReadonly = IsReadonlyProperty(left, right);
+ const isOptional = IsOptionalProperty(left, right);
+ const evaluated = EvaluateIntersect([left, right]);
+ const property = RemoveReadonly(RemoveOptional(evaluated));
+ return isReadonly && isOptional ? AddReadonly(AddOptional(property)) : isReadonly && !isOptional ? AddReadonly(property) : !isReadonly && isOptional ? AddOptional(property) : property;
+}
+function CompositePropertyKey(left, right, key) {
+ return key in left ? key in right ? CompositeProperty(left[key], right[key]) : left[key] : key in right ? right[key] : Never();
+}
+function CompositeProperties(left, right) {
+ const keys = /* @__PURE__ */ new Set([...guard_exports.Keys(left), ...guard_exports.Keys(right)]);
+ const result = [...keys].reduce((result2, key) => {
+ return { ...result2, [key]: CompositePropertyKey(left, right, key) };
+ }, {});
+ return result;
+}
+function GetProperties(type) {
+ const result = IsObject3(type) ? type.properties : IsTuple(type) ? TupleElementsToProperties(type.items) : {};
+ return result;
+}
+function Composite(left, right) {
+ const leftProperties = GetProperties(left);
+ const rightProperties = GetProperties(right);
+ const properties = CompositeProperties(leftProperties, rightProperties);
+ const result = _Object_(properties);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/evaluate/narrow.mjs
+function NarrowCompareRule(left, right) {
+ const result = Compare(left, right);
+ return guard_exports.IsEqual(result, CompareResultLeftInside) ? left : guard_exports.IsEqual(result, CompareResultRightInside) ? right : guard_exports.IsEqual(result, CompareResultEqual) ? right : Never();
+}
+function NarrowCompositeRule(left, right) {
+ const canCompositeLeft = CanComposite(left);
+ const canCompositeRight = CanComposite(right);
+ return canCompositeLeft && canCompositeRight ? Composite(left, right) : canCompositeLeft && !canCompositeRight ? left : !canCompositeLeft && canCompositeRight ? right : NarrowCompareRule(left, right);
+}
+function Narrow(left, right) {
+ return IsNever(left) ? left : IsAny(left) ? left : IsUnknown(left) ? right : IsNever(right) ? right : IsAny(right) ? right : IsUnknown(right) ? left : NarrowCompositeRule(left, right);
+}
+
+// node_modules/typebox/build/type/engine/evaluate/distribute.mjs
+function ShouldEvaluate(left, right) {
+ const result = IsUnion(left) || IsUnion(right);
+ return result;
+}
+function DistributeOperation(left, right) {
+ const evaluatedLeft = EvaluateType(left);
+ const evaluatedRight = EvaluateType(right);
+ const shouldEvaluate = ShouldEvaluate(evaluatedLeft, evaluatedRight);
+ const result = shouldEvaluate ? EvaluateIntersect([evaluatedLeft, evaluatedRight]) : Narrow(evaluatedLeft, evaluatedRight);
+ return result;
+}
+function DistributeType(type, types, result = []) {
+ return guard_exports.ShiftLeft(types, (left, right) => DistributeType(type, right, [...result, DistributeOperation(left, type)]), () => guard_exports.IsEqual(result.length, 0) ? [type] : result);
+}
+function DistributeUnion(types, distribution, result = []) {
+ return guard_exports.ShiftLeft(types, (left, right) => DistributeUnion(right, distribution, [...result, ...Distribute([left], distribution)]), () => result);
+}
+function Distribute(types, result = []) {
+ return guard_exports.ShiftLeft(types, (left, right) => IsUnion(left) ? Distribute(right, DistributeUnion(left.anyOf, result)) : Distribute(right, DistributeType(left, result)), () => result);
+}
+
+// node_modules/typebox/build/type/engine/exclude/operation.mjs
+function ExcludeType(left, right) {
+ const check = Extends({}, left, right);
+ const result = result_exports.IsExtendsTrueLike(check) ? [] : [left];
+ return result;
+}
+function ExcludeUnion(left, right, result = []) {
+ return guard_exports.ShiftLeft(left, (head, tail) => ExcludeUnion(tail, right, [...result, ...ExcludeType(head, right)]), () => result);
+}
+function ExcludeOperation(left, right) {
+ const evaluated = EvaluateType(left);
+ const canonical2 = IsUnion(evaluated) ? evaluated.anyOf : [evaluated];
+ const remaining = ExcludeUnion(canonical2, right);
+ const result = EvaluateUnion(remaining);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/evaluate/evaluate.mjs
+function EvaluateDependent(if_, then_, else_) {
+ const intersected = EvaluateIntersect([if_, then_]);
+ const excluded2 = ExcludeOperation(else_, if_);
+ const result = EvaluateUnion([intersected, excluded2]);
+ return result;
+}
+function EvaluateEnum(values, result = []) {
+ return guard_exports.ShiftLeft(values, (left, right) => EvaluateEnum(right, [...result, Literal(left)]), () => EvaluateUnion(result));
+}
+function EvaluateIntersect(types) {
+ const distribution = Distribute(types);
+ const broadend = Broaden(distribution);
+ const result = EvaluateUnion(broadend);
+ return result;
+}
+function EvaluateTemplateLiteral(pattern) {
+ const evaluated = TemplateLiteralDecode(pattern);
+ const result = EvaluateType(evaluated);
+ return result;
+}
+function EvaluateUnion(types) {
+ const broadend = Broaden(types);
+ const result = EvaluateUnionFast(broadend);
+ return result;
+}
+function EvaluateType(type) {
+ const result = IsDependent(type) ? EvaluateDependent(type.if, type.then, type.else) : IsEnum2(type) ? EvaluateEnum(type.enum) : IsIntersect(type) ? EvaluateIntersect(type.allOf) : IsTemplateLiteral(type) ? EvaluateTemplateLiteral(type.pattern) : IsUnion(type) ? EvaluateUnion(type.anyOf) : type;
+ return result;
+}
+function EvaluateUnionFast(types) {
+ const result = guard_exports.IsEqual(types.length, 1) ? types[0] : guard_exports.IsEqual(types.length, 0) ? Never() : Union(types);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_enum.mjs
+function FromEnumKey(values, value) {
+ const unionKey = EvaluateEnum(values);
+ const result = FromKey(unionKey, value);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_integer.mjs
+function FromIntegerKey(_key, value) {
+ const result = CreateRecord(IntegerKey, value);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_intersect.mjs
+function FromIntersectKey(types, value) {
+ const evaluatedKey = EvaluateIntersect(types);
+ const result = FromKey(evaluatedKey, value);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_literal.mjs
+function FromLiteralKey(key, value) {
+ return guard_exports.IsString(key) || guard_exports.IsNumber(key) ? _Object_({ [key]: value }) : guard_exports.IsEqual(key, false) ? _Object_({ false: value }) : guard_exports.IsEqual(key, true) ? _Object_({ true: value }) : _Object_({});
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_number.mjs
+function FromNumberKey(_key, value) {
+ const result = CreateRecord(NumberKey, value);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_string.mjs
+function FromStringKey(key, value) {
+ return guard_exports.HasPropertyKey(key, "pattern") && (guard_exports.IsString(key.pattern) || key.pattern instanceof RegExp) ? CreateRecord(key.pattern.toString(), value) : CreateRecord(StringKey, value);
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_template_literal.mjs
+function FromTemplateKey(pattern, value) {
+ const types = ParsePatternIntoTypes(pattern);
+ const finite = IsTemplateLiteralFinite(types);
+ const result = finite ? FromKey(EvaluateTemplateLiteral(pattern), value) : CreateRecord(pattern, value);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/evaluate/flatten.mjs
+function FlattenType(type) {
+ const result = IsUnion(type) ? Flatten(type.anyOf) : [type];
+ return result;
+}
+function Flatten(types, result = []) {
+ return guard_exports.ShiftLeft(types, (left, right) => Flatten(right, [...result, ...FlattenType(left)]), () => result);
+}
+
+// node_modules/typebox/build/type/engine/record/from_key_union.mjs
+function StringOrNumberCheck(types) {
+ return types.some((type) => IsString4(type) || IsNumber4(type) || IsInteger3(type));
+}
+function TryBuildRecord(types, value) {
+ return guard_exports.IsEqual(StringOrNumberCheck(types), true) ? CreateRecord(StringKey, value) : void 0;
+}
+function CreateProperties(types, value) {
+ return types.reduce((result, left) => {
+ return IsLiteral(left) && (guard_exports.IsString(left.const) || guard_exports.IsNumber(left.const)) ? { ...result, [left.const]: value } : result;
+ }, {});
+}
+function CreateObject(types, value) {
+ const properties = CreateProperties(types, value);
+ const result = _Object_(properties);
+ return result;
+}
+function FromUnionKey(types, value) {
+ const flattened = Flatten(types);
+ const record = TryBuildRecord(flattened, value);
+ return IsSchema2(record) ? record : CreateObject(flattened, value);
+}
+
+// node_modules/typebox/build/type/engine/record/from_key.mjs
+function FromKey(key, value) {
+ const result = IsAny(key) ? FromAnyKey(value) : IsBoolean4(key) ? FromBooleanKey(value) : IsEnum2(key) ? FromEnumKey(key.enum, value) : IsInteger3(key) ? FromIntegerKey(key, value) : IsIntersect(key) ? FromIntersectKey(key.allOf, value) : IsLiteral(key) ? FromLiteralKey(key.const, value) : IsNumber4(key) ? FromNumberKey(key, value) : IsUnion(key) ? FromUnionKey(key.anyOf, value) : IsString4(key) ? FromStringKey(key, value) : IsTemplateLiteral(key) ? FromTemplateKey(key.pattern, value) : _Object_({});
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/record/instantiate.mjs
+function RecordAction(key, value, options) {
+ const result = CanInstantiate([key]) ? memory_exports.Update(FromKey(key, value), {}, options) : RecordDeferred(key, value, options);
+ return result;
+}
+function RecordInstantiate(context, state3, key, value, options) {
+ const instantiatedKey = InstantiateType(context, state3, key);
+ const instantiatedValue = InstantiateType(context, state3, value);
+ return RecordAction(instantiatedKey, instantiatedValue, options);
+}
+
+// node_modules/typebox/build/type/types/record.mjs
+var IntegerKey = `^${IntegerPattern}$`;
+var NumberKey = `^${NumberPattern}$`;
+var StringKey = `^${StringPattern}$`;
+function RecordDeferred(key, value, options = {}) {
+ return Deferred("Record", [key, value], options);
+}
+function Record(key, value, options = {}) {
+ return RecordAction(key, value, options);
+}
+function RecordFromPattern(pattern, value) {
+ return CreateRecord(pattern, value);
+}
+function RecordPatternToType(pattern) {
+ const result = guard_exports.IsEqual(pattern, StringKey) ? String2() : guard_exports.IsEqual(pattern, IntegerKey) ? Integer() : guard_exports.IsEqual(pattern, NumberKey) ? Number2() : TemplateLiteralDecodeUnsafe(pattern);
+ return result;
+}
+function RecordPattern(type) {
+ return guard_exports.Keys(type.patternProperties)[0];
+}
+function RecordKey(type) {
+ const pattern = RecordPattern(type);
+ const result = RecordPatternToType(pattern);
+ return result;
+}
+function RecordValue(type) {
+ return type.patternProperties[RecordPattern(type)];
+}
+function IsRecord(value) {
+ return IsKind(value, "Record");
+}
+
+// node_modules/typebox/build/type/types/rest.mjs
+function Rest(type) {
+ return memory_exports.Create({ "~kind": "Rest" }, { type: "rest", items: type }, {});
+}
+function IsRest(value) {
+ return IsKind(value, "Rest");
+}
+
+// node_modules/typebox/build/type/types/this.mjs
+function This(options) {
+ return memory_exports.Create({ ["~kind"]: "This" }, { $ref: "#" }, options);
+}
+function IsThis(value) {
+ return IsKind(value, "This");
+}
+
+// node_modules/typebox/build/type/types/undefined.mjs
+function Undefined(options) {
+ return memory_exports.Create({ "~kind": "Undefined" }, { type: "undefined" }, options);
+}
+function IsUndefined3(value) {
+ return IsKind(value, "Undefined");
+}
+
+// node_modules/typebox/build/type/types/void.mjs
+function Void(options) {
+ return memory_exports.Create({ "~kind": "Void" }, { type: "void" }, options);
+}
+function IsVoid(value) {
+ return IsKind(value, "Void");
+}
+
+// node_modules/typebox/build/type/script/mapping.mjs
+function IntrinsicOrCall(ref, parameters) {
+ return guard_exports.IsEqual(ref, "Array") ? _Array_(parameters[0]) : guard_exports.IsEqual(ref, "Capitalize") ? CapitalizeDeferred(parameters[0]) : guard_exports.IsEqual(ref, "ConstructorParameters") ? ConstructorParametersDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Evaluate") ? EvaluateDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Exclude") ? ExcludeDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, "Extract") ? ExtractDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, "Index") ? IndexDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, "InstanceType") ? InstanceTypeDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Lowercase") ? LowercaseDeferred(parameters[0]) : guard_exports.IsEqual(ref, "NonNullable") ? NonNullableDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Omit") ? OmitDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, "Parameters") ? ParametersDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Partial") ? PartialDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Pick") ? PickDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, "Readonly") ? ReadonlyObjectDeferred(parameters[0]) : guard_exports.IsEqual(ref, "KeyOf") ? KeyOfDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Record") ? RecordDeferred(parameters[0], parameters[1]) : guard_exports.IsEqual(ref, "Required") ? RequiredDeferred(parameters[0]) : guard_exports.IsEqual(ref, "ReturnType") ? ReturnTypeDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Uncapitalize") ? UncapitalizeDeferred(parameters[0]) : guard_exports.IsEqual(ref, "Uppercase") ? UppercaseDeferred(parameters[0]) : CallConstruct(Ref2(ref), parameters);
+}
+function Unreachable2() {
+ throw Error("Unreachable");
+}
+function DelimitedDecode(input, result = []) {
+ return guard_exports.ShiftLeft(input, (left, right) => DelimitedDecode(right, [...result, left[1]]), () => result);
+}
+function Delimited(input) {
+ return guard_exports.IsEqual(input.length, 3) ? [input[0], ...DelimitedDecode(input[1])] : [];
+}
+function GenericParameterExtendsEqualsMapping(input) {
+ return Parameter(input[0], input[2], input[4]);
+}
+function GenericParameterExtendsMapping(input) {
+ return Parameter(input[0], input[2], input[2]);
+}
+function GenericParameterEqualsMapping(input) {
+ return Parameter(input[0], Unknown(), input[2]);
+}
+function GenericParameterIdentifierMapping(input) {
+ return Parameter(input, Unknown(), Unknown());
+}
+function GenericParameterMapping(input) {
+ return input;
+}
+function GenericParameterListMapping(input) {
+ return Delimited(input);
+}
+function GenericParametersMapping(input) {
+ return input[1];
+}
+function GenericCallArgumentListMapping(input) {
+ return Delimited(input);
+}
+function GenericCallArgumentsMapping(input) {
+ return input[1];
+}
+function GenericCallMapping(input) {
+ return IntrinsicOrCall(input[0], input[1]);
+}
+function OptionalSemiColonMapping(input) {
+ return null;
+}
+function KeywordStringMapping(input) {
+ return String2();
+}
+function KeywordNumberMapping(input) {
+ return Number2();
+}
+function KeywordBooleanMapping(input) {
+ return Boolean2();
+}
+function KeywordUndefinedMapping(input) {
+ return Undefined();
+}
+function KeywordNullMapping(input) {
+ return Null();
+}
+function KeywordIntegerMapping(input) {
+ return Integer();
+}
+function KeywordBigIntMapping(input) {
+ return BigInt2();
+}
+function KeywordUnknownMapping(input) {
+ return Unknown();
+}
+function KeywordAnyMapping(input) {
+ return Any();
+}
+function KeywordObjectMapping(input) {
+ return _Object_({});
+}
+function KeywordNeverMapping(input) {
+ return Never();
+}
+function KeywordSymbolMapping(input) {
+ return Symbol2();
+}
+function KeywordVoidMapping(input) {
+ return Void();
+}
+function KeywordThisMapping(input) {
+ return This();
+}
+function LiteralBigIntMapping(input) {
+ return Literal(BigInt(input));
+}
+function LiteralBooleanMapping(input) {
+ return Literal(guard_exports.IsEqual(input, "true"));
+}
+function LiteralNumberMapping(input) {
+ return Literal(parseFloat(input));
+}
+function LiteralStringMapping(input) {
+ return Literal(input);
+}
+function TemplateInterpolateMapping(input) {
+ return input[1];
+}
+function TemplateSpanMapping(input) {
+ return Literal(input);
+}
+function TemplateBodyMapping(input) {
+ return guard_exports.IsEqual(input.length, 3) ? [input[0], input[1], ...input[2]] : [input[0]];
+}
+function TemplateLiteralTypesMapping(input) {
+ return input[1];
+}
+function TemplateLiteralMapping(input) {
+ return TemplateLiteralDeferred(input);
+}
+function DependentMapping(input) {
+ return guard_exports.IsEqual(input.length, 6) ? Dependent(input[1], input[3], input[5]) : Dependent(input[1], input[3], Unknown());
+}
+function KeyOfMapping(input) {
+ return input.length > 0;
+}
+function IndexArrayMapping(input) {
+ return input.reduce((result, current) => {
+ return guard_exports.IsEqual(current.length, 3) ? [...result, [current[1]]] : [...result, []];
+ }, []);
+}
+function ExtendsMapping(input) {
+ return guard_exports.IsEqual(input.length, 6) ? [input[1], input[3], input[5]] : [];
+}
+function BaseMapping(input) {
+ return guard_exports.IsArray(input) && guard_exports.IsEqual(input.length, 3) ? input[1] : input;
+}
+function WithMapping(input) {
+ return guard_exports.IsEqual(input.length, 2) ? input[1] : [];
+}
+function FactorIndexArray(Type2, indexArray) {
+ return indexArray.reduce((result, left) => {
+ const _left = left;
+ return guard_exports.IsEqual(_left.length, 1) ? IndexDeferred(result, _left[0]) : guard_exports.IsEqual(_left.length, 0) ? _Array_(result) : Unreachable2();
+ }, Type2);
+}
+function FactorExtends(type, extend) {
+ return guard_exports.IsEqual(extend.length, 3) ? ConditionalDeferred(type, extend[0], extend[1], extend[2]) : type;
+}
+function FactorWith(type, withClause) {
+ return guard_exports.IsArray(withClause) && guard_exports.IsEqual(withClause.length, 0) ? type : WithDeferred(type, withClause);
+}
+function FactorMapping(input) {
+ const [keyOf, type, indexArray, extend, withClause] = input;
+ return FactorWith(keyOf ? FactorExtends(KeyOfDeferred(FactorIndexArray(type, indexArray)), extend) : FactorExtends(FactorIndexArray(type, indexArray), extend), withClause);
+}
+function ExprBinaryMapping(left, rest) {
+ return guard_exports.IsEqual(rest.length, 3) ? (() => {
+ const [operator, right, next] = rest;
+ const Schema = ExprBinaryMapping(right, next);
+ if (guard_exports.IsEqual(operator, "&")) {
+ return IsIntersect(Schema) ? Intersect([left, ...Schema.allOf]) : Intersect([left, Schema]);
+ }
+ if (guard_exports.IsEqual(operator, "|")) {
+ return IsUnion(Schema) ? Union([left, ...Schema.anyOf]) : Union([left, Schema]);
+ }
+ Unreachable2();
+ })() : left;
+}
+function ExprTermTailMapping(input) {
+ return input;
+}
+function ExprTermMapping(input) {
+ const [left, rest] = input;
+ return ExprBinaryMapping(left, rest);
+}
+function ExprTailMapping(input) {
+ return input;
+}
+function ExprMapping(input) {
+ const [left, rest] = input;
+ return ExprBinaryMapping(left, rest);
+}
+function ExprReadonlyMapping(input) {
+ return AddImmutableDeferred(input[1]);
+}
+function ExprPipeMapping(input) {
+ return input[1];
+}
+function GenericTypeMapping(input) {
+ return Generic(input[0], input[2]);
+}
+function InferTypeMapping(input) {
+ return guard_exports.IsEqual(input.length, 4) ? Infer(input[1], input[3]) : guard_exports.IsEqual(input.length, 2) ? Infer(input[1], Unknown()) : Unreachable2();
+}
+function TypeMapping(input) {
+ return input;
+}
+function PropertyKeyNumberMapping(input) {
+ return `${input}`;
+}
+function PropertyKeyIdentMapping(input) {
+ return input;
+}
+function PropertyKeyQuotedMapping(input) {
+ return input;
+}
+function PropertyKeyIndexMapping(input) {
+ return IsInteger3(input[3]) ? IntegerKey : IsNumber4(input[3]) ? NumberKey : IsSymbol3(input[3]) ? StringKey : IsString4(input[3]) ? StringKey : Unreachable2();
+}
+function PropertyKeyMapping(input) {
+ return input;
+}
+function ReadonlyMapping(input) {
+ return input.length > 0;
+}
+function OptionalMapping(input) {
+ return input.length > 0;
+}
+function PropertyMapping(input) {
+ const [isReadonly, key, isOptional, _colon, type] = input;
+ return {
+ [key]: isReadonly && isOptional ? AddReadonlyDeferred(AddOptionalDeferred(type)) : isReadonly && !isOptional ? AddReadonlyDeferred(type) : !isReadonly && isOptional ? AddOptionalDeferred(type) : type
+ };
+}
+function PropertyDelimiterMapping(input) {
+ return input;
+}
+function PropertyListMapping(input) {
+ return Delimited(input);
+}
+function PropertiesReduce(propertyList) {
+ return propertyList.reduce((result, left) => {
+ const isPatternProperties = guard_exports.HasPropertyKey(left, IntegerKey) || guard_exports.HasPropertyKey(left, NumberKey) || guard_exports.HasPropertyKey(left, StringKey);
+ return isPatternProperties ? [result[0], memory_exports.Assign(result[1], left)] : [memory_exports.Assign(result[0], left), result[1]];
+ }, [{}, {}]);
+}
+function PropertiesMapping(input) {
+ return PropertiesReduce(input[1]);
+}
+function _Object_Mapping(input) {
+ const [properties, patternProperties] = input;
+ const options = guard_exports.IsEqual(guard_exports.Keys(patternProperties).length, 0) ? {} : { patternProperties };
+ return _Object_(properties, options);
+}
+function ElementNamedMapping(input) {
+ return guard_exports.IsEqual(input.length, 5) ? AddReadonlyDeferred(AddOptionalDeferred(input[4])) : guard_exports.IsEqual(input.length, 3) ? input[2] : guard_exports.IsEqual(input.length, 4) ? guard_exports.IsEqual(input[2], "readonly") ? AddReadonlyDeferred(input[3]) : AddOptionalDeferred(input[3]) : Unreachable2();
+}
+function ElementBaseMapping(input) {
+ if (!guard_exports.IsArray(input) || !guard_exports.IsEqual(input.length, 3))
+ return input;
+ const [isReadonly, type, isOptional] = input;
+ return isReadonly && isOptional ? AddReadonlyDeferred(AddOptionalDeferred(type)) : isReadonly && !isOptional ? AddReadonlyDeferred(type) : !isReadonly && isOptional ? AddOptionalDeferred(type) : type;
+}
+function ElementMapping(input) {
+ return guard_exports.IsEqual(input.length, 2) ? Rest(input[1]) : guard_exports.IsEqual(input.length, 1) ? input[0] : Unreachable2();
+}
+function ElementListMapping(input) {
+ return Delimited(input);
+}
+function _Tuple_Mapping(input) {
+ return Tuple(input[1]);
+}
+function ParameterReadonlyOptionalMapping(input) {
+ return AddReadonlyDeferred(AddOptionalDeferred(input[4]));
+}
+function ParameterReadonlyMapping(input) {
+ return AddReadonlyDeferred(input[3]);
+}
+function ParameterOptionalMapping(input) {
+ return AddOptionalDeferred(input[3]);
+}
+function ParameterTypeMapping(input) {
+ return input[2];
+}
+function ParameterBaseMapping(input) {
+ return input;
+}
+function ParameterMapping(input) {
+ return guard_exports.IsEqual(input.length, 2) ? Rest(input[1]) : guard_exports.IsEqual(input.length, 1) ? input[0] : Unreachable2();
+}
+function ParameterListMapping(input) {
+ return Delimited(input);
+}
+function _Function_Mapping(input) {
+ return _Function_(input[1], input[4]);
+}
+function _Constructor_Mapping(input) {
+ return Constructor(input[2], input[5]);
+}
+function ApplyReadonly(state3, type) {
+ return guard_exports.IsEqual(state3, "remove") ? RemoveReadonlyDeferred(type) : guard_exports.IsEqual(state3, "add") ? AddReadonlyDeferred(type) : type;
+}
+function MappedReadonlyMapping(input) {
+ return guard_exports.IsEqual(input.length, 2) && guard_exports.IsEqual(input[0], "-") ? "remove" : guard_exports.IsEqual(input.length, 2) && guard_exports.IsEqual(input[0], "+") ? "add" : guard_exports.IsEqual(input.length, 1) ? "add" : "none";
+}
+function ApplyOptional(state3, type) {
+ return guard_exports.IsEqual(state3, "remove") ? RemoveOptionalDeferred(type) : guard_exports.IsEqual(state3, "add") ? AddOptionalDeferred(type) : type;
+}
+function MappedOptionalMapping(input) {
+ return guard_exports.IsEqual(input.length, 2) && guard_exports.IsEqual(input[0], "-") ? "remove" : guard_exports.IsEqual(input.length, 2) && guard_exports.IsEqual(input[0], "+") ? "add" : guard_exports.IsEqual(input.length, 1) ? "add" : "none";
+}
+function MappedAsMapping(input) {
+ return guard_exports.IsEqual(input.length, 2) ? [input[1]] : [];
+}
+function _Mapped_Mapping(input) {
+ return guard_exports.IsArray(input[6]) && guard_exports.IsEqual(input[6].length, 1) ? MappedDeferred(Identifier(input[3]), input[5], input[6][0], ApplyReadonly(input[1], ApplyOptional(input[8], input[10]))) : MappedDeferred(Identifier(input[3]), input[5], Ref2(input[3]), ApplyReadonly(input[1], ApplyOptional(input[8], input[10])));
+}
+function ReferenceMapping(input) {
+ return Ref2(input);
+}
+function WithBigIntMapping(input) {
+ return BigInt(input);
+}
+function WithNumberMapping(input) {
+ return parseFloat(input);
+}
+function WithBooleanMapping(input) {
+ return guard_exports.IsEqual(input, "true");
+}
+function WithStringMapping(input) {
+ return input;
+}
+function WithNullMapping(input) {
+ return null;
+}
+function WithUndefinedMapping(input) {
+ return void 0;
+}
+function WithPropertyMapping(input) {
+ return { [input[0]]: input[2] };
+}
+function WithPropertyListMapping(input) {
+ return Delimited(input);
+}
+function WithObjectMappingReduce(propertyList) {
+ return propertyList.reduce((result, left) => {
+ return memory_exports.Assign(result, left);
+ }, {});
+}
+function WithObjectMapping(input) {
+ return WithObjectMappingReduce(input[1]);
+}
+function WithElementListMapping(input) {
+ return Delimited(input);
+}
+function WithArrayMapping(input) {
+ return input[1];
+}
+function WithValueMapping(input) {
+ return input;
+}
+function PatternBigIntMapping(input) {
+ return BigInt2();
+}
+function PatternStringMapping(input) {
+ return String2();
+}
+function PatternNumberMapping(input) {
+ return Number2();
+}
+function PatternIntegerMapping(input) {
+ return Integer();
+}
+function PatternNeverMapping(input) {
+ return Never();
+}
+function PatternTextMapping(input) {
+ return Literal(input);
+}
+function PatternBaseMapping(input) {
+ return input;
+}
+function PatternGroupMapping(input) {
+ return Union(input[1]);
+}
+function PatternUnionMapping(input) {
+ return input.length === 3 ? [...input[0], ...input[2]] : input.length === 1 ? [...input[0]] : [];
+}
+function PatternTermMapping(input) {
+ return [input[0], ...input[1]];
+}
+function PatternBodyMapping(input) {
+ return input;
+}
+function PatternMapping(input) {
+ return input[1];
+}
+function InterfaceDeclarationHeritageListMapping(input) {
+ return Delimited(input);
+}
+function InterfaceDeclarationHeritageMapping(input) {
+ return guard_exports.IsEqual(input.length, 2) ? input[1] : [];
+}
+function InterfaceDeclarationGenericMapping(input) {
+ const parameters = input[2];
+ const heritage = input[3];
+ const [properties, patternProperties] = input[4];
+ const options = guard_exports.IsEqual(guard_exports.Keys(patternProperties).length, 0) ? {} : { patternProperties };
+ return { [input[1]]: Generic(parameters, InterfaceDeferred(heritage, properties, options)) };
+}
+function InterfaceDeclarationMapping(input) {
+ const heritage = input[2];
+ const [properties, patternProperties] = input[3];
+ const options = guard_exports.IsEqual(guard_exports.Keys(patternProperties).length, 0) ? {} : { patternProperties };
+ return { [input[1]]: InterfaceDeferred(heritage, properties, options) };
+}
+function TypeAliasDeclarationGenericMapping(input) {
+ return { [input[1]]: Generic(input[2], input[4]) };
+}
+function TypeAliasDeclarationMapping(input) {
+ return { [input[1]]: input[3] };
+}
+function ExportKeywordMapping(input) {
+ return null;
+}
+function ModuleDeclarationDelimiterMapping(input) {
+ return input;
+}
+function ModuleDeclarationListMapping(input) {
+ return Delimited(input);
+}
+function ModuleDeclarationMapping(input) {
+ return input[1];
+}
+function ModuleMapping(input) {
+ const [moduleDeclaration, moduleDeclarationList] = [input[0], input[1]];
+ return ModuleDeferred(memory_exports.Assign(moduleDeclaration, PropertiesReduce(moduleDeclarationList)[0]));
+}
+function ScriptMapping(input) {
+ return input;
+}
+
+// node_modules/typebox/build/type/script/token/internal/match.mjs
+function IsMatch(value) {
+ return IsEqual(value.length, 2);
+}
+function Match3(input, ok2, fail) {
+ return IsMatch(input) ? ok2(input[0], input[1]) : fail();
+}
+
+// node_modules/typebox/build/type/script/token/internal/take.mjs
+function TakeVariant(variant, input) {
+ return IsEqual(input.indexOf(variant), 0) ? [variant, input.slice(variant.length)] : [];
+}
+function Take(variants, input) {
+ for (let i = 0; i < variants.length; i++) {
+ const result = TakeVariant(variants[i], input);
+ if (IsMatch(result))
+ return result;
+ }
+ return [];
+}
+
+// node_modules/typebox/build/type/script/token/internal/char.mjs
+function Range(start, end) {
+ return Array.from({ length: end - start + 1 }, (_, i) => String.fromCharCode(start + i));
+}
+var Alpha2 = [
+ ...Range(97, 122),
+ // Lowercase
+ ...Range(65, 90)
+ // Uppercase
+];
+var Zero = "0";
+var NonZero = Range(49, 57);
+var Digit = [Zero, ...NonZero];
+var WhiteSpace = " ";
+var NewLine = "\n";
+var UnderScore = "_";
+var Dot = ".";
+var DollarSign = "$";
+var Hyphen = "-";
+
+// node_modules/typebox/build/type/script/token/internal/trim.mjs
+var LineComment = "//";
+var OpenComment = "/*";
+var CloseComment = "*/";
+function DiscardMultilineComment(input) {
+ const index3 = input.indexOf(CloseComment);
+ const result = IsEqual(index3, -1) ? "" : input.slice(index3 + 2);
+ return result;
+}
+function DiscardLineComment(input) {
+ const index3 = input.indexOf(NewLine);
+ const result = IsEqual(index3, -1) ? "" : input.slice(index3);
+ return result;
+}
+function TrimStartUntilNewline(input) {
+ return input.replace(/^[ \t\r\f\v]+/, "");
+}
+function TrimWhitespace(input) {
+ const trimmed = TrimStartUntilNewline(input);
+ return trimmed.startsWith(OpenComment) ? TrimWhitespace(DiscardMultilineComment(trimmed.slice(2))) : trimmed.startsWith(LineComment) ? TrimWhitespace(DiscardLineComment(trimmed.slice(2))) : trimmed;
+}
+function Trim(input) {
+ const trimmed = input.trimStart();
+ return trimmed.startsWith(OpenComment) ? Trim(DiscardMultilineComment(trimmed.slice(2))) : trimmed.startsWith(LineComment) ? Trim(DiscardLineComment(trimmed.slice(2))) : trimmed;
+}
+
+// node_modules/typebox/build/type/script/token/internal/optional.mjs
+function Optional2(value, input) {
+ return Match3(Take([value], input), (Optional4, Rest2) => [Optional4, Rest2], () => ["", input]);
+}
+
+// node_modules/typebox/build/type/script/token/internal/many.mjs
+function IsDiscard(discard, input) {
+ return discard.includes(input);
+}
+function Many(allowed, discard, input, result = "") {
+ return Match3(Take(allowed, input), (Char, Rest2) => IsDiscard(discard, Char) ? Many(allowed, discard, Rest2, result) : Many(allowed, discard, Rest2, `${result}${Char}`), () => [result, input]);
+}
+
+// node_modules/typebox/build/type/script/token/unsigned_integer.mjs
+function TakeNonZero(input) {
+ return Take(NonZero, input);
+}
+var AllowedDigits = [...Digit, UnderScore];
+function TakeDigits(input) {
+ return Many(AllowedDigits, [UnderScore], input);
+}
+function TakeUnsignedInteger(input) {
+ return Match3(Take([Zero], input), (Zero2, ZeroRest) => [Zero2, ZeroRest], () => Match3(
+ TakeNonZero(input),
+ (NonZero2, NonZeroRest) => Match3(TakeDigits(NonZeroRest), (Digits, DigitsRest) => [`${NonZero2}${Digits}`, DigitsRest], () => []),
+ // fail: did not match Digits
+ () => []
+ ));
+}
+function UnsignedInteger(input) {
+ return TakeUnsignedInteger(Trim(input));
+}
+
+// node_modules/typebox/build/type/script/token/integer.mjs
+function TakeSign(input) {
+ return Optional2(Hyphen, input);
+}
+function TakeSignedInteger(input) {
+ return Match3(
+ TakeSign(input),
+ (Sign, SignRest) => Match3(UnsignedInteger(SignRest), (UnsignedInteger2, UnsignedIntegerRest) => [`${Sign}${UnsignedInteger2}`, UnsignedIntegerRest], () => []),
+ // fail: did not match unsigned integer
+ () => []
+ );
+}
+function Integer2(input) {
+ return TakeSignedInteger(Trim(input));
+}
+
+// node_modules/typebox/build/type/script/token/bigint.mjs
+function TakeBigInt(input) {
+ return Match3(
+ Integer2(input),
+ (Integer3, IntegerRest) => Match3(Take(["n"], IntegerRest), (_N, NRest) => [`${Integer3}`, NRest], () => []),
+ // fail: did not match 'n'
+ () => []
+ );
+}
+function BigInt3(input) {
+ return TakeBigInt(input);
+}
+
+// node_modules/typebox/build/type/script/token/const.mjs
+function TakeConst(const_, input) {
+ return Take([const_], input);
+}
+function Const(const_, input) {
+ return IsEqual(const_, "") ? ["", input] : const_.startsWith(NewLine) ? TakeConst(const_, TrimWhitespace(input)) : const_.startsWith(WhiteSpace) ? TakeConst(const_, input) : TakeConst(const_, Trim(input));
+}
+
+// node_modules/typebox/build/type/script/token/ident.mjs
+var Initial = [...Alpha2, UnderScore, DollarSign];
+function TakeInitial(input) {
+ return Take(Initial, input);
+}
+var Remaining = [...Initial, ...Digit];
+function TakeRemaining(input, result = "") {
+ return Match3(Take(Remaining, input), (Remaining2, RemainingRest) => TakeRemaining(RemainingRest, `${result}${Remaining2}`), () => [result, input]);
+}
+function TakeIdent(input) {
+ return Match3(
+ TakeInitial(input),
+ (Initial2, InitialRest) => Match3(TakeRemaining(InitialRest), (Remaining2, RemainingRest) => [`${Initial2}${Remaining2}`, RemainingRest], () => []),
+ // fail: did not match Remaining
+ () => []
+ );
+}
+function Ident(input) {
+ return TakeIdent(Trim(input));
+}
+
+// node_modules/typebox/build/type/script/token/unsigned_number.mjs
+var AllowedDigits2 = [...Digit, UnderScore];
+function IsLeadingDot(input) {
+ return IsMatch(Take([Dot], input));
+}
+function TakeFractional(input) {
+ return Match3(Many(AllowedDigits2, [UnderScore], input), (Digits, DigitsRest) => IsEqual(Digits, "") ? [] : [Digits, DigitsRest], () => []);
+}
+function LeadingDot(input) {
+ return Match3(
+ Take([Dot], input),
+ (Dot2, DotRest) => Match3(TakeFractional(DotRest), (Fractional, FractionalRest) => [`0${Dot2}${Fractional}`, FractionalRest], () => []),
+ // fail: did not match Fractional
+ () => []
+ );
+}
+function LeadingInteger(input) {
+ return Match3(
+ UnsignedInteger(input),
+ (Integer3, IntegerRest) => Match3(
+ Take([Dot], IntegerRest),
+ (Dot2, DotRest) => Match3(TakeFractional(DotRest), (Fractional, FractionalRest) => [`${Integer3}${Dot2}${Fractional}`, FractionalRest], () => [`${Integer3}`, DotRest]),
+ // fail: did not match Fractional, use Integer
+ () => [`${Integer3}`, IntegerRest]
+ ),
+ // fail: did not match Dot, use Integer
+ () => []
+ );
+}
+function TakeUnsignedNumber(input) {
+ return IsLeadingDot(input) ? LeadingDot(input) : LeadingInteger(input);
+}
+function UnsignedNumber(input) {
+ return TakeUnsignedNumber(Trim(input));
+}
+
+// node_modules/typebox/build/type/script/token/number.mjs
+function TakeSign2(input) {
+ return Optional2(Hyphen, input);
+}
+function TakeSignedNumber(input) {
+ return Match3(
+ TakeSign2(input),
+ (Sign, SignRest) => Match3(UnsignedNumber(SignRest), (UnsignedInteger2, UnsignedIntegerRest) => [`${Sign}${UnsignedInteger2}`, UnsignedIntegerRest], () => []),
+ // fail: did not match unsigned integer
+ () => []
+ );
+}
+function Number3(input) {
+ return TakeSignedNumber(Trim(input));
+}
+
+// node_modules/typebox/build/type/script/token/until.mjs
+function TakeOne(input) {
+ const result = IsEqual(input, "") ? [] : [input.slice(0, 1), input.slice(1)];
+ return result;
+}
+function IsInputMatchSentinal(end, input) {
+ return ShiftLeft(end, (left, right) => input.startsWith(left) ? true : IsInputMatchSentinal(right, input), () => false);
+}
+function Until(end, input, result = "") {
+ return Match3(
+ TakeOne(input),
+ (One, Rest2) => IsInputMatchSentinal(end, input) ? [result, input] : Until(end, Rest2, `${result}${One}`),
+ () => []
+ );
+}
+
+// node_modules/typebox/build/type/script/token/span.mjs
+function MultiLine(start, end, input) {
+ return Match3(
+ Take([start], input),
+ (_, Rest2) => Match3(
+ Until([end], Rest2),
+ (Until2, UntilRest) => Match3(Take([end], UntilRest), (_2, Rest3) => [`${Until2}`, Rest3], () => []),
+ // fail: did not match End
+ () => []
+ ),
+ // fail: did not match Until
+ () => []
+ );
+}
+function SingleLine(start, end, input) {
+ return Match3(
+ Take([start], input),
+ (_, Rest2) => Match3(
+ Until([NewLine, end], Rest2),
+ (Until2, UntilRest) => Match3(Take([end], UntilRest), (_2, EndRest) => [`${Until2}`, EndRest], () => []),
+ // fail: did not match End
+ () => []
+ ),
+ // fail: did not match Until
+ () => []
+ );
+}
+function Span(start, end, multiLine, input) {
+ return multiLine ? MultiLine(start, end, Trim(input)) : SingleLine(start, end, Trim(input));
+}
+
+// node_modules/typebox/build/type/script/token/string.mjs
+function TakeInitial2(quotes, input) {
+ return Take(quotes, input);
+}
+function TakeSpan(quote, input) {
+ return Span(quote, quote, false, input);
+}
+function TakeString(quotes, input) {
+ return Match3(TakeInitial2(quotes, input), (Initial2, InitialRest) => TakeSpan(Initial2, `${Initial2}${InitialRest}`), () => []);
+}
+function String3(quotes, input) {
+ return TakeString(quotes, Trim(input));
+}
+
+// node_modules/typebox/build/type/script/token/until_1.mjs
+function Until_1(end, input) {
+ return Match3(Until(end, input), (Until2, UntilRest) => IsEqual(Until2, "") ? [] : [Until2, UntilRest], () => []);
+}
+
+// node_modules/typebox/build/type/script/parser.mjs
+var If2 = (result, left, right = () => []) => result.length === 2 ? left(result) : right();
+var GenericParameterExtendsEquals = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const("extends", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => If2(Const("=", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [GenericParameterExtendsEqualsMapping(_0), input2]);
+var GenericParameterExtends = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const("extends", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericParameterExtendsMapping(_0), input2]);
+var GenericParameterEquals = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const("=", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericParameterEqualsMapping(_0), input2]);
+var GenericParameterIdentifier = (input) => If2(Ident(input), ([_0, input2]) => [GenericParameterIdentifierMapping(_0), input2]);
+var GenericParameter = (input) => If2(If2(GenericParameterExtendsEquals(input), ([_0, input2]) => [_0, input2], () => If2(GenericParameterExtends(input), ([_0, input2]) => [_0, input2], () => If2(GenericParameterEquals(input), ([_0, input2]) => [_0, input2], () => If2(GenericParameterIdentifier(input), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [GenericParameterMapping(_0), input2]);
+var GenericParameterList_0 = (input, result = []) => If2(If2(Const(",", input), ([_0, input2]) => If2(GenericParameter(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => GenericParameterList_0(input2, [...result, _0]), () => [result, input]);
+var GenericParameterList = (input) => If2(If2(If2(GenericParameter(input), ([_0, input2]) => If2(GenericParameterList_0(input2), ([_1, input3]) => If2(If2(Const(",", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [GenericParameterListMapping(_0), input2]);
+var GenericParameters = (input) => If2(If2(Const("<", input), ([_0, input2]) => If2(GenericParameterList(input2), ([_1, input3]) => If2(Const(">", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericParametersMapping(_0), input2]);
+var GenericCallArgumentList_0 = (input, result = []) => If2(If2(Const(",", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => GenericCallArgumentList_0(input2, [...result, _0]), () => [result, input]);
+var GenericCallArgumentList = (input) => If2(If2(If2(Type(input), ([_0, input2]) => If2(GenericCallArgumentList_0(input2), ([_1, input3]) => If2(If2(Const(",", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [GenericCallArgumentListMapping(_0), input2]);
+var GenericCallArguments = (input) => If2(If2(Const("<", input), ([_0, input2]) => If2(GenericCallArgumentList(input2), ([_1, input3]) => If2(Const(">", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericCallArgumentsMapping(_0), input2]);
+var GenericCall = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(GenericCallArguments(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [GenericCallMapping(_0), input2]);
+var OptionalSemiColon = (input) => If2(If2(If2(Const(";", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [OptionalSemiColonMapping(_0), input2]);
+var KeywordString = (input) => If2(Const("string", input), ([_0, input2]) => [KeywordStringMapping(_0), input2]);
+var KeywordNumber = (input) => If2(Const("number", input), ([_0, input2]) => [KeywordNumberMapping(_0), input2]);
+var KeywordBoolean = (input) => If2(Const("boolean", input), ([_0, input2]) => [KeywordBooleanMapping(_0), input2]);
+var KeywordUndefined = (input) => If2(Const("undefined", input), ([_0, input2]) => [KeywordUndefinedMapping(_0), input2]);
+var KeywordNull = (input) => If2(Const("null", input), ([_0, input2]) => [KeywordNullMapping(_0), input2]);
+var KeywordInteger = (input) => If2(Const("integer", input), ([_0, input2]) => [KeywordIntegerMapping(_0), input2]);
+var KeywordBigInt = (input) => If2(Const("bigint", input), ([_0, input2]) => [KeywordBigIntMapping(_0), input2]);
+var KeywordUnknown = (input) => If2(Const("unknown", input), ([_0, input2]) => [KeywordUnknownMapping(_0), input2]);
+var KeywordAny = (input) => If2(Const("any", input), ([_0, input2]) => [KeywordAnyMapping(_0), input2]);
+var KeywordObject = (input) => If2(Const("object", input), ([_0, input2]) => [KeywordObjectMapping(_0), input2]);
+var KeywordNever = (input) => If2(Const("never", input), ([_0, input2]) => [KeywordNeverMapping(_0), input2]);
+var KeywordSymbol = (input) => If2(Const("symbol", input), ([_0, input2]) => [KeywordSymbolMapping(_0), input2]);
+var KeywordVoid = (input) => If2(Const("void", input), ([_0, input2]) => [KeywordVoidMapping(_0), input2]);
+var KeywordThis = (input) => If2(Const("this", input), ([_0, input2]) => [KeywordThisMapping(_0), input2]);
+var TemplateInterpolate = (input) => If2(If2(Const("${", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const("}", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [TemplateInterpolateMapping(_0), input2]);
+var TemplateSpan = (input) => If2(Until(["${", "`"], input), ([_0, input2]) => [TemplateSpanMapping(_0), input2]);
+var TemplateBody = (input) => If2(If2(If2(TemplateSpan(input), ([_0, input2]) => If2(TemplateInterpolate(input2), ([_1, input3]) => If2(TemplateBody(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2(If2(TemplateSpan(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2(If2(TemplateSpan(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => []))), ([_0, input2]) => [TemplateBodyMapping(_0), input2]);
+var TemplateLiteralTypes = (input) => If2(If2(Const("`", input), ([_0, input2]) => If2(TemplateBody(input2), ([_1, input3]) => If2(Const("`", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [TemplateLiteralTypesMapping(_0), input2]);
+var TemplateLiteral = (input) => If2(TemplateLiteralTypes(input), ([_0, input2]) => [TemplateLiteralMapping(_0), input2]);
+var Dependent2 = (input) => If2(If2(If2(Const("if", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const("then", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => If2(Const("else", input5), ([_4, input6]) => If2(Type(input6), ([_5, input7]) => [[_0, _1, _2, _3, _4, _5], input7])))))), ([_0, input2]) => [_0, input2], () => If2(If2(Const("if", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const("then", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [DependentMapping(_0), input2]);
+var LiteralBigInt = (input) => If2(BigInt3(input), ([_0, input2]) => [LiteralBigIntMapping(_0), input2]);
+var LiteralBoolean = (input) => If2(If2(Const("true", input), ([_0, input2]) => [_0, input2], () => If2(Const("false", input), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [LiteralBooleanMapping(_0), input2]);
+var LiteralNumber = (input) => If2(Number3(input), ([_0, input2]) => [LiteralNumberMapping(_0), input2]);
+var LiteralString = (input) => If2(String3(["'", '"'], input), ([_0, input2]) => [LiteralStringMapping(_0), input2]);
+var KeyOf = (input) => If2(If2(If2(Const("keyof", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [KeyOfMapping(_0), input2]);
+var IndexArray_0 = (input, result = []) => If2(If2(If2(Const("[", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const("]", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2(If2(Const("[", input), ([_0, input2]) => If2(Const("]", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => IndexArray_0(input2, [...result, _0]), () => [result, input]);
+var IndexArray = (input) => If2(IndexArray_0(input), ([_0, input2]) => [IndexArrayMapping(_0), input2]);
+var Extends2 = (input) => If2(If2(If2(Const("extends", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const("?", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => If2(Const(":", input5), ([_4, input6]) => If2(Type(input6), ([_5, input7]) => [[_0, _1, _2, _3, _4, _5], input7])))))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ExtendsMapping(_0), input2]);
+var Base2 = (input) => If2(If2(If2(Const("(", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Const(")", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2(KeywordString(input), ([_0, input2]) => [_0, input2], () => If2(KeywordNumber(input), ([_0, input2]) => [_0, input2], () => If2(KeywordBoolean(input), ([_0, input2]) => [_0, input2], () => If2(KeywordUndefined(input), ([_0, input2]) => [_0, input2], () => If2(KeywordNull(input), ([_0, input2]) => [_0, input2], () => If2(KeywordInteger(input), ([_0, input2]) => [_0, input2], () => If2(KeywordBigInt(input), ([_0, input2]) => [_0, input2], () => If2(KeywordUnknown(input), ([_0, input2]) => [_0, input2], () => If2(KeywordAny(input), ([_0, input2]) => [_0, input2], () => If2(KeywordObject(input), ([_0, input2]) => [_0, input2], () => If2(KeywordNever(input), ([_0, input2]) => [_0, input2], () => If2(KeywordSymbol(input), ([_0, input2]) => [_0, input2], () => If2(KeywordVoid(input), ([_0, input2]) => [_0, input2], () => If2(KeywordThis(input), ([_0, input2]) => [_0, input2], () => If2(LiteralBigInt(input), ([_0, input2]) => [_0, input2], () => If2(LiteralBoolean(input), ([_0, input2]) => [_0, input2], () => If2(LiteralNumber(input), ([_0, input2]) => [_0, input2], () => If2(LiteralString(input), ([_0, input2]) => [_0, input2], () => If2(TemplateLiteral(input), ([_0, input2]) => [_0, input2], () => If2(Dependent2(input), ([_0, input2]) => [_0, input2], () => If2(_Object_2(input), ([_0, input2]) => [_0, input2], () => If2(_Tuple_(input), ([_0, input2]) => [_0, input2], () => If2(_Constructor_(input), ([_0, input2]) => [_0, input2], () => If2(_Function_2(input), ([_0, input2]) => [_0, input2], () => If2(_Mapped_(input), ([_0, input2]) => [_0, input2], () => If2(GenericCall(input), ([_0, input2]) => [_0, input2], () => If2(Reference(input), ([_0, input2]) => [_0, input2], () => [])))))))))))))))))))))))))))), ([_0, input2]) => [BaseMapping(_0), input2]);
+var With = (input) => If2(If2(If2(Const("with", input), ([_0, input2]) => If2(WithObject(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [WithMapping(_0), input2]);
+var Factor = (input) => If2(If2(KeyOf(input), ([_0, input2]) => If2(Base2(input2), ([_1, input3]) => If2(IndexArray(input3), ([_2, input4]) => If2(Extends2(input4), ([_3, input5]) => If2(With(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [FactorMapping(_0), input2]);
+var ExprTermTail = (input) => If2(If2(If2(Const("&", input), ([_0, input2]) => If2(Factor(input2), ([_1, input3]) => If2(ExprTermTail(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ExprTermTailMapping(_0), input2]);
+var ExprTerm = (input) => If2(If2(Factor(input), ([_0, input2]) => If2(ExprTermTail(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ExprTermMapping(_0), input2]);
+var ExprTail = (input) => If2(If2(If2(Const("|", input), ([_0, input2]) => If2(ExprTerm(input2), ([_1, input3]) => If2(ExprTail(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ExprTailMapping(_0), input2]);
+var Expr = (input) => If2(If2(ExprTerm(input), ([_0, input2]) => If2(ExprTail(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ExprMapping(_0), input2]);
+var ExprReadonly = (input) => If2(If2(Const("readonly", input), ([_0, input2]) => If2(Expr(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ExprReadonlyMapping(_0), input2]);
+var ExprPipe = (input) => If2(If2(Const("|", input), ([_0, input2]) => If2(Expr(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ExprPipeMapping(_0), input2]);
+var GenericType = (input) => If2(If2(GenericParameters(input), ([_0, input2]) => If2(Const("=", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [GenericTypeMapping(_0), input2]);
+var InferType = (input) => If2(If2(If2(Const("infer", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(Const("extends", input3), ([_2, input4]) => If2(Expr(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [_0, input2], () => If2(If2(Const("infer", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [InferTypeMapping(_0), input2]);
+var Type = (input) => If2(If2(InferType(input), ([_0, input2]) => [_0, input2], () => If2(ExprPipe(input), ([_0, input2]) => [_0, input2], () => If2(ExprReadonly(input), ([_0, input2]) => [_0, input2], () => If2(Expr(input), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [TypeMapping(_0), input2]);
+var PropertyKeyNumber = (input) => If2(Number3(input), ([_0, input2]) => [PropertyKeyNumberMapping(_0), input2]);
+var PropertyKeyIdent = (input) => If2(Ident(input), ([_0, input2]) => [PropertyKeyIdentMapping(_0), input2]);
+var PropertyKeyQuoted = (input) => If2(String3(["'", '"'], input), ([_0, input2]) => [PropertyKeyQuotedMapping(_0), input2]);
+var PropertyKeyIndex = (input) => If2(If2(Const("[", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(Const(":", input3), ([_2, input4]) => If2(If2(KeywordInteger(input4), ([_02, input5]) => [_02, input5], () => If2(KeywordNumber(input4), ([_02, input5]) => [_02, input5], () => If2(KeywordString(input4), ([_02, input5]) => [_02, input5], () => If2(KeywordSymbol(input4), ([_02, input5]) => [_02, input5], () => [])))), ([_3, input5]) => If2(Const("]", input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [PropertyKeyIndexMapping(_0), input2]);
+var PropertyKey = (input) => If2(If2(PropertyKeyNumber(input), ([_0, input2]) => [_0, input2], () => If2(PropertyKeyIdent(input), ([_0, input2]) => [_0, input2], () => If2(PropertyKeyQuoted(input), ([_0, input2]) => [_0, input2], () => If2(PropertyKeyIndex(input), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [PropertyKeyMapping(_0), input2]);
+var Readonly2 = (input) => If2(If2(If2(Const("readonly", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ReadonlyMapping(_0), input2]);
+var Optional3 = (input) => If2(If2(If2(Const("?", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [OptionalMapping(_0), input2]);
+var Property = (input) => If2(If2(Readonly2(input), ([_0, input2]) => If2(PropertyKey(input2), ([_1, input3]) => If2(Optional3(input3), ([_2, input4]) => If2(Const(":", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [PropertyMapping(_0), input2]);
+var PropertyDelimiter = (input) => If2(If2(If2(Const(",", input), ([_0, input2]) => If2(Const("\n", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(";", input), ([_0, input2]) => If2(Const("\n", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(",", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2(If2(Const(";", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2(If2(Const("\n", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => []))))), ([_0, input2]) => [PropertyDelimiterMapping(_0), input2]);
+var PropertyList_0 = (input, result = []) => If2(If2(PropertyDelimiter(input), ([_0, input2]) => If2(Property(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => PropertyList_0(input2, [...result, _0]), () => [result, input]);
+var PropertyList = (input) => If2(If2(If2(Property(input), ([_0, input2]) => If2(PropertyList_0(input2), ([_1, input3]) => If2(If2(PropertyDelimiter(input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [PropertyListMapping(_0), input2]);
+var Properties = (input) => If2(If2(Const("{", input), ([_0, input2]) => If2(PropertyList(input2), ([_1, input3]) => If2(Const("}", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [PropertiesMapping(_0), input2]);
+var _Object_2 = (input) => If2(Properties(input), ([_0, input2]) => [_Object_Mapping(_0), input2]);
+var ElementNamed = (input) => If2(If2(If2(Ident(input), ([_0, input2]) => If2(Const("?", input2), ([_1, input3]) => If2(Const(":", input3), ([_2, input4]) => If2(Const("readonly", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [_0, input2], () => If2(If2(Ident(input), ([_0, input2]) => If2(Const(":", input2), ([_1, input3]) => If2(Const("readonly", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [_0, input2], () => If2(If2(Ident(input), ([_0, input2]) => If2(Const("?", input2), ([_1, input3]) => If2(Const(":", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [_0, input2], () => If2(If2(Ident(input), ([_0, input2]) => If2(Const(":", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [ElementNamedMapping(_0), input2]);
+var ElementBase = (input) => If2(If2(ElementNamed(input), ([_0, input2]) => [_0, input2], () => If2(If2(Readonly2(input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => If2(Optional3(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ElementBaseMapping(_0), input2]);
+var Element = (input) => If2(If2(If2(Const("...", input), ([_0, input2]) => If2(ElementBase(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(ElementBase(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ElementMapping(_0), input2]);
+var ElementList_0 = (input, result = []) => If2(If2(Const(",", input), ([_0, input2]) => If2(Element(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => ElementList_0(input2, [...result, _0]), () => [result, input]);
+var ElementList = (input) => If2(If2(If2(Element(input), ([_0, input2]) => If2(ElementList_0(input2), ([_1, input3]) => If2(If2(Const(",", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ElementListMapping(_0), input2]);
+var _Tuple_ = (input) => If2(If2(Const("[", input), ([_0, input2]) => If2(ElementList(input2), ([_1, input3]) => If2(Const("]", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_Tuple_Mapping(_0), input2]);
+var ParameterReadonlyOptional = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const("?", input2), ([_1, input3]) => If2(Const(":", input3), ([_2, input4]) => If2(Const("readonly", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [ParameterReadonlyOptionalMapping(_0), input2]);
+var ParameterReadonly = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(":", input2), ([_1, input3]) => If2(Const("readonly", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [ParameterReadonlyMapping(_0), input2]);
+var ParameterOptional = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const("?", input2), ([_1, input3]) => If2(Const(":", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [ParameterOptionalMapping(_0), input2]);
+var ParameterType = (input) => If2(If2(Ident(input), ([_0, input2]) => If2(Const(":", input2), ([_1, input3]) => If2(Type(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [ParameterTypeMapping(_0), input2]);
+var ParameterBase = (input) => If2(If2(ParameterReadonlyOptional(input), ([_0, input2]) => [_0, input2], () => If2(ParameterReadonly(input), ([_0, input2]) => [_0, input2], () => If2(ParameterOptional(input), ([_0, input2]) => [_0, input2], () => If2(ParameterType(input), ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [ParameterBaseMapping(_0), input2]);
+var Parameter2 = (input) => If2(If2(If2(Const("...", input), ([_0, input2]) => If2(ParameterBase(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(ParameterBase(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ParameterMapping(_0), input2]);
+var ParameterList_0 = (input, result = []) => If2(If2(Const(",", input), ([_0, input2]) => If2(Parameter2(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => ParameterList_0(input2, [...result, _0]), () => [result, input]);
+var ParameterList = (input) => If2(If2(If2(Parameter2(input), ([_0, input2]) => If2(ParameterList_0(input2), ([_1, input3]) => If2(If2(Const(",", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ParameterListMapping(_0), input2]);
+var _Function_2 = (input) => If2(If2(Const("(", input), ([_0, input2]) => If2(ParameterList(input2), ([_1, input3]) => If2(Const(")", input3), ([_2, input4]) => If2(Const("=>", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [_Function_Mapping(_0), input2]);
+var _Constructor_ = (input) => If2(If2(Const("new", input), ([_0, input2]) => If2(Const("(", input2), ([_1, input3]) => If2(ParameterList(input3), ([_2, input4]) => If2(Const(")", input4), ([_3, input5]) => If2(Const("=>", input5), ([_4, input6]) => If2(Type(input6), ([_5, input7]) => [[_0, _1, _2, _3, _4, _5], input7])))))), ([_0, input2]) => [_Constructor_Mapping(_0), input2]);
+var MappedReadonly = (input) => If2(If2(If2(Const("+", input), ([_0, input2]) => If2(Const("readonly", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const("-", input), ([_0, input2]) => If2(Const("readonly", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const("readonly", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [MappedReadonlyMapping(_0), input2]);
+var MappedOptional = (input) => If2(If2(If2(Const("+", input), ([_0, input2]) => If2(Const("?", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const("-", input), ([_0, input2]) => If2(Const("?", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const("?", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])))), ([_0, input2]) => [MappedOptionalMapping(_0), input2]);
+var MappedAs = (input) => If2(If2(If2(Const("as", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [MappedAsMapping(_0), input2]);
+var _Mapped_ = (input) => If2(If2(Const("{", input), ([_0, input2]) => If2(MappedReadonly(input2), ([_1, input3]) => If2(Const("[", input3), ([_2, input4]) => If2(Ident(input4), ([_3, input5]) => If2(Const("in", input5), ([_4, input6]) => If2(Type(input6), ([_5, input7]) => If2(MappedAs(input7), ([_6, input8]) => If2(Const("]", input8), ([_7, input9]) => If2(MappedOptional(input9), ([_8, input10]) => If2(Const(":", input10), ([_9, input11]) => If2(Type(input11), ([_10, input12]) => If2(OptionalSemiColon(input12), ([_11, input13]) => If2(Const("}", input13), ([_12, input14]) => [[_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12], input14]))))))))))))), ([_0, input2]) => [_Mapped_Mapping(_0), input2]);
+var Reference = (input) => If2(Ident(input), ([_0, input2]) => [ReferenceMapping(_0), input2]);
+var WithBigInt = (input) => If2(BigInt3(input), ([_0, input2]) => [WithBigIntMapping(_0), input2]);
+var WithNumber = (input) => If2(Number3(input), ([_0, input2]) => [WithNumberMapping(_0), input2]);
+var WithBoolean = (input) => If2(If2(Const("true", input), ([_0, input2]) => [_0, input2], () => If2(Const("false", input), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [WithBooleanMapping(_0), input2]);
+var WithString = (input) => If2(String3(['"', "'"], input), ([_0, input2]) => [WithStringMapping(_0), input2]);
+var WithNull = (input) => If2(Const("null", input), ([_0, input2]) => [WithNullMapping(_0), input2]);
+var WithUndefined = (input) => If2(Const("undefined", input), ([_0, input2]) => [WithUndefinedMapping(_0), input2]);
+var WithProperty = (input) => If2(If2(PropertyKey(input), ([_0, input2]) => If2(Const(":", input2), ([_1, input3]) => If2(WithValue(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [WithPropertyMapping(_0), input2]);
+var WithPropertyList_0 = (input, result = []) => If2(If2(PropertyDelimiter(input), ([_0, input2]) => If2(WithProperty(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => WithPropertyList_0(input2, [...result, _0]), () => [result, input]);
+var WithPropertyList = (input) => If2(If2(If2(WithProperty(input), ([_0, input2]) => If2(WithPropertyList_0(input2), ([_1, input3]) => If2(If2(PropertyDelimiter(input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [WithPropertyListMapping(_0), input2]);
+var WithObject = (input) => If2(If2(Const("{", input), ([_0, input2]) => If2(WithPropertyList(input2), ([_1, input3]) => If2(Const("}", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [WithObjectMapping(_0), input2]);
+var WithElementList_0 = (input, result = []) => If2(If2(Const(",", input), ([_0, input2]) => If2(WithValue(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => WithElementList_0(input2, [...result, _0]), () => [result, input]);
+var WithElementList = (input) => If2(If2(If2(WithValue(input), ([_0, input2]) => If2(WithElementList_0(input2), ([_1, input3]) => If2(If2(Const(",", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [WithElementListMapping(_0), input2]);
+var WithArray = (input) => If2(If2(Const("[", input), ([_0, input2]) => If2(WithElementList(input2), ([_1, input3]) => If2(Const("]", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [WithArrayMapping(_0), input2]);
+var WithValue = (input) => If2(If2(WithBigInt(input), ([_0, input2]) => [_0, input2], () => If2(WithNumber(input), ([_0, input2]) => [_0, input2], () => If2(WithBoolean(input), ([_0, input2]) => [_0, input2], () => If2(WithString(input), ([_0, input2]) => [_0, input2], () => If2(WithNull(input), ([_0, input2]) => [_0, input2], () => If2(WithUndefined(input), ([_0, input2]) => [_0, input2], () => If2(WithObject(input), ([_0, input2]) => [_0, input2], () => If2(WithArray(input), ([_0, input2]) => [_0, input2], () => [])))))))), ([_0, input2]) => [WithValueMapping(_0), input2]);
+var PatternBigInt = (input) => If2(Const("-?(?:0|[1-9][0-9]*)n", input), ([_0, input2]) => [PatternBigIntMapping(_0), input2]);
+var PatternString = (input) => If2(Const(".*", input), ([_0, input2]) => [PatternStringMapping(_0), input2]);
+var PatternNumber = (input) => If2(Const("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?", input), ([_0, input2]) => [PatternNumberMapping(_0), input2]);
+var PatternInteger = (input) => If2(Const("-?(?:0|[1-9][0-9]*)", input), ([_0, input2]) => [PatternIntegerMapping(_0), input2]);
+var PatternNever = (input) => If2(Const("(?!)", input), ([_0, input2]) => [PatternNeverMapping(_0), input2]);
+var PatternText = (input) => If2(Until_1(["-?(?:0|[1-9][0-9]*)n", ".*", "-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?", "-?(?:0|[1-9][0-9]*)", "(?!)", "(", ")", "$", "|"], input), ([_0, input2]) => [PatternTextMapping(_0), input2]);
+var PatternBase = (input) => If2(If2(PatternBigInt(input), ([_0, input2]) => [_0, input2], () => If2(PatternString(input), ([_0, input2]) => [_0, input2], () => If2(PatternNumber(input), ([_0, input2]) => [_0, input2], () => If2(PatternInteger(input), ([_0, input2]) => [_0, input2], () => If2(PatternNever(input), ([_0, input2]) => [_0, input2], () => If2(PatternGroup(input), ([_0, input2]) => [_0, input2], () => If2(PatternText(input), ([_0, input2]) => [_0, input2], () => []))))))), ([_0, input2]) => [PatternBaseMapping(_0), input2]);
+var PatternGroup = (input) => If2(If2(Const("(", input), ([_0, input2]) => If2(PatternBody(input2), ([_1, input3]) => If2(Const(")", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [PatternGroupMapping(_0), input2]);
+var PatternUnion = (input) => If2(If2(If2(PatternTerm(input), ([_0, input2]) => If2(Const("|", input2), ([_1, input3]) => If2(PatternUnion(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2(If2(PatternTerm(input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => []))), ([_0, input2]) => [PatternUnionMapping(_0), input2]);
+var PatternTerm = (input) => If2(If2(PatternBase(input), ([_0, input2]) => If2(PatternBody(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [PatternTermMapping(_0), input2]);
+var PatternBody = (input) => If2(If2(PatternUnion(input), ([_0, input2]) => [_0, input2], () => If2(PatternTerm(input), ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [PatternBodyMapping(_0), input2]);
+var Pattern = (input) => If2(If2(Const("^", input), ([_0, input2]) => If2(PatternBody(input2), ([_1, input3]) => If2(Const("$", input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [PatternMapping(_0), input2]);
+var InterfaceDeclarationHeritageList_0 = (input, result = []) => If2(If2(Const(",", input), ([_0, input2]) => If2(Type(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => InterfaceDeclarationHeritageList_0(input2, [...result, _0]), () => [result, input]);
+var InterfaceDeclarationHeritageList = (input) => If2(If2(If2(Type(input), ([_0, input2]) => If2(InterfaceDeclarationHeritageList_0(input2), ([_1, input3]) => If2(If2(Const(",", input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [InterfaceDeclarationHeritageListMapping(_0), input2]);
+var InterfaceDeclarationHeritage = (input) => If2(If2(If2(Const("extends", input), ([_0, input2]) => If2(InterfaceDeclarationHeritageList(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [InterfaceDeclarationHeritageMapping(_0), input2]);
+var InterfaceDeclarationGeneric = (input) => If2(If2(Const("interface", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(GenericParameters(input3), ([_2, input4]) => If2(InterfaceDeclarationHeritage(input4), ([_3, input5]) => If2(Properties(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [InterfaceDeclarationGenericMapping(_0), input2]);
+var InterfaceDeclaration = (input) => If2(If2(Const("interface", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(InterfaceDeclarationHeritage(input3), ([_2, input4]) => If2(Properties(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [InterfaceDeclarationMapping(_0), input2]);
+var TypeAliasDeclarationGeneric = (input) => If2(If2(Const("type", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(GenericParameters(input3), ([_2, input4]) => If2(Const("=", input4), ([_3, input5]) => If2(Type(input5), ([_4, input6]) => [[_0, _1, _2, _3, _4], input6]))))), ([_0, input2]) => [TypeAliasDeclarationGenericMapping(_0), input2]);
+var TypeAliasDeclaration = (input) => If2(If2(Const("type", input), ([_0, input2]) => If2(Ident(input2), ([_1, input3]) => If2(Const("=", input3), ([_2, input4]) => If2(Type(input4), ([_3, input5]) => [[_0, _1, _2, _3], input5])))), ([_0, input2]) => [TypeAliasDeclarationMapping(_0), input2]);
+var ExportKeyword = (input) => If2(If2(If2(Const("export", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ExportKeywordMapping(_0), input2]);
+var ModuleDeclarationDelimiter = (input) => If2(If2(If2(Const(";", input), ([_0, input2]) => If2(Const("\n", input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [_0, input2], () => If2(If2(Const(";", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => If2(If2(Const("\n", input), ([_0, input2]) => [[_0], input2]), ([_0, input2]) => [_0, input2], () => []))), ([_0, input2]) => [ModuleDeclarationDelimiterMapping(_0), input2]);
+var ModuleDeclarationList_0 = (input, result = []) => If2(If2(ModuleDeclarationDelimiter(input), ([_0, input2]) => If2(ModuleDeclaration(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => ModuleDeclarationList_0(input2, [...result, _0]), () => [result, input]);
+var ModuleDeclarationList = (input) => If2(If2(If2(ModuleDeclaration(input), ([_0, input2]) => If2(ModuleDeclarationList_0(input2), ([_1, input3]) => If2(If2(ModuleDeclarationDelimiter(input3), ([_02, input4]) => [[_02], input4], () => [[], input3]), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [_0, input2], () => If2([[], input], ([_0, input2]) => [_0, input2], () => [])), ([_0, input2]) => [ModuleDeclarationListMapping(_0), input2]);
+var ModuleDeclaration = (input) => If2(If2(ExportKeyword(input), ([_0, input2]) => If2(If2(InterfaceDeclarationGeneric(input2), ([_02, input3]) => [_02, input3], () => If2(InterfaceDeclaration(input2), ([_02, input3]) => [_02, input3], () => If2(TypeAliasDeclarationGeneric(input2), ([_02, input3]) => [_02, input3], () => If2(TypeAliasDeclaration(input2), ([_02, input3]) => [_02, input3], () => [])))), ([_1, input3]) => If2(OptionalSemiColon(input3), ([_2, input4]) => [[_0, _1, _2], input4]))), ([_0, input2]) => [ModuleDeclarationMapping(_0), input2]);
+var Module = (input) => If2(If2(ModuleDeclaration(input), ([_0, input2]) => If2(ModuleDeclarationList(input2), ([_1, input3]) => [[_0, _1], input3])), ([_0, input2]) => [ModuleMapping(_0), input2]);
+var Script = (input) => If2(If2(Module(input), ([_0, input2]) => [_0, input2], () => If2(GenericType(input), ([_0, input2]) => [_0, input2], () => If2(Type(input), ([_0, input2]) => [_0, input2], () => []))), ([_0, input2]) => [ScriptMapping(_0), input2]);
+
+// node_modules/typebox/build/type/engine/patterns/template.mjs
+function ParseTemplateIntoTypes(template) {
+ const parsed = TemplateLiteralTypes(`\`${template}\``);
+ const result = guard_exports.IsEqual(parsed.length, 2) ? parsed[0] : Unreachable();
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/template_literal/encode.mjs
+function JoinString(input) {
+ return input.join("|");
+}
+function UnwrapTemplateLiteralPattern(pattern) {
+ return pattern.slice(1, pattern.length - 1);
+}
+function EncodeLiteral(value, right, pattern) {
+ return EncodeTypes(right, `${pattern}${value}`);
+}
+function EncodeBigInt(right, pattern) {
+ return EncodeTypes(right, `${pattern}${BigIntPattern}`);
+}
+function EncodeInteger(right, pattern) {
+ return EncodeTypes(right, `${pattern}${IntegerPattern}`);
+}
+function EncodeNumber(right, pattern) {
+ return EncodeTypes(right, `${pattern}${NumberPattern}`);
+}
+function EncodeBoolean(right, pattern) {
+ return EncodeType(Union([Literal("false"), Literal("true")]), right, pattern);
+}
+function EncodeString(right, pattern) {
+ return EncodeTypes(right, `${pattern}${StringPattern}`);
+}
+function EncodeTemplateLiteral(templatePattern, right, pattern) {
+ return EncodeTypes(right, `${pattern}${UnwrapTemplateLiteralPattern(templatePattern)}`);
+}
+function EncodeTemplateLiteralDeferred(types, right, pattern) {
+ const templateLiteral = TemplateLiteralAction(types, {});
+ const result = EncodeType(templateLiteral, right, pattern);
+ return result;
+}
+function EncodeEnum(values, right, pattern) {
+ const evaluated = EvaluateEnum(values);
+ return EncodeType(evaluated, right, pattern);
+}
+function EncodeUnion(types, right, pattern, result = []) {
+ return guard_exports.ShiftLeft(types, (head, tail) => EncodeUnion(tail, right, pattern, [...result, EncodeType(head, [], "")]), () => EncodeTypes(right, `${pattern}(${JoinString(result)})`));
+}
+function EncodeType(type, right, pattern) {
+ return IsEnum2(type) ? EncodeEnum(type.enum, right, pattern) : IsInteger3(type) ? EncodeInteger(right, pattern) : IsLiteral(type) ? EncodeLiteral(type.const, right, pattern) : IsBigInt3(type) ? EncodeBigInt(right, pattern) : IsBoolean4(type) ? EncodeBoolean(right, pattern) : IsNumber4(type) ? EncodeNumber(right, pattern) : IsString4(type) ? EncodeString(right, pattern) : IsTemplateLiteral(type) ? EncodeTemplateLiteral(type.pattern, right, pattern) : IsTemplateLiteralDeferred(type) ? EncodeTemplateLiteralDeferred(type.parameters[0], right, pattern) : IsUnion(type) ? EncodeUnion(type.anyOf, right, pattern) : NeverPattern;
+}
+function EncodeTypes(types, pattern) {
+ return guard_exports.ShiftLeft(types, (left, right) => EncodeType(left, right, pattern), () => pattern);
+}
+function EncodePattern(types) {
+ const encoded = EncodeTypes(types, "");
+ const result = `^${encoded}$`;
+ return result;
+}
+function TemplateLiteralEncode(types) {
+ const pattern = EncodePattern(types);
+ const result = TemplateLiteralCreate(pattern);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/template_literal/instantiate.mjs
+function TemplateLiteralAction(types, options) {
+ const result = CanInstantiate(types) ? memory_exports.Update(TemplateLiteralEncode(types), {}, options) : TemplateLiteralDeferred(types, options);
+ return result;
+}
+function TemplateLiteralInstantiate(context, state3, types, options) {
+ const instantiatedTypes = InstantiateTypes(context, state3, types);
+ return TemplateLiteralAction(instantiatedTypes, options);
+}
+
+// node_modules/typebox/build/type/types/template_literal.mjs
+function TemplateLiteralDeferred(types, options = {}) {
+ return Deferred("TemplateLiteral", [types], options);
+}
+function IsTemplateLiteralDeferred(value) {
+ return IsSchema2(value) && guard_exports.HasPropertyKey(value, "action") && guard_exports.IsEqual(value.action, "TemplateLiteral");
+}
+function TemplateLiteralFromTypes(types) {
+ return TemplateLiteralAction(types, {});
+}
+function TemplateLiteralFromString(template) {
+ const types = ParseTemplateIntoTypes(template);
+ return TemplateLiteralFromTypes(types);
+}
+function TemplateLiteral2(input, options = {}) {
+ const type = guard_exports.IsString(input) ? TemplateLiteralFromString(input) : TemplateLiteralFromTypes(input);
+ return memory_exports.Update(type, {}, options);
+}
+function IsTemplateLiteral(value) {
+ return IsKind(value, "TemplateLiteral");
+}
+
+// node_modules/typebox/build/type/extends/result.mjs
+var result_exports = {};
+__export(result_exports, {
+ ExtendsFalse: () => ExtendsFalse,
+ ExtendsTrue: () => ExtendsTrue,
+ ExtendsUnion: () => ExtendsUnion,
+ IsExtendsFalse: () => IsExtendsFalse,
+ IsExtendsTrue: () => IsExtendsTrue,
+ IsExtendsTrueLike: () => IsExtendsTrueLike,
+ IsExtendsUnion: () => IsExtendsUnion,
+ Match: () => Match4
+});
+function ExtendsUnion(inferred) {
+ return memory_exports.Create({ ["~kind"]: "ExtendsUnion" }, { inferred });
+}
+function IsExtendsUnion(value) {
+ return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, "~kind") && guard_exports.HasPropertyKey(value, "inferred") && guard_exports.IsEqual(value["~kind"], "ExtendsUnion") && guard_exports.IsObject(value.inferred);
+}
+function ExtendsTrue(inferred) {
+ return memory_exports.Create({ ["~kind"]: "ExtendsTrue" }, { inferred });
+}
+function IsExtendsTrue(value) {
+ return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, "~kind") && guard_exports.HasPropertyKey(value, "inferred") && guard_exports.IsEqual(value["~kind"], "ExtendsTrue") && guard_exports.IsObject(value.inferred);
+}
+function ExtendsFalse() {
+ return memory_exports.Create({ ["~kind"]: "ExtendsFalse" }, {});
+}
+function IsExtendsFalse(value) {
+ return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, "~kind") && guard_exports.IsEqual(value["~kind"], "ExtendsFalse");
+}
+function IsExtendsTrueLike(value) {
+ return IsExtendsUnion(value) || IsExtendsTrue(value);
+}
+function Match4(result, true_, false_) {
+ return IsExtendsTrueLike(result) ? true_(result.inferred) : false_();
+}
+
+// node_modules/typebox/build/type/extends/extends_right.mjs
+function ExtendsRightInfer(inferred, name, left, right) {
+ return Match4(ExtendsLeft(inferred, left, right), (checkInferred) => ExtendsTrue(memory_exports.Assign(memory_exports.Assign(inferred, checkInferred), { [name]: left })), () => ExtendsFalse());
+}
+function ExtendsRightAny(inferred, _left) {
+ return ExtendsTrue(inferred);
+}
+function ExtendsRightDependent(inferred, left, if_, then_, else_) {
+ return Match4(ExtendsLeft(inferred, left, if_), (inferred2) => Match4(ExtendsLeft(inferred2, left, then_), (inferred3) => ExtendsTrue(inferred3), () => ExtendsFalse()), () => Match4(ExtendsLeft(inferred, left, else_), (inferred2) => ExtendsTrue(inferred2), () => ExtendsFalse()));
+}
+function ExtendsRightEnum(inferred, left, right) {
+ const evaluated = EvaluateEnum(right);
+ return ExtendsLeft(inferred, left, evaluated);
+}
+function ExtendsRightIntersect(inferred, left, right) {
+ return guard_exports.ShiftLeft(right, (head, tail) => Match4(ExtendsLeft(inferred, left, head), (inferred2) => ExtendsRightIntersect(inferred2, left, tail), () => ExtendsFalse()), () => ExtendsTrue(inferred));
+}
+function ExtendsRightTemplateLiteral(inferred, left, right) {
+ const evaluated = EvaluateTemplateLiteral(right);
+ return ExtendsLeft(inferred, left, evaluated);
+}
+function ExtendsRightUnion(inferred, left, right) {
+ return guard_exports.ShiftLeft(right, (head, tail) => Match4(ExtendsLeft(inferred, left, head), (inferred2) => ExtendsTrue(inferred2), () => ExtendsRightUnion(inferred, left, tail)), () => ExtendsFalse());
+}
+function ExtendsRight(inferred, left, right) {
+ return IsAny(right) ? ExtendsRightAny(inferred, left) : IsDependent(right) ? ExtendsRightDependent(inferred, left, right.if, right.then, right.else) : IsEnum2(right) ? ExtendsRightEnum(inferred, left, right.enum) : IsInfer(right) ? ExtendsRightInfer(inferred, right.name, left, right.extends) : IsIntersect(right) ? ExtendsRightIntersect(inferred, left, right.allOf) : IsTemplateLiteral(right) ? ExtendsRightTemplateLiteral(inferred, left, right.pattern) : IsUnion(right) ? ExtendsRightUnion(inferred, left, right.anyOf) : IsUnknown(right) ? ExtendsTrue(inferred) : ExtendsFalse();
+}
+
+// node_modules/typebox/build/type/extends/any.mjs
+function ExtendsAny(inferred, left, right) {
+ return IsInfer(right) ? ExtendsRight(inferred, left, right) : IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : ExtendsUnion(inferred);
+}
+
+// node_modules/typebox/build/type/extends/array.mjs
+function ExtendsImmutable(left, right) {
+ const isImmutableLeft = IsImmutable(left);
+ const isImmutableRight = IsImmutable(right);
+ return isImmutableLeft && isImmutableRight ? true : !isImmutableLeft && isImmutableRight ? true : isImmutableLeft && !isImmutableRight ? false : true;
+}
+function ExtendsArray(inferred, arrayLeft, left, right) {
+ return IsArray3(right) ? ExtendsImmutable(arrayLeft, right) ? ExtendsLeft(inferred, left, right.items) : ExtendsFalse() : ExtendsRight(inferred, arrayLeft, right);
+}
+
+// node_modules/typebox/build/type/extends/bigint.mjs
+function ExtendsBigInt(inferred, left, right) {
+ return IsBigInt3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/boolean.mjs
+function ExtendsBoolean(inferred, left, right) {
+ return IsBoolean4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/parameters.mjs
+function ParameterCompare(inferred, left, leftRest, right, rightRest) {
+ const checkLeft = IsInfer(right) ? left : right;
+ const checkRight = IsInfer(right) ? right : left;
+ const isLeftOptional = IsOptional(left);
+ const isRightOptional = IsOptional(right);
+ return !isLeftOptional && isRightOptional ? ExtendsFalse() : Match4(ExtendsLeft(inferred, checkLeft, checkRight), (inferred2) => ExtendsParameters(inferred2, leftRest, rightRest), () => ExtendsFalse());
+}
+function ParameterRight(inferred, left, leftRest, rightRest) {
+ return guard_exports.ShiftLeft(rightRest, (head, tail) => ParameterCompare(inferred, left, leftRest, head, tail), () => IsOptional(left) ? ExtendsTrue(inferred) : ExtendsFalse());
+}
+function ParametersLeft(inferred, left, rightRest) {
+ return guard_exports.ShiftLeft(left, (head, tail) => ParameterRight(inferred, head, tail, rightRest), () => ExtendsTrue(inferred));
+}
+function ExtendsParameters(inferred, left, right) {
+ return ParametersLeft(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/return_type.mjs
+function ExtendsReturnType(inferred, left, right) {
+ return IsVoid(right) ? ExtendsTrue(inferred) : ExtendsLeft(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/constructor.mjs
+function ExtendsConstructor(inferred, parameters, returnType, right) {
+ return IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : IsConstructor3(right) ? Match4(ExtendsParameters(inferred, parameters, right["parameters"]), (inferred2) => ExtendsReturnType(inferred2, returnType, right["instanceType"]), () => ExtendsFalse()) : ExtendsFalse();
+}
+
+// node_modules/typebox/build/type/extends/dependent.mjs
+function ExtendsDependent(inferred, if_, then_, else_, right) {
+ return Match4(ExtendsLeft(inferred, if_, right), () => ExtendsLeft(inferred, then_, right), () => ExtendsLeft(inferred, else_, right));
+}
+
+// node_modules/typebox/build/type/extends/enum.mjs
+function ExtendsEnum(inferred, left, right) {
+ const evaluated = EvaluateEnum(left);
+ return ExtendsLeft(inferred, evaluated, right);
+}
+
+// node_modules/typebox/build/type/extends/function.mjs
+function ExtendsFunction(inferred, parameters, returnType, right) {
+ return IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : IsFunction3(right) ? Match4(ExtendsParameters(inferred, parameters, right["parameters"]), (inferred2) => ExtendsReturnType(inferred2, returnType, right["returnType"]), () => ExtendsFalse()) : ExtendsFalse();
+}
+
+// node_modules/typebox/build/type/extends/integer.mjs
+function ExtendsInteger(inferred, left, right) {
+ return IsInteger3(right) ? ExtendsTrue(inferred) : IsNumber4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/intersect.mjs
+function ExtendsIntersect(inferred, left, right) {
+ const evaluated = EvaluateIntersect(left);
+ return ExtendsLeft(inferred, evaluated, right);
+}
+
+// node_modules/typebox/build/type/extends/literal.mjs
+function ExtendsLiteralValue(inferred, left, right) {
+ return left === right ? ExtendsTrue(inferred) : ExtendsFalse();
+}
+function ExtendsLiteralBigInt(inferred, left, right) {
+ return IsLiteral(right) ? ExtendsLiteralValue(inferred, left, right.const) : IsBigInt3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, Literal(left), right);
+}
+function ExtendsLiteralBoolean(inferred, left, right) {
+ return IsLiteral(right) ? ExtendsLiteralValue(inferred, left, right.const) : IsBoolean4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, Literal(left), right);
+}
+function ExtendsLiteralNumber(inferred, left, right) {
+ return IsLiteral(right) ? ExtendsLiteralValue(inferred, left, right.const) : IsNumber4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, Literal(left), right);
+}
+function ExtendsLiteralString(inferred, left, right) {
+ return IsLiteral(right) ? ExtendsLiteralValue(inferred, left, right.const) : IsString4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, Literal(left), right);
+}
+function ExtendsLiteral(inferred, left, right) {
+ return guard_exports.IsBigInt(left.const) ? ExtendsLiteralBigInt(inferred, left.const, right) : guard_exports.IsBoolean(left.const) ? ExtendsLiteralBoolean(inferred, left.const, right) : guard_exports.IsNumber(left.const) ? ExtendsLiteralNumber(inferred, left.const, right) : guard_exports.IsString(left.const) ? ExtendsLiteralString(inferred, left.const, right) : Unreachable();
+}
+
+// node_modules/typebox/build/type/extends/never.mjs
+function ExtendsNever(inferred, left, right) {
+ return IsInfer(right) ? ExtendsRight(inferred, left, right) : ExtendsTrue(inferred);
+}
+
+// node_modules/typebox/build/type/extends/null.mjs
+function ExtendsNull(inferred, left, right) {
+ return IsNull3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/number.mjs
+function ExtendsNumber(inferred, left, right) {
+ return IsNumber4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/object.mjs
+function ExtendsPropertyOptional(inferred, left, right) {
+ return IsOptional(left) ? IsOptional(right) ? ExtendsTrue(inferred) : ExtendsFalse() : ExtendsTrue(inferred);
+}
+function ExtendsProperty(inferred, left, right) {
+ return (
+ // Right TInfer is TExtendsFalse
+ IsInfer(right) && IsNever(right.extends) ? ExtendsFalse() : Match4(ExtendsLeft(inferred, left, right), (inferred2) => ExtendsPropertyOptional(inferred2, left, right), () => ExtendsFalse())
+ );
+}
+function ExtractInferredProperties(keys, properties) {
+ return keys.reduce((result, key) => {
+ return key in properties ? IsExtendsTrueLike(properties[key]) ? { ...result, ...properties[key].inferred } : Unreachable() : Unreachable();
+ }, {});
+}
+function ExtendsPropertiesComparer(inferred, left, right) {
+ const properties = {};
+ for (const rightKey of guard_exports.Keys(right)) {
+ properties[rightKey] = rightKey in left ? ExtendsProperty({}, left[rightKey], right[rightKey]) : IsOptional(right[rightKey]) ? IsInfer(right[rightKey]) ? ExtendsTrue(memory_exports.Assign(inferred, { [right[rightKey].name]: right[rightKey].extends })) : ExtendsTrue(inferred) : ExtendsFalse();
+ }
+ const checked = guard_exports.Values(properties).every((result) => IsExtendsTrueLike(result));
+ const extracted = checked ? ExtractInferredProperties(guard_exports.Keys(properties), properties) : {};
+ return checked ? ExtendsTrue(extracted) : ExtendsFalse();
+}
+function ExtendsProperties(inferred, left, right) {
+ const compared = ExtendsPropertiesComparer(inferred, left, right);
+ return IsExtendsTrueLike(compared) ? ExtendsTrue(memory_exports.Assign(inferred, compared.inferred)) : ExtendsFalse();
+}
+function ExtendsObjectToObject(inferred, left, right) {
+ return ExtendsProperties(inferred, left, right);
+}
+function RecordMergeInferred(left, right) {
+ return guard_exports.Keys(right).reduce((result, key) => {
+ return {
+ ...result,
+ [key]: guard_exports.HasPropertyKey(left, key) ? IsUnion(result[key]) ? Union([...result[key].anyOf, right[key]]) : Union([left[key], right[key]]) : right[key]
+ };
+ }, left);
+}
+function ExtendsRecordComparer(properties, keys, type, result) {
+ return guard_exports.ShiftLeft(keys, (left, right) => Match4(ExtendsLeft({}, properties[left], type), (inferred) => ExtendsRecordComparer(properties, right, type, RecordMergeInferred(result, inferred)), () => ExtendsFalse()), () => ExtendsTrue(result));
+}
+function ExtendsObjectToRecord(inferred, properties, _pattern, value) {
+ const keys = guard_exports.Keys(properties);
+ const result = ExtendsRecordComparer(properties, keys, value, inferred);
+ return result;
+}
+function ExtendsObject(inferred, left, right) {
+ return IsRecord(right) ? ExtendsObjectToRecord(inferred, left, RecordPattern(right), RecordValue(right)) : IsObject3(right) ? ExtendsObjectToObject(inferred, left, right.properties) : ExtendsRight(inferred, _Object_(left), right);
+}
+
+// node_modules/typebox/build/type/extends/record.mjs
+function FromObject4(inferred, properties) {
+ return guard_exports.IsEqual(guard_exports.Keys(properties).length, 0) ? ExtendsTrue(inferred) : ExtendsFalse();
+}
+function FromRecord(inferred, _leftKey, leftValue, _rightKey, rightValue) {
+ return ExtendsLeft(inferred, leftValue, rightValue);
+}
+function ExtendsRecord(inferred, leftPattern, leftValue, right) {
+ return IsRecord(right) ? FromRecord(inferred, RecordPatternToType(leftPattern), leftValue, RecordPatternToType(RecordPattern(right)), RecordValue(right)) : IsObject3(right) ? FromObject4(inferred, right.properties) : IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : ExtendsFalse();
+}
+
+// node_modules/typebox/build/type/extends/string.mjs
+function ExtendsString(inferred, left, right) {
+ return IsString4(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/symbol.mjs
+function ExtendsSymbol(inferred, left, right) {
+ return IsSymbol3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/template_literal.mjs
+function ExtendsTemplateLiteral(inferred, left, right) {
+ const evaluated = EvaluateTemplateLiteral(left);
+ return ExtendsLeft(inferred, evaluated, right);
+}
+
+// node_modules/typebox/build/type/extends/inference.mjs
+function Inferrable(name, type) {
+ return memory_exports.Create({ "~kind": "Inferrable" }, { name, type }, {});
+}
+function IsInferable(value) {
+ return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, "~kind") && guard_exports.HasPropertyKey(value, "name") && guard_exports.HasPropertyKey(value, "type") && guard_exports.IsEqual(value["~kind"], "Inferrable") && guard_exports.IsString(value.name) && guard_exports.IsObject(value.type);
+}
+function TryRestInferable(type) {
+ return IsRest(type) ? IsInfer(type.items) ? IsArray3(type.items.extends) ? Inferrable(type.items.name, type.items.extends.items) : IsUnknown(type.items.extends) ? Inferrable(type.items.name, type.items.extends) : void 0 : Unreachable() : void 0;
+}
+function TryInferable(type) {
+ return IsInfer(type) ? Inferrable(type.name, type.extends) : void 0;
+}
+function TryInferResults(rest, right, result = []) {
+ return guard_exports.ShiftLeft(rest, (head, tail) => Match4(ExtendsLeft({}, head, right), () => TryInferResults(tail, right, [...result, head]), () => void 0), () => result);
+}
+function InferTupleResult(inferred, name, left, right) {
+ const results = TryInferResults(left, right);
+ return guard_exports.IsArray(results) ? ExtendsTrue(memory_exports.Assign(inferred, { [name]: Tuple(results) })) : ExtendsFalse();
+}
+function InferUnionResult(inferred, name, left, right) {
+ const results = TryInferResults(left, right);
+ return guard_exports.IsArray(results) ? ExtendsTrue(memory_exports.Assign(inferred, { [name]: Union(results) })) : ExtendsFalse();
+}
+
+// node_modules/typebox/build/type/extends/tuple.mjs
+function Reverse(types) {
+ return [...types].reverse();
+}
+function ApplyReverse(types, reversed) {
+ return reversed ? Reverse(types) : types;
+}
+function Reversed(types) {
+ const first = types.length > 0 ? types[0] : void 0;
+ const inferrable = IsSchema2(first) ? TryRestInferable(first) : void 0;
+ return IsSchema2(inferrable);
+}
+function ElementsCompare(inferred, reversed, left, leftRest, right, rightRest) {
+ return Match4(ExtendsLeft(inferred, left, right), (checkInferred) => Elements(checkInferred, reversed, leftRest, rightRest), () => ExtendsFalse());
+}
+function ElementsLeft(inferred, reversed, leftRest, right, rightRest) {
+ const inferable = TryRestInferable(right);
+ return (
+ // Rest Inferrable Right Means we delegate to TInferTupleResult to Generate a Result
+ IsInferable(inferable) ? InferTupleResult(inferred, inferable["name"], ApplyReverse(leftRest, reversed), inferable["type"]) : guard_exports.ShiftLeft(leftRest, (head, tail) => ElementsCompare(inferred, reversed, head, tail, right, rightRest), () => ExtendsFalse())
+ );
+}
+function ElementsRight(inferred, reversed, leftRest, rightRest) {
+ return guard_exports.ShiftLeft(rightRest, (head, tail) => ElementsLeft(inferred, reversed, leftRest, head, tail), () => guard_exports.IsEqual(leftRest.length, 0) ? ExtendsTrue(inferred) : ExtendsFalse());
+}
+function Elements(inferred, reversed, leftRest, rightRest) {
+ return ElementsRight(inferred, reversed, leftRest, rightRest);
+}
+function ExtendsTupleToTuple(inferred, left, right) {
+ const instantiatedRight = InstantiateElements(inferred, State([], []), right);
+ const reversed = Reversed(instantiatedRight);
+ return Elements(inferred, reversed, ApplyReverse(left, reversed), ApplyReverse(instantiatedRight, reversed));
+}
+function ExtendsTupleToArray(inferred, left, right) {
+ const inferrable = TryInferable(right);
+ return IsInferable(inferrable) ? InferUnionResult(inferred, inferrable["name"], left, inferrable["type"]) : guard_exports.ShiftLeft(left, (head, tail) => Match4(ExtendsLeft(inferred, head, right), (inferred2) => ExtendsTupleToArray(inferred2, tail, right), () => ExtendsFalse()), () => ExtendsTrue(inferred));
+}
+function ExtendsTuple(inferred, left, right) {
+ const instantiatedLeft = InstantiateElements(inferred, State([], []), left);
+ return IsTuple(right) ? ExtendsTupleToTuple(inferred, instantiatedLeft, right.items) : IsArray3(right) ? ExtendsTupleToArray(inferred, instantiatedLeft, right.items) : ExtendsRight(inferred, Tuple(instantiatedLeft), right);
+}
+
+// node_modules/typebox/build/type/extends/undefined.mjs
+function ExtendsUndefined(inferred, left, right) {
+ return IsVoid(right) ? ExtendsTrue(inferred) : IsUndefined3(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/union.mjs
+function ExtendsUnionSome(inferred, type, unionTypes) {
+ return guard_exports.ShiftLeft(unionTypes, (head, tail) => Match4(ExtendsLeft(inferred, type, head), (inferred2) => ExtendsTrue(inferred2), () => ExtendsUnionSome(inferred, type, tail)), () => ExtendsFalse());
+}
+function ExtendsUnionLeft(inferred, left, right) {
+ return guard_exports.ShiftLeft(left, (head, tail) => Match4(ExtendsUnionSome(inferred, head, right), (inferred2) => ExtendsUnionLeft(inferred2, tail, right), () => ExtendsFalse()), () => ExtendsTrue(inferred));
+}
+function ExtendsUnion2(inferred, left, right) {
+ const inferrable = TryInferable(right);
+ return IsInferable(inferrable) ? InferUnionResult(inferred, inferrable.name, left, inferrable.type) : IsUnion(right) ? ExtendsUnionLeft(inferred, left, right.anyOf) : ExtendsUnionLeft(inferred, left, [right]);
+}
+
+// node_modules/typebox/build/type/extends/unknown.mjs
+function ExtendsUnknown(inferred, left, right) {
+ return IsInfer(right) ? ExtendsRight(inferred, left, right) : IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : ExtendsFalse();
+}
+
+// node_modules/typebox/build/type/extends/void.mjs
+function ExtendsVoid(inferred, left, right) {
+ return IsVoid(right) ? ExtendsTrue(inferred) : ExtendsRight(inferred, left, right);
+}
+
+// node_modules/typebox/build/type/extends/extends_left.mjs
+function ExtendsLeft(inferred, left, right) {
+ return IsAny(left) ? ExtendsAny(inferred, left, right) : IsArray3(left) ? ExtendsArray(inferred, left, left.items, right) : IsBigInt3(left) ? ExtendsBigInt(inferred, left, right) : IsBoolean4(left) ? ExtendsBoolean(inferred, left, right) : IsConstructor3(left) ? ExtendsConstructor(inferred, left.parameters, left.instanceType, right) : IsDependent(left) ? ExtendsDependent(inferred, left.if, left.then, left.else, right) : IsEnum2(left) ? ExtendsEnum(inferred, left.enum, right) : IsFunction3(left) ? ExtendsFunction(inferred, left.parameters, left.returnType, right) : IsInteger3(left) ? ExtendsInteger(inferred, left, right) : IsIntersect(left) ? ExtendsIntersect(inferred, left.allOf, right) : IsLiteral(left) ? ExtendsLiteral(inferred, left, right) : IsNever(left) ? ExtendsNever(inferred, left, right) : IsNull3(left) ? ExtendsNull(inferred, left, right) : IsNumber4(left) ? ExtendsNumber(inferred, left, right) : IsObject3(left) ? ExtendsObject(inferred, left.properties, right) : IsRecord(left) ? ExtendsRecord(inferred, RecordPattern(left), RecordValue(left), right) : IsString4(left) ? ExtendsString(inferred, left, right) : IsSymbol3(left) ? ExtendsSymbol(inferred, left, right) : IsTemplateLiteral(left) ? ExtendsTemplateLiteral(inferred, left.pattern, right) : IsTuple(left) ? ExtendsTuple(inferred, left.items, right) : IsUndefined3(left) ? ExtendsUndefined(inferred, left, right) : IsUnion(left) ? ExtendsUnion2(inferred, left.anyOf, right) : IsUnknown(left) ? ExtendsUnknown(inferred, left, right) : IsVoid(left) ? ExtendsVoid(inferred, left, right) : ExtendsFalse();
+}
+
+// node_modules/typebox/build/type/engine/interface/instantiate.mjs
+function InterfaceOperation(heritage, properties) {
+ const result = EvaluateIntersect([...heritage, _Object_(properties)]);
+ return result;
+}
+function InterfaceAction(heritage, properties, options) {
+ const result = CanInstantiate(heritage) ? memory_exports.Update(InterfaceOperation(heritage, properties), {}, options) : InterfaceDeferred(heritage, properties, options);
+ return result;
+}
+function InterfaceInstantiate(context, state3, heritage, properties, options) {
+ const instantiatedHeritage = InstantiateTypes(context, state3, heritage);
+ const instantiatedProperties = InstantiateProperties(context, state3, properties);
+ return InterfaceAction(instantiatedHeritage, instantiatedProperties, options);
+}
+
+// node_modules/typebox/build/type/action/interface.mjs
+function InterfaceDeferred(heritage, properties, options = {}) {
+ return Deferred("Interface", [heritage, properties], options);
+}
+function IsInterfaceDeferred(value) {
+ return IsSchema2(value) && guard_exports.HasPropertyKey(value, "action") && guard_exports.IsEqual(value.action, "Interface");
+}
+function Interface(heritage, properties, options = {}) {
+ return InterfaceAction(heritage, properties, options);
+}
+
+// node_modules/typebox/build/type/engine/cyclic/check.mjs
+function FromRef(stack, context, ref) {
+ return stack.includes(ref) ? true : FromType3([...stack, ref], context, context[ref]);
+}
+function FromProperties(stack, context, properties) {
+ const types = PropertyValues(properties);
+ return FromTypes2(stack, context, types);
+}
+function FromTypes2(stack, context, types) {
+ return guard_exports.ShiftLeft(types, (left, right) => FromType3(stack, context, left) ? true : FromTypes2(stack, context, right), () => false);
+}
+function FromType3(stack, context, type) {
+ return IsRef2(type) ? FromRef(stack, context, type.$ref) : IsArray3(type) ? FromType3(stack, context, type.items) : IsConstructor3(type) ? FromTypes2(stack, context, [...type.parameters, type.instanceType]) : IsFunction3(type) ? FromTypes2(stack, context, [...type.parameters, type.returnType]) : IsInterfaceDeferred(type) ? FromProperties(stack, context, type.parameters[1]) : IsIntersect(type) ? FromTypes2(stack, context, type.allOf) : IsObject3(type) ? FromProperties(stack, context, type.properties) : IsUnion(type) ? FromTypes2(stack, context, type.anyOf) : IsTuple(type) ? FromTypes2(stack, context, type.items) : IsRecord(type) ? FromType3(stack, context, RecordValue(type)) : false;
+}
+function CyclicCheck(stack, context, type) {
+ const result = FromType3(stack, context, type);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/cyclic/candidates.mjs
+function ResolveCandidateKeys(context, keys) {
+ return keys.reduce((result, left) => {
+ return CyclicCheck([left], context, context[left]) ? [...result, left] : result;
+ }, []);
+}
+function CyclicCandidates(context) {
+ const keys = PropertyKeys(context);
+ const result = ResolveCandidateKeys(context, keys);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/cyclic/dependencies.mjs
+function FromRef2(context, ref, result) {
+ return result.includes(ref) ? result : ref in context ? FromType4(context, context[ref], [...result, ref]) : Unreachable();
+}
+function FromProperties2(context, properties, result) {
+ const types = PropertyValues(properties);
+ return FromTypes3(context, types, result);
+}
+function FromTypes3(context, types, result) {
+ return types.reduce((result2, left) => {
+ return FromType4(context, left, result2);
+ }, result);
+}
+function FromType4(context, type, result) {
+ return IsRef2(type) ? FromRef2(context, type.$ref, result) : IsArray3(type) ? FromType4(context, type.items, result) : IsConstructor3(type) ? FromTypes3(context, [...type.parameters, type.instanceType], result) : IsFunction3(type) ? FromTypes3(context, [...type.parameters, type.returnType], result) : IsInterfaceDeferred(type) ? FromProperties2(context, type.parameters[1], result) : IsIntersect(type) ? FromTypes3(context, type.allOf, result) : IsObject3(type) ? FromProperties2(context, type.properties, result) : IsUnion(type) ? FromTypes3(context, type.anyOf, result) : IsTuple(type) ? FromTypes3(context, type.items, result) : IsRecord(type) ? FromType4(context, RecordValue(type), result) : result;
+}
+function CyclicDependencies(context, key, type) {
+ const result = FromType4(context, type, [key]);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/cyclic/extends.mjs
+function FromRef3(_ref) {
+ return Any();
+}
+function FromProperties3(properties) {
+ return guard_exports.Keys(properties).reduce((result, key) => {
+ return { ...result, [key]: FromType5(properties[key]) };
+ }, {});
+}
+function FromTypes4(types) {
+ return types.reduce((result, left) => {
+ return [...result, FromType5(left)];
+ }, []);
+}
+function FromType5(type) {
+ return IsRef2(type) ? FromRef3(type.$ref) : IsArray3(type) ? _Array_(FromType5(type.items), ArrayOptions(type)) : IsConstructor3(type) ? Constructor(FromTypes4(type.parameters), FromType5(type.instanceType)) : IsFunction3(type) ? _Function_(FromTypes4(type.parameters), FromType5(type.returnType)) : IsIntersect(type) ? Intersect(FromTypes4(type.allOf)) : IsObject3(type) ? _Object_(FromProperties3(type.properties)) : IsRecord(type) ? Record(RecordKey(type), FromType5(RecordValue(type))) : IsUnion(type) ? Union(FromTypes4(type.anyOf)) : IsTuple(type) ? Tuple(FromTypes4(type.items)) : type;
+}
+function CyclicAnyFromParameters(defs, ref) {
+ return ref in defs ? FromType5(defs[ref]) : Unknown();
+}
+function CyclicExtends(type) {
+ return CyclicAnyFromParameters(type.$defs, type.$ref);
+}
+
+// node_modules/typebox/build/type/engine/cyclic/instantiate.mjs
+function CyclicInterface(context, heritage, properties) {
+ const instantiatedHeritage = InstantiateTypes(context, State([], []), heritage);
+ const instantiatedProperties = InstantiateProperties({}, State([], []), properties);
+ const evaluatedInterface = EvaluateIntersect([...instantiatedHeritage, _Object_(instantiatedProperties)]);
+ return evaluatedInterface;
+}
+function CyclicDefinitions(context, dependencies) {
+ const keys = guard_exports.Keys(context).filter((key) => dependencies.includes(key));
+ return keys.reduce((result, key) => {
+ const type = context[key];
+ const instantiatedType = IsInterfaceDeferred(type) ? CyclicInterface(context, type.parameters[0], type.parameters[1]) : type;
+ return { ...result, [key]: instantiatedType };
+ }, {});
+}
+function InstantiateCyclic(context, ref, type) {
+ const dependencies = CyclicDependencies(context, ref, type);
+ const definitions = CyclicDefinitions(context, dependencies);
+ const result = Cyclic(definitions, ref);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/cyclic/target.mjs
+function Resolve(defs, ref) {
+ return ref in defs ? IsRef2(defs[ref]) ? Resolve(defs, defs[ref].$ref) : defs[ref] : Never();
+}
+function CyclicTarget(defs, ref) {
+ const result = Resolve(defs, ref);
+ return result;
+}
+
+// node_modules/typebox/build/type/extends/extends.mjs
+function Canonical(type) {
+ return IsCyclic(type) ? CyclicExtends(type) : IsUnsafe(type) ? Unknown() : type;
+}
+function Extends(inferred, left, right) {
+ const canonicalLeft = Canonical(left);
+ const canonicalRight = Canonical(right);
+ return ExtendsLeft(inferred, canonicalLeft, canonicalRight);
+}
+
+// node_modules/typebox/build/type/engine/evaluate/compare.mjs
+var CompareResultEqual = 0;
+var CompareResultDisjoint = 1;
+var CompareResultLeftInside = 2;
+var CompareResultRightInside = 3;
+function Compare(left, right) {
+ const extendsCheck = [Extends({}, left, right), Extends({}, right, left)];
+ return result_exports.IsExtendsTrueLike(extendsCheck[0]) && result_exports.IsExtendsTrueLike(extendsCheck[1]) ? CompareResultEqual : result_exports.IsExtendsTrueLike(extendsCheck[0]) && result_exports.IsExtendsFalse(extendsCheck[1]) ? CompareResultLeftInside : result_exports.IsExtendsFalse(extendsCheck[0]) && result_exports.IsExtendsTrueLike(extendsCheck[1]) ? CompareResultRightInside : CompareResultDisjoint;
+}
+
+// node_modules/typebox/build/type/engine/evaluate/broaden.mjs
+function BroadenFilter(type, types, result = [], all = types) {
+ return guard_exports.ShiftLeft(types, (left, right) => {
+ const compare = Compare(type, left);
+ return guard_exports.IsEqual(compare, CompareResultLeftInside) || guard_exports.IsEqual(compare, CompareResultEqual) ? all : guard_exports.IsEqual(compare, CompareResultDisjoint) ? BroadenFilter(type, right, [...result, left], all) : BroadenFilter(type, right, result, all);
+ }, () => [...result, type]);
+}
+function BroadenType(type, types, result) {
+ const evaluated = EvaluateType(type);
+ return IsAny(evaluated) ? [evaluated] : (
+ // terminate (always the most broad)
+ IsUnknown(evaluated) ? [evaluated] : (
+ // terminate (always the most broad)
+ IsNever(evaluated) ? BroadenTypes(types, result) : (
+ // ignored: never is dropped
+ IsObject3(evaluated) ? BroadenTypes(types, [...result, evaluated]) : (
+ // objects are always considered (too expensive to compare)
+ BroadenTypes(types, BroadenFilter(evaluated, result))
+ )
+ )
+ )
+ );
+}
+function BroadenTypes(types, result = []) {
+ return guard_exports.ShiftLeft(types, (left, right) => BroadenType(left, right, result), () => result);
+}
+function Broaden(types) {
+ const broadened = BroadenTypes(types);
+ const flattened = Flatten(broadened);
+ return flattened;
+}
+
+// node_modules/typebox/build/type/engine/evaluate/instantiate.mjs
+function EvaluateAction(type, options) {
+ const result = memory_exports.Update(EvaluateType(type), {}, options);
+ return result;
+}
+function EvaluateInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return EvaluateAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/engine/call/distribute_arguments.mjs
+function CollectDistributionNames(expression, result = []) {
+ return (
+ // Conditional
+ IsDeferred(expression) && guard_exports.IsEqual(expression.action, "Conditional") ? IsRef2(expression.parameters[0]) ? CollectDistributionNames(expression.parameters[2], CollectDistributionNames(expression.parameters[3], [...result, expression.parameters[0]["$ref"]])) : CollectDistributionNames(expression.parameters[2], CollectDistributionNames(expression.parameters[3], result)) : IsDeferred(expression) && guard_exports.IsEqual(expression.action, "Mapped") ? IsDeferred(expression.parameters[1]) && guard_exports.IsEqual(expression.parameters[1].action, "KeyOf") && IsRef2(expression.parameters[1].parameters[0]) ? [...result, expression.parameters[1].parameters[0]["$ref"]] : result : result
+ );
+}
+function BuildDistributionArray(parameters, names3) {
+ return parameters.reduce((result, left) => [...result, names3.includes(left.name)], []);
+}
+function ZipDistributionArray(arguments_, distributionArray, result = []) {
+ return guard_exports.ShiftLeft(arguments_, (argumentLeft, argumentRight) => guard_exports.ShiftLeft(distributionArray, (booleanLeft, booleanRight) => ZipDistributionArray(argumentRight, booleanRight, [...result, [booleanLeft, argumentLeft]]), () => result), () => result);
+}
+function CanonicalArgument(type) {
+ return IsTemplateLiteral(type) ? EvaluateTemplateLiteral(type.pattern) : IsEnum2(type) ? EvaluateEnum(type.enum) : type;
+}
+function Expand(type) {
+ const canonicalArgument = CanonicalArgument(type);
+ return IsUnion(canonicalArgument) ? [...canonicalArgument.anyOf] : [canonicalArgument];
+}
+function Append(current, type) {
+ return current.reduce((result, left) => [...result, [...left, type]], []);
+}
+function Cross(current, variants) {
+ return variants.reduce((result, left) => {
+ return [...result, ...Append(current, left)];
+ }, []);
+}
+function Distribute2(zipped) {
+ return zipped.reduce((result, left) => {
+ return guard_exports.IsEqual(left[0], true) ? Cross(result, Expand(left[1])) : Cross(result, [left[1]]);
+ }, [[]]);
+}
+function DistributeArguments(parameters, arguments_, expression) {
+ const distributionNames = CollectDistributionNames(expression);
+ const distributionArray = BuildDistributionArray(parameters, distributionNames);
+ const zippedArguments = ZipDistributionArray(arguments_, distributionArray);
+ return IsDeferred(expression) && guard_exports.IsEqual(expression.action, "Conditional") ? Distribute2(zippedArguments) : IsDeferred(expression) && guard_exports.IsEqual(expression.action, "Mapped") ? Distribute2(zippedArguments) : [arguments_];
+}
+
+// node_modules/typebox/build/type/engine/call/resolve_target.mjs
+function FromNotResolvable() {
+ return ["(not-resolvable)", Never()];
+}
+function FromNotGeneric() {
+ return ["(not-generic)", Never()];
+}
+function FromGeneric(name, parameters, expression) {
+ return [name, Generic(parameters, expression)];
+}
+function FromRef4(context, ref, arguments_) {
+ return ref in context ? FromType6(context, ref, context[ref], arguments_) : FromNotResolvable();
+}
+function FromType6(context, name, target, arguments_) {
+ return IsGeneric(target) ? FromGeneric(name, target.parameters, target.expression) : IsRef2(target) ? FromRef4(context, target.$ref, arguments_) : FromNotGeneric();
+}
+function ResolveTarget(context, target, arguments_) {
+ return FromType6(context, "(anonymous)", target, arguments_);
+}
+
+// node_modules/typebox/build/type/engine/call/resolve_arguments.mjs
+function AssertArgumentExtends(name, type, extends_) {
+ if (IsInfer(type) || IsCall(type) || result_exports.IsExtendsTrueLike(Extends({}, type, extends_)))
+ return;
+ const cause = { parameter: name, expect: extends_, actual: type };
+ throw new Error(`Argument for parameter ${name} does not satisfy constraint`, { cause });
+}
+function BindArgument(context, state3, name, extends_, type) {
+ const instantiatedArgument = InstantiateType(context, state3, type);
+ AssertArgumentExtends(name, instantiatedArgument, extends_);
+ return memory_exports.Assign(context, { [name]: instantiatedArgument });
+}
+function BindArguments(context, state3, parameterLeft, parameterRight, arguments_) {
+ const instantiatedExtends = InstantiateType(context, state3, parameterLeft.extends);
+ const instantiatedEquals = InstantiateType(context, state3, parameterLeft.equals);
+ return guard_exports.ShiftLeft(arguments_, (left, right) => BindParameters(BindArgument(context, state3, parameterLeft["name"], instantiatedExtends, left), state3, parameterRight, right), () => BindParameters(BindArgument(context, state3, parameterLeft["name"], instantiatedExtends, instantiatedEquals), state3, parameterRight, []));
+}
+function BindParameters(context, state3, parameters, arguments_) {
+ return guard_exports.ShiftLeft(parameters, (left, right) => BindArguments(context, state3, left, right, arguments_), () => context);
+}
+function ResolveArgumentsContext(context, state3, parameters, arguments_) {
+ return BindParameters(context, state3, parameters, arguments_);
+}
+
+// node_modules/typebox/build/type/engine/call/instantiate.mjs
+var instantiationDepth = 0;
+var instantiationCount = 0;
+function InstantiationAssert() {
+ if (guard_exports.IsLessThan(instantiationCount, settings_exports.Get().maxInstantiationCount))
+ return;
+ throw Error("Type instantiation is excessively deep and possibly infinite");
+}
+function InstantiationIncrement() {
+ InstantiationAssert();
+ instantiationCount++;
+ instantiationDepth++;
+}
+function InstantiationDecrement() {
+ instantiationDepth--;
+ if (guard_exports.IsEqual(instantiationDepth, 0))
+ instantiationCount = 0;
+}
+function Peek(state3) {
+ const result = guard_exports.IsGreaterThan(state3.callstack.length, 0) ? state3.callstack[state3.callstack.length - 1] : "";
+ return result;
+}
+function IsTailCall(state3, name) {
+ const result = guard_exports.IsEqual(Peek(state3), name);
+ return result;
+}
+function CallDispatch(context, state3, target, parameters, expression, arguments_) {
+ InstantiationIncrement();
+ try {
+ const argumentsContext = ResolveArgumentsContext(context, state3, parameters, arguments_);
+ const returnType = InstantiateType(argumentsContext, State([...state3["callstack"], target["$ref"]], state3["visited"]), expression);
+ return InstantiateType(argumentsContext, State([], []), returnType);
+ } finally {
+ InstantiationDecrement();
+ }
+}
+function CallDistributed(context, state3, target, parameters, expression, distributedArguments) {
+ return distributedArguments.reduce((result, arguments_) => {
+ const returnType = CallDispatch(context, state3, target, parameters, expression, arguments_);
+ return [...result, returnType];
+ }, []);
+}
+function CallImmediate(context, state3, target, parameters, expression, arguments_) {
+ const distributedArguments = DistributeArguments(parameters, arguments_, expression);
+ const returnTypes = CallDistributed(context, state3, target, parameters, expression, distributedArguments);
+ const result = guard_exports.IsEqual(returnTypes.length, 1) ? returnTypes[0] : EvaluateUnion(returnTypes);
+ return result;
+}
+function CallInstantiate(context, state3, target, arguments_) {
+ const instantiatedArguments = InstantiateTypes(context, state3, arguments_);
+ const resolved = ResolveTarget(context, target, arguments_);
+ const name = resolved[0];
+ const type = resolved[1];
+ const result = IsGeneric(type) ? IsTailCall(state3, name) ? CallConstruct(Ref2(name), instantiatedArguments) : CallImmediate(context, state3, Ref2(name), type.parameters, type.expression, instantiatedArguments) : CallConstruct(target, instantiatedArguments);
+ return result;
+}
+
+// node_modules/typebox/build/type/types/call.mjs
+function CallConstruct(target, arguments_) {
+ return memory_exports.Create({ ["~kind"]: "Call" }, { type: "call", target, arguments: arguments_ }, {});
+}
+function Call2(target, arguments_) {
+ return CallInstantiate({}, State([], []), target, arguments_);
+}
+function IsCall(value) {
+ return IsKind(value, "Call");
+}
+
+// node_modules/typebox/build/type/engine/immutable/instantiate_remove.mjs
+function RemoveImmutableOperation(type) {
+ return memory_exports.Discard(type, ["~immutable"]);
+}
+function RemoveImmutableAction(type, options) {
+ const result = memory_exports.Update(RemoveImmutableOperation(type), {}, options);
+ return result;
+}
+function RemoveImmutableInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return RemoveImmutableAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/engine/intrinsics/mapping.mjs
+function ApplyMapping(mapping, value) {
+ return mapping(value);
+}
+
+// node_modules/typebox/build/type/engine/intrinsics/from_literal.mjs
+function FromLiteral3(mapping, value) {
+ return guard_exports.IsString(value) ? Literal(ApplyMapping(mapping, value)) : Literal(value);
+}
+
+// node_modules/typebox/build/type/engine/intrinsics/from_template_literal.mjs
+function FromTemplateLiteral(mapping, pattern) {
+ const evaluated = EvaluateTemplateLiteral(pattern);
+ const result = FromType7(mapping, evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/intrinsics/from_union.mjs
+function FromUnion2(mapping, types) {
+ const result = types.map((type) => FromType7(mapping, type));
+ return Union(result);
+}
+
+// node_modules/typebox/build/type/engine/intrinsics/from_type.mjs
+function FromType7(mapping, type) {
+ return IsLiteral(type) ? FromLiteral3(mapping, type.const) : IsTemplateLiteral(type) ? FromTemplateLiteral(mapping, type.pattern) : IsUnion(type) ? FromUnion2(mapping, type.anyOf) : type;
+}
+
+// node_modules/typebox/build/type/action/capitalize.mjs
+function CapitalizeDeferred(type, options = {}) {
+ return Deferred("Capitalize", [type], options);
+}
+function Capitalize(type, options = {}) {
+ return CapitalizeAction(type, options);
+}
+
+// node_modules/typebox/build/type/action/lowercase.mjs
+function LowercaseDeferred(type, options = {}) {
+ return Deferred("Lowercase", [type], options);
+}
+function Lowercase(type, options = {}) {
+ return LowercaseAction(type, options);
+}
+
+// node_modules/typebox/build/type/action/uncapitalize.mjs
+function UncapitalizeDeferred(type, options = {}) {
+ return Deferred("Uncapitalize", [type], options);
+}
+function Uncapitalize(type, options = {}) {
+ return UncapitalizeAction(type, options);
+}
+
+// node_modules/typebox/build/type/action/uppercase.mjs
+function UppercaseDeferred(type, options = {}) {
+ return Deferred("Uppercase", [type], options);
+}
+function Uppercase(type, options = {}) {
+ return UppercaseAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/intrinsics/instantiate.mjs
+var CapitalizeMapping = (input) => input[0].toUpperCase() + input.slice(1);
+var LowercaseMapping = (input) => input.toLowerCase();
+var UncapitalizeMapping = (input) => input[0].toLowerCase() + input.slice(1);
+var UppercaseMapping = (input) => input.toUpperCase();
+function CapitalizeAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(FromType7(CapitalizeMapping, type), {}, options) : CapitalizeDeferred(type, options);
+ return result;
+}
+function LowercaseAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(FromType7(LowercaseMapping, type), {}, options) : LowercaseDeferred(type, options);
+ return result;
+}
+function UncapitalizeAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(FromType7(UncapitalizeMapping, type), {}, options) : UncapitalizeDeferred(type, options);
+ return result;
+}
+function UppercaseAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(FromType7(UppercaseMapping, type), {}, options) : UppercaseDeferred(type, options);
+ return result;
+}
+function CapitalizeInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return CapitalizeAction(instantiatedType, options);
+}
+function LowercaseInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return LowercaseAction(instantiatedType, options);
+}
+function UncapitalizeInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return UncapitalizeAction(instantiatedType, options);
+}
+function UppercaseInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return UppercaseAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/conditional.mjs
+function ConditionalDeferred(left, right, true_, false_, options = {}) {
+ return Deferred("Conditional", [left, right, true_, false_], options);
+}
+function Conditional(left, right, true_, false_, options = {}) {
+ return ConditionalAction({}, State([], []), left, right, true_, false_, options);
+}
+
+// node_modules/typebox/build/type/engine/conditional/instantiate.mjs
+function ConditionalOperation(context, state3, left, right, true_, false_) {
+ const extendsResult = Extends(context, left, right);
+ return result_exports.IsExtendsUnion(extendsResult) ? Union([InstantiateType(extendsResult.inferred, state3, true_), InstantiateType(context, state3, false_)]) : result_exports.IsExtendsTrue(extendsResult) ? InstantiateType(extendsResult.inferred, state3, true_) : InstantiateType(context, state3, false_);
+}
+function ConditionalAction(context, state3, left, right, true_, false_, options) {
+ const result = CanInstantiate([left, right]) ? memory_exports.Update(ConditionalOperation(context, state3, left, right, true_, false_), {}, options) : ConditionalDeferred(left, right, true_, false_, options);
+ return result;
+}
+function ConditionalInstantiate(context, state3, left, right, true_, false_, options) {
+ const instantiatedLeft = InstantiateType(context, state3, left);
+ const instantiatedRight = InstantiateType(context, state3, right);
+ return ConditionalAction(context, state3, instantiatedLeft, instantiatedRight, true_, false_, options);
+}
+
+// node_modules/typebox/build/type/action/constructor_parameters.mjs
+function ConstructorParametersDeferred(type, options = {}) {
+ return Deferred("ConstructorParameters", [type], options);
+}
+function ConstructorParameters(type, options = {}) {
+ return ConstructorParametersAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/constructor_parameters/instantiate.mjs
+function ConstructorParametersOperation(type) {
+ const parameters = IsConstructor3(type) ? type["parameters"] : [];
+ const instantiatedParameters = InstantiateElements({}, State([], []), parameters);
+ const result = Tuple(instantiatedParameters);
+ return result;
+}
+function ConstructorParametersAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(ConstructorParametersOperation(type), {}, options) : ConstructorParametersDeferred(type, options);
+ return result;
+}
+function ConstructorParametersInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return ConstructorParametersAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/exclude.mjs
+function ExcludeDeferred(left, right, options = {}) {
+ return Deferred("Exclude", [left, right], options);
+}
+function Exclude(left, right, options = {}) {
+ return ExcludeAction(left, right, options);
+}
+
+// node_modules/typebox/build/type/engine/exclude/instantiate.mjs
+function ExcludeAction(left, right, options) {
+ const result = CanInstantiate([left, right]) ? memory_exports.Update(ExcludeOperation(left, right), {}, options) : ExcludeDeferred(left, right, options);
+ return result;
+}
+function ExcludeInstantiate(context, state3, left, right, options) {
+ const instantiatedLeft = InstantiateType(context, state3, left);
+ const instantiatedRight = InstantiateType(context, state3, right);
+ return ExcludeAction(instantiatedLeft, instantiatedRight, options);
+}
+
+// node_modules/typebox/build/type/action/extract.mjs
+function ExtractDeferred(left, right, options = {}) {
+ return Deferred("Extract", [left, right], options);
+}
+function Extract(left, right, options = {}) {
+ return ExtractAction(left, right, options);
+}
+
+// node_modules/typebox/build/type/engine/extract/operation.mjs
+function ExtractType(left, right) {
+ const check = Extends({}, left, right);
+ const result = result_exports.IsExtendsTrueLike(check) ? [left] : [];
+ return result;
+}
+function ExtractUnion(left, right, result = []) {
+ return guard_exports.ShiftLeft(left, (head, tail) => ExtractUnion(tail, right, [...result, ...ExtractType(head, right)]), () => result);
+}
+function ExtractOperation(left, right) {
+ const evaluated = EvaluateType(left);
+ const canonical2 = IsUnion(evaluated) ? evaluated.anyOf : [evaluated];
+ const remaining = ExtractUnion(canonical2, right);
+ const result = EvaluateUnion(remaining);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/extract/instantiate.mjs
+function ExtractAction(left, right, options) {
+ const result = CanInstantiate([left, right]) ? memory_exports.Update(ExtractOperation(left, right), {}, options) : ExtractDeferred(left, right, options);
+ return result;
+}
+function ExtractInstantiate(context, state3, left, right, options) {
+ const instantiatedLeft = InstantiateType(context, state3, left);
+ const instantiatedRight = InstantiateType(context, state3, right);
+ return ExtractAction(instantiatedLeft, instantiatedRight, options);
+}
+
+// node_modules/typebox/build/type/engine/helpers/keys_to_indexer.mjs
+function KeysToLiterals(keys) {
+ return keys.reduce((result, left) => {
+ return IsLiteralValue(left) ? [...result, Literal(left)] : result;
+ }, []);
+}
+function KeysToIndexer(keys) {
+ const literals = KeysToLiterals(keys);
+ const result = Union(literals);
+ return result;
+}
+
+// node_modules/typebox/build/type/action/indexed.mjs
+function IndexDeferred(type, indexer, options = {}) {
+ return Deferred("Index", [type, indexer], options);
+}
+function Index(type, indexer_or_keys, options = {}) {
+ const indexer = guard_exports.IsArray(indexer_or_keys) ? KeysToIndexer(indexer_or_keys) : indexer_or_keys;
+ return IndexAction(type, indexer, options);
+}
+
+// node_modules/typebox/build/type/engine/object/from_cyclic.mjs
+function FromCyclic(defs, ref) {
+ const target = CyclicTarget(defs, ref);
+ const result = FromType8(target);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/object/from_dependent.mjs
+function FromDependent(if_, then_, else_) {
+ const evaluated = EvaluateDependent(if_, then_, else_);
+ const result = FromType8(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/object/from_intersect.mjs
+function CollapseIntersectProperties(left, right) {
+ const leftKeys = guard_exports.Keys(left).filter((key) => !guard_exports.HasPropertyKey(right, key));
+ const rightKeys = guard_exports.Keys(right).filter((key) => !guard_exports.HasPropertyKey(left, key));
+ const sharedKeys = guard_exports.Keys(left).filter((key) => guard_exports.HasPropertyKey(right, key));
+ const leftProperties = leftKeys.reduce((result, key) => ({ ...result, [key]: left[key] }), {});
+ const rightProperties = rightKeys.reduce((result, key) => ({ ...result, [key]: right[key] }), {});
+ const sharedProperties = sharedKeys.reduce((result, key) => ({ ...result, [key]: EvaluateIntersect([left[key], right[key]]) }), {});
+ const unique = memory_exports.Assign(leftProperties, rightProperties);
+ const shared = memory_exports.Assign(unique, sharedProperties);
+ return shared;
+}
+function FromIntersect(types) {
+ return types.reduce((result, left) => {
+ return CollapseIntersectProperties(result, FromType8(left));
+ }, {});
+}
+
+// node_modules/typebox/build/type/engine/object/from_object.mjs
+function FromObject5(properties) {
+ return properties;
+}
+
+// node_modules/typebox/build/type/engine/object/from_tuple.mjs
+function FromTuple(types) {
+ const object = TupleToObject(Tuple(types));
+ const result = FromType8(object);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/object/from_union.mjs
+function CollapseUnionProperties(left, right) {
+ const sharedKeys = guard_exports.Keys(left).filter((key) => key in right);
+ const result = sharedKeys.reduce((result2, key) => {
+ return { ...result2, [key]: EvaluateUnion([left[key], right[key]]) };
+ }, {});
+ return result;
+}
+function ReduceVariants(types, result) {
+ return guard_exports.ShiftLeft(types, (left, right) => ReduceVariants(right, CollapseUnionProperties(result, FromType8(left))), () => result);
+}
+function FromUnion3(types) {
+ return guard_exports.ShiftLeft(types, (left, right) => ReduceVariants(right, FromType8(left)), () => Unreachable());
+}
+
+// node_modules/typebox/build/type/engine/object/from_type.mjs
+function FromType8(type) {
+ return IsCyclic(type) ? FromCyclic(type.$defs, type.$ref) : IsDependent(type) ? FromDependent(type.if, type.then, type.else) : IsIntersect(type) ? FromIntersect(type.allOf) : IsUnion(type) ? FromUnion3(type.anyOf) : IsTuple(type) ? FromTuple(type.items) : IsObject3(type) ? FromObject5(type.properties) : {};
+}
+
+// node_modules/typebox/build/type/engine/object/collapse.mjs
+function CollapseToObject(type) {
+ const properties = FromType8(type);
+ const result = _Object_(properties);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/helpers/keys.mjs
+var integerKeyPattern = new RegExp("^(?:0|[1-9][0-9]*)$");
+function ConvertToIntegerKey(value) {
+ const normal = `${value}`;
+ return integerKeyPattern.test(normal) ? parseInt(normal) : value;
+}
+
+// node_modules/typebox/build/type/engine/indexed/from_array.mjs
+function NormalizeLiteral(value) {
+ return Literal(ConvertToIntegerKey(value));
+}
+function NormalizeIndexerTypes(types) {
+ return types.map((type) => NormalizeIndexer(type));
+}
+function NormalizeIndexer(type) {
+ return IsIntersect(type) ? Intersect(NormalizeIndexerTypes(type.allOf)) : IsUnion(type) ? Union(NormalizeIndexerTypes(type.anyOf)) : IsLiteral(type) ? NormalizeLiteral(type.const) : type;
+}
+function FromArray4(type, indexer) {
+ const normalizedIndexer = NormalizeIndexer(indexer);
+ const check = Extends({}, normalizedIndexer, Number2());
+ const result = (
+ // indexer
+ result_exports.IsExtendsTrueLike(check) ? type : IsLiteral(indexer) && guard_exports.IsEqual(indexer.const, "length") ? Number2() : Never()
+ );
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexable/from_cyclic.mjs
+function FromCyclic2(defs, ref) {
+ const target = CyclicTarget(defs, ref);
+ const result = FromType9(target);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexable/from_dependent.mjs
+function FromDependent2(if_, then_, else_) {
+ const evaluated = EvaluateDependent(if_, then_, else_);
+ const result = FromType9(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexable/from_enum.mjs
+function FromEnum(values) {
+ const evaluated = EvaluateEnum(values);
+ const result = FromType9(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexable/from_intersect.mjs
+function FromIntersect2(types) {
+ const evaluated = EvaluateIntersect(types);
+ const result = FromType9(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexable/from_literal.mjs
+function FromLiteral4(value) {
+ const result = [`${value}`];
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexable/from_template_literal.mjs
+function FromTemplateLiteral2(pattern) {
+ const evaluated = EvaluateTemplateLiteral(pattern);
+ const result = FromType9(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexable/from_union.mjs
+function FromUnion4(types) {
+ return types.reduce((result, left) => {
+ return [...result, ...FromType9(left)];
+ }, []);
+}
+
+// node_modules/typebox/build/type/engine/indexable/from_type.mjs
+function FromType9(type) {
+ return IsCyclic(type) ? FromCyclic2(type.$defs, type.$ref) : IsDependent(type) ? FromDependent2(type.if, type.then, type.else) : IsEnum2(type) ? FromEnum(type.enum) : IsIntersect(type) ? FromIntersect2(type.allOf) : IsLiteral(type) ? FromLiteral4(type.const) : IsTemplateLiteral(type) ? FromTemplateLiteral2(type.pattern) : IsUnion(type) ? FromUnion4(type.anyOf) : [];
+}
+
+// node_modules/typebox/build/type/engine/indexable/to_indexable_keys.mjs
+function ToIndexableKeys(type) {
+ const result = FromType9(type);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/this/expand_this.mjs
+function FromTypes5(properties, types) {
+ return types.map((type) => FromType10(properties, type));
+}
+function FromType10(properties, type) {
+ return IsArray3(type) ? _Array_(FromType10(properties, type.items)) : IsConstructor3(type) ? Constructor(FromTypes5(properties, type.parameters), FromType10(properties, type.instanceType)) : IsFunction3(type) ? _Function_(FromTypes5(properties, type.parameters), FromType10(properties, type.returnType)) : IsTuple(type) ? Tuple(FromTypes5(properties, type.items)) : IsUnion(type) ? Union(FromTypes5(properties, type.anyOf)) : IsIntersect(type) ? Intersect(FromTypes5(properties, type.allOf)) : IsThis(type) ? _Object_(properties) : type;
+}
+function ExpandThis(properties, type) {
+ const result = FromType10(properties, type);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexed/from_object.mjs
+function IndexProperty(properties, key) {
+ const selectedType = key in properties ? properties[key] : Never();
+ const result = ExpandThis(properties, selectedType);
+ return result;
+}
+function IndexProperties(properties, keys) {
+ return keys.reduce((result, left) => {
+ return [...result, IndexProperty(properties, left)];
+ }, []);
+}
+function FromIndexer(properties, indexer) {
+ const keys = ToIndexableKeys(indexer);
+ const variants = IndexProperties(properties, keys);
+ const result = EvaluateUnion(variants);
+ return result;
+}
+var NumericKeyPattern = new RegExp(IntegerKey);
+function NumericKeys(keys) {
+ const result = keys.filter((key) => NumericKeyPattern.test(key));
+ return result;
+}
+function FromIndexerNumber(properties) {
+ const keys = PropertyKeys(properties);
+ const numericKeys = NumericKeys(keys);
+ const variants = IndexProperties(properties, numericKeys);
+ const result = EvaluateUnion(variants);
+ return result;
+}
+function FromObject6(properties, indexer) {
+ const result = IsNumber4(indexer) ? FromIndexerNumber(properties) : FromIndexer(properties, indexer);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/indexed/array_indexer.mjs
+function ConvertLiteral(value) {
+ return Literal(ConvertToIntegerKey(value));
+}
+function ArrayIndexerTypes(types) {
+ return types.map((type) => FormatArrayIndexer(type));
+}
+function FormatArrayIndexer(type) {
+ return IsIntersect(type) ? Intersect(ArrayIndexerTypes(type.allOf)) : IsUnion(type) ? Union(ArrayIndexerTypes(type.anyOf)) : IsLiteral(type) ? ConvertLiteral(type.const) : type;
+}
+
+// node_modules/typebox/build/type/engine/indexed/from_tuple.mjs
+function IndexElementsWithIndexer(types, indexer) {
+ return types.reduceRight((result, right, index3) => {
+ const check = Extends({}, Literal(index3), indexer);
+ return result_exports.IsExtendsTrueLike(check) ? [right, ...result] : result;
+ }, []);
+}
+function FromTupleWithIndexer(types, indexer) {
+ const formattedArrayIndexer = FormatArrayIndexer(indexer);
+ const elements = IndexElementsWithIndexer(types, formattedArrayIndexer);
+ return EvaluateUnionFast(elements);
+}
+function FromTupleWithoutIndexer(types) {
+ return EvaluateUnionFast(types);
+}
+function FromTuple2(types, indexer) {
+ return (
+ // length (intrinsic)
+ IsLiteral(indexer) && guard_exports.IsEqual(indexer.const, "length") ? Literal(types.length) : IsNumber4(indexer) || IsInteger3(indexer) ? FromTupleWithoutIndexer(types) : FromTupleWithIndexer(types, indexer)
+ );
+}
+
+// node_modules/typebox/build/type/engine/indexed/from_type.mjs
+function FromType11(type, indexer) {
+ return IsArray3(type) ? FromArray4(type.items, indexer) : IsObject3(type) ? FromObject6(type.properties, indexer) : IsTuple(type) ? FromTuple2(type.items, indexer) : Never();
+}
+
+// node_modules/typebox/build/type/engine/indexed/instantiate.mjs
+function NormalizeType(type) {
+ const result = IsCyclic(type) || IsDependent(type) || IsIntersect(type) || IsUnion(type) ? CollapseToObject(type) : type;
+ return result;
+}
+function IndexAction(type, indexer, options) {
+ const result = CanInstantiate([type, indexer]) ? memory_exports.Update(FromType11(NormalizeType(type), indexer), {}, options) : IndexDeferred(type, indexer, options);
+ return result;
+}
+function IndexInstantiate(context, state3, type, indexer, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ const instantiatedIndexer = InstantiateType(context, state3, indexer);
+ return IndexAction(instantiatedType, instantiatedIndexer, options);
+}
+
+// node_modules/typebox/build/type/action/instance_type.mjs
+function InstanceTypeDeferred(type, options = {}) {
+ return Deferred("InstanceType", [type], options);
+}
+function InstanceType(type, options = {}) {
+ return InstanceTypeAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/instance_type/instantiate.mjs
+function InstanceTypeOperation(type) {
+ return IsConstructor3(type) ? type["instanceType"] : Never();
+}
+function InstanceTypeAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(InstanceTypeOperation(type), {}, options) : InstanceTypeDeferred(type, options);
+ return result;
+}
+function InstanceTypeInstantiate(context, state3, type, options = {}) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return InstanceTypeAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/keyof.mjs
+function KeyOfDeferred(type, options = {}) {
+ return Deferred("KeyOf", [type], options);
+}
+function KeyOf2(type, options = {}) {
+ return KeyOfAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/keyof/from_any.mjs
+function FromAny() {
+ return Union([Number2(), String2(), Symbol2()]);
+}
+
+// node_modules/typebox/build/type/engine/keyof/from_array.mjs
+function FromArray5(_type) {
+ return Number2();
+}
+
+// node_modules/typebox/build/type/engine/keyof/from_object.mjs
+function FromPropertyKeys(keys) {
+ const result = keys.reduce((result2, left) => {
+ return IsLiteralValue(left) ? [...result2, Literal(ConvertToIntegerKey(left))] : Unreachable();
+ }, []);
+ return result;
+}
+function FromObject7(properties) {
+ const propertyKeys = guard_exports.Keys(properties);
+ const variants = FromPropertyKeys(propertyKeys);
+ const result = EvaluateUnionFast(variants);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/keyof/from_record.mjs
+function FromRecord2(type) {
+ return RecordKey(type);
+}
+
+// node_modules/typebox/build/type/engine/keyof/from_tuple.mjs
+function FromTuple3(types) {
+ const result = types.map((_, index3) => Literal(index3));
+ return EvaluateUnionFast(result);
+}
+
+// node_modules/typebox/build/type/engine/keyof/from_type.mjs
+function FromType12(type) {
+ return IsAny(type) ? FromAny() : IsArray3(type) ? FromArray5(type.items) : IsObject3(type) ? FromObject7(type.properties) : IsRecord(type) ? FromRecord2(type) : IsTuple(type) ? FromTuple3(type.items) : Never();
+}
+
+// node_modules/typebox/build/type/engine/keyof/instantiate.mjs
+function NormalizeType2(type) {
+ const result = IsCyclic(type) || IsDependent(type) || IsIntersect(type) || IsUnion(type) ? CollapseToObject(type) : type;
+ return result;
+}
+function KeyOfAction(type, options) {
+ return CanInstantiate([type]) ? memory_exports.Update(FromType12(NormalizeType2(type)), {}, options) : KeyOfDeferred(type, options);
+}
+function KeyOfInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return KeyOfAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/mapped.mjs
+function MappedDeferred(identifier, type, as, property, options = {}) {
+ return Deferred("Mapped", [identifier, type, as, property], options);
+}
+function Mapped(identifier, type, as, property, options = {}) {
+ return MappedAction({}, State([], []), identifier, type, as, property, options);
+}
+
+// node_modules/typebox/build/type/engine/mapped/mapped_variants.mjs
+function FromTemplateLiteral3(pattern) {
+ const evaluated = EvaluateTemplateLiteral(pattern);
+ const result = FromType13(evaluated);
+ return result;
+}
+function FromUnion5(types) {
+ return types.reduce((result, left) => {
+ return [...result, ...FromType13(left)];
+ }, []);
+}
+function FromEnum2(values) {
+ const evaluated = EvaluateEnum(values);
+ const result = FromType13(evaluated);
+ return result;
+}
+function FromLiteral5(value) {
+ const result = guard_exports.IsNumber(value) ? [Literal(`${value}`)] : [Literal(value)];
+ return result;
+}
+function FromType13(type) {
+ const result = IsEnum2(type) ? FromEnum2(type.enum) : IsLiteral(type) ? FromLiteral5(type.const) : IsTemplateLiteral(type) ? FromTemplateLiteral3(type.pattern) : IsUnion(type) ? FromUnion5(type.anyOf) : [type];
+ return result;
+}
+function MappedVariants(type) {
+ const result = FromType13(type);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/mapped/mapped_operation.mjs
+function CanonicalAs(instantiatedAs) {
+ const result = IsTemplateLiteral(instantiatedAs) ? EvaluateTemplateLiteral(instantiatedAs.pattern) : instantiatedAs;
+ return result;
+}
+function MappedVariant(context, state3, identifier, variant, as, property) {
+ const variantContext = memory_exports.Assign(context, { [identifier["name"]]: variant });
+ const instantiatedAs = InstantiateType(variantContext, state3, as);
+ const canonicalAs = CanonicalAs(instantiatedAs);
+ const instantiatedProperty = InstantiateType(variantContext, state3, property);
+ return IsLiteralNumber(canonicalAs) || IsLiteralString(canonicalAs) ? { [canonicalAs.const]: instantiatedProperty } : {};
+}
+function MappedProperties(context, state3, identifier, variants, as, property) {
+ return variants.reduce((result, left) => {
+ return [...result, MappedVariant(context, state3, identifier, left, as, property)];
+ }, []);
+}
+function MappedObjects(properties) {
+ return properties.reduce((result, left) => {
+ return [...result, _Object_(left)];
+ }, []);
+}
+function MappedOperation(context, state3, identifier, type, as, property) {
+ const variants = MappedVariants(type);
+ const mappedProperties = MappedProperties(context, state3, identifier, variants, as, property);
+ const mappedObjects = MappedObjects(mappedProperties);
+ const result = EvaluateIntersect(mappedObjects);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/mapped/instantiate.mjs
+function MappedAction(context, state3, identifier, type, as, property, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(MappedOperation(context, state3, identifier, type, as, property), {}, options) : MappedDeferred(identifier, type, as, property, options);
+ return result;
+}
+function MappedInstantiate(context, state3, identifier, type, as, property, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return MappedAction(context, state3, identifier, instantiatedType, as, property, options);
+}
+
+// node_modules/typebox/build/type/engine/module/instantiate.mjs
+function InstantiateCyclics(context, declarations, cyclicKeys) {
+ const declarationContext = memory_exports.Assign(context, declarations);
+ const declarationKeys = guard_exports.Keys(declarations).filter((key) => cyclicKeys.includes(key));
+ return declarationKeys.reduce((result, key) => {
+ return { ...result, [key]: InstantiateCyclic(declarationContext, key, declarations[key]) };
+ }, {});
+}
+function InstantiateNonCyclics(context, declarations, cyclicKeys) {
+ const declarationContext = memory_exports.Assign(context, declarations);
+ const declarationKeys = guard_exports.Keys(declarations).filter((key) => !cyclicKeys.includes(key));
+ return declarationKeys.reduce((result, key) => {
+ return { ...result, [key]: InstantiateType(declarationContext, State([], []), declarations[key]) };
+ }, {});
+}
+function InstantiateModule(context, declarations, options) {
+ const cyclicCandidates = CyclicCandidates(declarations);
+ const instantiatedCyclics = InstantiateCyclics(context, declarations, cyclicCandidates);
+ const instantiatedNonCyclics = InstantiateNonCyclics(context, declarations, cyclicCandidates);
+ const instantiatedModule = { ...instantiatedCyclics, ...instantiatedNonCyclics };
+ return memory_exports.Update(instantiatedModule, {}, options);
+}
+function ModuleInstantiate(context, _state, declarations, options) {
+ const instantiatedModule = InstantiateModule(context, declarations, options);
+ return instantiatedModule;
+}
+
+// node_modules/typebox/build/type/action/non_nullable.mjs
+function NonNullableDeferred(type, options = {}) {
+ return Deferred("NonNullable", [type], options);
+}
+function NonNullable(type, options = {}) {
+ return NonNullableAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/non_nullable/instantiate.mjs
+function NonNullableOperation(type) {
+ const excluded2 = Union([Null(), Undefined()]);
+ return ExcludeAction(type, excluded2, {});
+}
+function NonNullableAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(NonNullableOperation(type), {}, options) : NonNullableDeferred(type, options);
+ return result;
+}
+function NonNullableInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return NonNullableAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/omit.mjs
+function OmitDeferred(type, indexer, options = {}) {
+ return Deferred("Omit", [type, indexer], options);
+}
+function Omit(type, indexer_or_keys, options = {}) {
+ const indexer = guard_exports.IsArray(indexer_or_keys) ? KeysToIndexer(indexer_or_keys) : indexer_or_keys;
+ return OmitAction(type, indexer, options);
+}
+
+// node_modules/typebox/build/type/engine/indexable/to_indexable.mjs
+function ToIndexable(type) {
+ const collapsed = CollapseToObject(type);
+ const result = IsObject3(collapsed) ? collapsed.properties : Unreachable();
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/omit/from_type.mjs
+function FromKeys(properties, keys) {
+ const result = guard_exports.Keys(properties).reduce((result2, key) => {
+ return keys.includes(key) ? result2 : { ...result2, [key]: properties[key] };
+ }, {});
+ return result;
+}
+function FromType14(type, indexer) {
+ const indexable = ToIndexable(type);
+ const indexableKeys = ToIndexableKeys(indexer);
+ const omitted = FromKeys(indexable, indexableKeys);
+ const result = _Object_(omitted);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/omit/instantiate.mjs
+function OmitAction(type, indexer, options) {
+ const result = CanInstantiate([type, indexer]) ? memory_exports.Update(FromType14(type, indexer), {}, options) : OmitDeferred(type, indexer, options);
+ return result;
+}
+function OmitInstantiate(context, state3, type, indexer, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ const instantiatedIndexer = InstantiateType(context, state3, indexer);
+ return OmitAction(instantiatedType, instantiatedIndexer, options);
+}
+
+// node_modules/typebox/build/type/action/parameters.mjs
+function ParametersDeferred(type, options = {}) {
+ return Deferred("Parameters", [type], options);
+}
+function Parameters(type, options = {}) {
+ return ParametersAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/parameters/instantiate.mjs
+function ParametersOperation(type) {
+ const parameters = IsFunction3(type) ? type["parameters"] : [];
+ const instantiatedParameters = InstantiateElements({}, State([], []), parameters);
+ const result = Tuple(instantiatedParameters);
+ return result;
+}
+function ParametersAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(ParametersOperation(type), {}, options) : ParametersDeferred(type, options);
+ return result;
+}
+function ParametersInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return ParametersAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/partial.mjs
+function PartialDeferred(type, options = {}) {
+ return Deferred("Partial", [type], options);
+}
+function Partial(type, options = {}) {
+ return PartialAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/partial/from_cyclic.mjs
+function FromCyclic3(defs, ref) {
+ const target = CyclicTarget(defs, ref);
+ const partial = FromType15(target);
+ const result = Cyclic(memory_exports.Assign(defs, { [ref]: partial }), ref);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/partial/from_dependent.mjs
+function FromDependent3(if_, then_, else_) {
+ const evaluated = EvaluateDependent(if_, then_, else_);
+ const result = FromType15(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/partial/from_intersect.mjs
+function FromIntersect3(types) {
+ const evaluated = EvaluateIntersect(types);
+ const result = FromType15(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/partial/from_union.mjs
+function FromUnion6(types) {
+ const result = types.map((type) => FromType15(type));
+ return Union(result);
+}
+
+// node_modules/typebox/build/type/engine/partial/from_object.mjs
+function FromObject8(properties) {
+ const mapped = guard_exports.Keys(properties).reduce((result2, left) => {
+ return { ...result2, [left]: AddOptional(properties[left]) };
+ }, {});
+ const result = _Object_(mapped);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/partial/from_type.mjs
+function FromType15(type) {
+ return IsCyclic(type) ? FromCyclic3(type.$defs, type.$ref) : IsDependent(type) ? FromDependent3(type.if, type.then, type.else) : IsIntersect(type) ? FromIntersect3(type.allOf) : IsUnion(type) ? FromUnion6(type.anyOf) : IsObject3(type) ? FromObject8(type.properties) : _Object_({});
+}
+
+// node_modules/typebox/build/type/engine/partial/instantiate.mjs
+function PartialAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(FromType15(type), {}, options) : PartialDeferred(type, options);
+ return result;
+}
+function PartialInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return PartialAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/pick.mjs
+function PickDeferred(type, indexer, options = {}) {
+ return Deferred("Pick", [type, indexer], options);
+}
+function Pick(type, indexer_or_keys, options = {}) {
+ const indexer = guard_exports.IsArray(indexer_or_keys) ? KeysToIndexer(indexer_or_keys) : indexer_or_keys;
+ return PickAction(type, indexer, options);
+}
+
+// node_modules/typebox/build/type/engine/pick/from_type.mjs
+function FromKeys2(properties, keys) {
+ const result = guard_exports.Keys(properties).reduce((result2, key) => {
+ return keys.includes(key) ? memory_exports.Assign(result2, { [key]: properties[key] }) : result2;
+ }, {});
+ return result;
+}
+function FromType16(type, indexer) {
+ const indexable = ToIndexable(type);
+ const keys = ToIndexableKeys(indexer);
+ const applied = FromKeys2(indexable, keys);
+ const result = _Object_(applied);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/pick/instantiate.mjs
+function PickAction(type, indexer, options) {
+ const result = CanInstantiate([type, indexer]) ? memory_exports.Update(FromType16(type, indexer), {}, options) : PickDeferred(type, indexer, options);
+ return result;
+}
+function PickInstantiate(context, state3, type, indexer, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ const instantiatedIndexer = InstantiateType(context, state3, indexer);
+ return PickAction(instantiatedType, instantiatedIndexer, options);
+}
+
+// node_modules/typebox/build/type/action/readonly_object.mjs
+function ReadonlyObjectDeferred(type, options = {}) {
+ return Deferred("ReadonlyObject", [type], options);
+}
+function ReadonlyObject(type, options = {}) {
+ return ReadonlyObjectAction(type, options);
+}
+var ReadonlyType = ReadonlyObject;
+
+// node_modules/typebox/build/type/engine/readonly_object/from_array.mjs
+function FromArray6(type) {
+ const result = AddImmutable(_Array_(type));
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/readonly_object/from_cyclic.mjs
+function FromCyclic4(defs, ref) {
+ const target = CyclicTarget(defs, ref);
+ const partial = FromType17(target);
+ const result = Cyclic(memory_exports.Assign(defs, { [ref]: partial }), ref);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/readonly_object/from_dependent.mjs
+function FromDependent4(if_, then_, else_) {
+ const evaluated = EvaluateDependent(if_, then_, else_);
+ const result = FromType17(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/readonly_object/from_intersect.mjs
+function FromIntersect4(types) {
+ const evaluated = EvaluateIntersect(types);
+ const result = FromType17(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/readonly_object/from_object.mjs
+function FromObject9(properties) {
+ const mapped = guard_exports.Keys(properties).reduce((result2, left) => {
+ return { ...result2, [left]: AddReadonly(properties[left]) };
+ }, {});
+ const result = _Object_(mapped);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/readonly_object/from_tuple.mjs
+function FromTuple4(types) {
+ const result = AddImmutable(Tuple(types));
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/readonly_object/from_union.mjs
+function FromUnion7(types) {
+ const result = types.map((type) => FromType17(type));
+ return Union(result);
+}
+
+// node_modules/typebox/build/type/engine/readonly_object/from_type.mjs
+function FromType17(type) {
+ return IsArray3(type) ? FromArray6(type.items) : IsCyclic(type) ? FromCyclic4(type.$defs, type.$ref) : IsDependent(type) ? FromDependent4(type.if, type.then, type.else) : IsIntersect(type) ? FromIntersect4(type.allOf) : IsObject3(type) ? FromObject9(type.properties) : IsTuple(type) ? FromTuple4(type.items) : IsUnion(type) ? FromUnion7(type.anyOf) : type;
+}
+
+// node_modules/typebox/build/type/engine/readonly_object/instantiate.mjs
+function ReadonlyObjectAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(FromType17(type), {}, options) : ReadonlyObjectDeferred(type);
+ return result;
+}
+function ReadonlyObjectInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return ReadonlyObjectAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/engine/ref/instantiate.mjs
+function RefInstantiate(context, state3, type, ref) {
+ return state3.visited.includes(ref) ? type : ref in context ? InstantiateType(context, State(state3["callstack"], [...state3["visited"], ref]), context[ref]) : type;
+}
+
+// node_modules/typebox/build/type/engine/required/from_cyclic.mjs
+function FromCyclic5(defs, ref) {
+ const target = CyclicTarget(defs, ref);
+ const partial = FromType18(target);
+ const result = Cyclic(memory_exports.Assign(defs, { [ref]: partial }), ref);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/required/from_dependent.mjs
+function FromDependent5(if_, then_, else_) {
+ const evaluated = EvaluateDependent(if_, then_, else_);
+ const result = FromType18(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/required/from_intersect.mjs
+function FromIntersect5(types) {
+ const evaluated = EvaluateIntersect(types);
+ const result = FromType18(evaluated);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/required/from_union.mjs
+function FromUnion8(types) {
+ const result = types.map((type) => FromType18(type));
+ return Union(result);
+}
+
+// node_modules/typebox/build/type/engine/required/from_object.mjs
+function FromObject10(properties) {
+ const mapped = guard_exports.Keys(properties).reduce((result2, left) => {
+ return { ...result2, [left]: RemoveOptional(properties[left]) };
+ }, {});
+ const result = _Object_(mapped);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/required/from_type.mjs
+function FromType18(type) {
+ return IsCyclic(type) ? FromCyclic5(type.$defs, type.$ref) : IsDependent(type) ? FromDependent5(type.if, type.then, type.else) : IsIntersect(type) ? FromIntersect5(type.allOf) : IsUnion(type) ? FromUnion8(type.anyOf) : IsObject3(type) ? FromObject10(type.properties) : _Object_({});
+}
+
+// node_modules/typebox/build/type/action/required.mjs
+function RequiredDeferred(type, options = {}) {
+ return Deferred("Required", [type], options);
+}
+function Required(type, options = {}) {
+ return RequiredAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/required/instantiate.mjs
+function RequiredAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(FromType18(type), {}, options) : RequiredDeferred(type, options);
+ return result;
+}
+function RequiredInstantiate(context, state3, type, options) {
+ const instaniatedType = InstantiateType(context, state3, type);
+ return RequiredAction(instaniatedType, options);
+}
+
+// node_modules/typebox/build/type/action/return_type.mjs
+function ReturnTypeDeferred(type, options = {}) {
+ return Deferred("ReturnType", [type], options);
+}
+function ReturnType(type, options = {}) {
+ return ReturnTypeAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/return_type/instantiate.mjs
+function ReturnTypeOperation(type) {
+ return IsFunction3(type) ? type["returnType"] : Never();
+}
+function ReturnTypeAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(ReturnTypeOperation(type), {}, options) : ReturnTypeDeferred(type, options);
+ return result;
+}
+function ReturnTypeInstantiate(context, state3, type, options = {}) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return ReturnTypeAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/with.mjs
+function WithDeferred(type, options) {
+ return Deferred("With", [type, options], {});
+}
+function With2(type, options) {
+ return WithAction(type, options);
+}
+
+// node_modules/typebox/build/type/engine/with/instantiate.mjs
+function WithAction(type, options) {
+ const result = CanInstantiate([type]) ? memory_exports.Update(type, {}, options) : WithDeferred(type, options);
+ return result;
+}
+function WithInstantiate(context, state3, type, options) {
+ const instaniatedType = InstantiateType(context, state3, type);
+ return WithAction(instaniatedType, options);
+}
+
+// node_modules/typebox/build/type/engine/rest/spread.mjs
+function SpreadElement(type) {
+ const result = IsRest(type) ? IsTuple(type.items) ? RestSpread(type.items.items) : IsInfer(type.items) ? [type] : IsRef2(type.items) ? [type] : [Never()] : [type];
+ return result;
+}
+function RestSpread(types) {
+ const result = types.reduce((result2, left) => {
+ return [...result2, ...SpreadElement(left)];
+ }, []);
+ return result;
+}
+
+// node_modules/typebox/build/type/engine/instantiate.mjs
+function State(callstack, visited2) {
+ return { callstack, visited: visited2 };
+}
+function CanInstantiate(types) {
+ return guard_exports.ShiftLeft(types, (left, right) => IsRef2(left) ? false : CanInstantiate(right), () => true);
+}
+function InstantiateProperties(context, state3, properties) {
+ return guard_exports.Keys(properties).reduce((result, key) => {
+ return { ...result, [key]: InstantiateType(context, state3, properties[key]) };
+ }, {});
+}
+function InstantiateElements(context, state3, types) {
+ const elements = InstantiateTypes(context, state3, types);
+ const result = RestSpread(elements);
+ return result;
+}
+function InstantiateTypes(context, state3, types) {
+ return types.map((type) => InstantiateType(context, state3, type));
+}
+function WithModifiers(type, instantiatedType) {
+ const withOptional = IsOptional(type) ? AddOptionalAction(instantiatedType, {}) : instantiatedType;
+ const withReadonly = IsReadonly(type) ? AddReadonlyAction(withOptional, {}) : withOptional;
+ const withImmutable = IsImmutable(type) ? AddImmutableAction(withReadonly, {}) : withReadonly;
+ return withImmutable;
+}
+function InstantiateDeferred(context, state3, action, parameters, options) {
+ return (
+ // Modifiers
+ guard_exports.IsEqual(action, "AddImmutable") ? AddImmutableInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "RemoveImmutable") ? RemoveImmutableInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "AddReadonly") ? AddReadonlyInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "RemoveReadonly") ? RemoveReadonlyInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "AddOptional") ? AddOptionalInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "RemoveOptional") ? RemoveOptionalInstantiate(context, state3, parameters[0], options) : (
+ // Actions
+ guard_exports.IsEqual(action, "Capitalize") ? CapitalizeInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Conditional") ? ConditionalInstantiate(context, state3, parameters[0], parameters[1], parameters[2], parameters[3], options) : guard_exports.IsEqual(action, "ConstructorParameters") ? ConstructorParametersInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Evaluate") ? EvaluateInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Exclude") ? ExcludeInstantiate(context, state3, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, "Extract") ? ExtractInstantiate(context, state3, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, "Index") ? IndexInstantiate(context, state3, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, "InstanceType") ? InstanceTypeInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Interface") ? InterfaceInstantiate(context, state3, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, "KeyOf") ? KeyOfInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Lowercase") ? LowercaseInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Mapped") ? MappedInstantiate(context, state3, parameters[0], parameters[1], parameters[2], parameters[3], options) : guard_exports.IsEqual(action, "Module") ? ModuleInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "NonNullable") ? NonNullableInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Pick") ? PickInstantiate(context, state3, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, "Parameters") ? ParametersInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Partial") ? PartialInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Omit") ? OmitInstantiate(context, state3, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, "ReadonlyObject") ? ReadonlyObjectInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Record") ? RecordInstantiate(context, state3, parameters[0], parameters[1], options) : guard_exports.IsEqual(action, "Required") ? RequiredInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "ReturnType") ? ReturnTypeInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "TemplateLiteral") ? TemplateLiteralInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Uncapitalize") ? UncapitalizeInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "Uppercase") ? UppercaseInstantiate(context, state3, parameters[0], options) : guard_exports.IsEqual(action, "With") ? WithInstantiate(context, state3, parameters[0], parameters[1]) : Deferred(action, parameters, options)
+ )
+ );
+}
+function InstantiateImmediate(context, state3, type) {
+ const instantiatedType = IsRef2(type) ? RefInstantiate(context, state3, type, type.$ref) : IsArray3(type) ? _Array_(InstantiateType(context, state3, type.items), ArrayOptions(type)) : IsCall(type) ? CallInstantiate(context, state3, type.target, type.arguments) : IsConstructor3(type) ? Constructor(InstantiateTypes(context, state3, type.parameters), InstantiateType(context, state3, type.instanceType), ConstructorOptions(type)) : IsFunction3(type) ? _Function_(InstantiateTypes(context, state3, type.parameters), InstantiateType(context, state3, type.returnType), FunctionOptions(type)) : IsDependent(type) ? Dependent(InstantiateType(context, state3, type.if), InstantiateType(context, state3, type.then), InstantiateType(context, state3, type.else), DependentOptions(type)) : IsIntersect(type) ? Intersect(InstantiateTypes(context, state3, type.allOf), IntersectOptions(type)) : IsObject3(type) ? _Object_(InstantiateProperties(context, state3, type.properties), ObjectOptions(type)) : IsRecord(type) ? RecordFromPattern(RecordPattern(type), InstantiateType(context, state3, RecordValue(type))) : IsRest(type) ? Rest(InstantiateType(context, state3, type.items)) : IsTuple(type) ? Tuple(InstantiateElements(context, state3, type.items), TupleOptions(type)) : IsUnion(type) ? Union(InstantiateTypes(context, state3, type.anyOf), UnionOptions(type)) : type;
+ const withModifiers = WithModifiers(type, instantiatedType);
+ return withModifiers;
+}
+function InstantiateType(context, state3, type) {
+ const result = IsDeferred(type) ? InstantiateDeferred(context, state3, type.action, type.parameters, type.options) : InstantiateImmediate(context, state3, type);
+ return result;
+}
+function Instantiate(context, type) {
+ return InstantiateType(context, State([], []), type);
+}
+
+// node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs
+function AddImmutableOperation(type) {
+ return memory_exports.Update(type, { "~immutable": true }, {});
+}
+function AddImmutableAction(type, options) {
+ const result = memory_exports.Update(AddImmutableOperation(type), {}, options);
+ return result;
+}
+function AddImmutableInstantiate(context, state3, type, options) {
+ const instantiatedType = InstantiateType(context, state3, type);
+ return AddImmutableAction(instantiatedType, options);
+}
+
+// node_modules/typebox/build/type/action/_add_immutable.mjs
+function AddImmutableDeferred(type, options = {}) {
+ return Deferred("AddImmutable", [type], options);
+}
+function AddImmutable(type, options = {}) {
+ return AddImmutableAction(type, options);
+}
+
+// node_modules/typebox/build/type/action/evaluate.mjs
+function EvaluateDeferred(type, options = {}) {
+ return Deferred("Evaluate", [type], options);
+}
+function Evaluate2(type, options = {}) {
+ return EvaluateAction(type, options);
+}
+
+// node_modules/typebox/build/type/action/module.mjs
+function ModuleDeferred(declarations, options = {}) {
+ return Deferred("Module", [declarations], options);
+}
+function Module2(declarations, options = {}) {
+ return ModuleInstantiate({}, State([], []), declarations, options);
+}
+
+// node_modules/typebox/build/type/engine/priority/priority.mjs
+function Comparer(left, right) {
+ const compareResult = Compare(left, right);
+ return guard_exports.IsEqual(compareResult, CompareResultRightInside) ? 1 : guard_exports.IsEqual(compareResult, CompareResultDisjoint) ? 1 : 0;
+}
+function Insert(type, types, result = []) {
+ return guard_exports.ShiftLeft(types, (left, right) => guard_exports.IsEqual(Comparer(type, left), 1) ? Insert(type, right, [...result, left]) : [...result, type, ...types], () => [...result, type]);
+}
+function Sort(types, result = []) {
+ return guard_exports.ShiftLeft(types, (left, right) => Sort(right, Insert(left, result)), () => result);
+}
+function Priority(types) {
+ const result = Sort(types);
+ return result;
+}
+
+// node_modules/typebox/build/type/script/script.mjs
+function Script2(...args) {
+ const [context, input, options] = arguments_exports.Match(args, {
+ 2: (script, options2) => guard_exports.IsString(script) ? [{}, script, options2] : [script, options2, {}],
+ 3: (context2, script, options2) => [context2, script, options2],
+ 1: (script) => [{}, script, {}]
+ });
+ const result = Script(input);
+ const parsed = guard_exports.IsArray(result) && guard_exports.IsEqual(result.length, 2) ? InstantiateType(context, State([], []), result[0]) : Never();
+ return memory_exports.Update(parsed, {}, options);
+}
+
+// node_modules/typebox/build/value/clean/from_array.mjs
+function FromArray7(context, type, value) {
+ if (!guard_exports.IsArray(value))
+ return value;
+ return value.map((value2) => FromType19(context, type.items, value2));
+}
+
+// node_modules/typebox/build/value/clean/from_cyclic.mjs
+function FromCyclic6(context, type, value) {
+ return FromType19({ ...context, ...type.$defs }, Ref2(type.$ref), value);
+}
+
+// node_modules/typebox/build/value/clean/from_intersect.mjs
+function EvaluateIntersection(context, type) {
+ const additionalProperties = guard_exports.HasPropertyKey(type, "unevaluatedProperties") ? { additionalProperties: type.unevaluatedProperties } : {};
+ const instantiated = Instantiate(context, type);
+ const evaluated = Evaluate2(instantiated);
+ return IsObject3(evaluated) ? With2(evaluated, additionalProperties) : evaluated;
+}
+function FromIntersect6(context, type, value) {
+ const evaluated = EvaluateIntersection(context, type);
+ return FromType19(context, evaluated, value);
+}
+
+// node_modules/typebox/build/value/clean/additional.mjs
+function GetAdditionalProperties(type) {
+ const additionalProperties = guard_exports.HasPropertyKey(type, "additionalProperties") ? type.additionalProperties : void 0;
+ return additionalProperties;
+}
+
+// node_modules/typebox/build/value/clean/from_object.mjs
+function FromObject11(context, type, value) {
+ if (!guard_exports.IsObject(value) || guard_exports.IsArray(value))
+ return value;
+ const additionalProperties = GetAdditionalProperties(type);
+ for (const key of guard_exports.Keys(value)) {
+ if (guard_exports.HasPropertyKey(type.properties, key)) {
+ value[key] = FromType19(context, type.properties[key], value[key]);
+ continue;
+ }
+ const unknownCheck = (
+ // 1. additionalProperties: true
+ guard_exports.IsBoolean(additionalProperties) && guard_exports.IsEqual(additionalProperties, true) || IsSchema2(additionalProperties) && Check2(context, additionalProperties, value[key])
+ );
+ if (unknownCheck) {
+ value[key] = FromType19(context, additionalProperties, value[key]);
+ continue;
+ }
+ delete value[key];
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/clean/from_record.mjs
+function FromRecord3(context, type, value) {
+ if (!guard_exports.IsObject(value))
+ return value;
+ const additionalProperties = GetAdditionalProperties(type);
+ const [recordPattern, recordValue] = [new RegExp(RecordPattern(type)), RecordValue(type)];
+ for (const key of guard_exports.Keys(value)) {
+ if (recordPattern.test(key)) {
+ value[key] = FromType19(context, recordValue, value[key]);
+ continue;
+ }
+ const unknownCheck = (
+ // 1. additionalProperties: true
+ guard_exports.IsBoolean(additionalProperties) && guard_exports.IsEqual(additionalProperties, true) || IsSchema2(additionalProperties) && Check2(context, additionalProperties, value[key])
+ );
+ if (unknownCheck) {
+ value[key] = FromType19(context, additionalProperties, value[key]);
+ continue;
+ }
+ delete value[key];
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/clean/from_ref.mjs
+function FromRef5(context, type, value) {
+ return guard_exports.HasPropertyKey(context, type.$ref) ? FromType19(context, context[type.$ref], value) : value;
+}
+
+// node_modules/typebox/build/value/clean/from_tuple.mjs
+function FromTuple5(context, schema, value) {
+ if (!guard_exports.IsArray(value))
+ return value;
+ const length = Math.min(value.length, schema.items.length);
+ for (let index3 = 0; index3 < length; index3++) {
+ value[index3] = FromType19(context, schema.items[index3], value[index3]);
+ }
+ return guard_exports.IsGreaterThan(value.length, length) ? value.slice(0, length) : value;
+}
+
+// node_modules/typebox/build/value/clone/clone.mjs
+function Clone2(value) {
+ return Clone(value);
+}
+
+// node_modules/typebox/build/value/clean/from_union.mjs
+function FromUnion9(context, type, value) {
+ for (const schema of type.anyOf) {
+ const clean = FromType19(context, schema, Clone2(value));
+ if (Check2(context, schema, clean))
+ return clean;
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/clean/from_type.mjs
+function FromType19(context, type, value) {
+ return IsArray3(type) ? FromArray7(context, type, value) : IsCyclic(type) ? FromCyclic6(context, type, value) : IsIntersect(type) ? FromIntersect6(context, type, value) : IsObject3(type) ? FromObject11(context, type, value) : IsRecord(type) ? FromRecord3(context, type, value) : IsRef2(type) ? FromRef5(context, type, value) : IsTuple(type) ? FromTuple5(context, type, value) : IsUnion(type) ? FromUnion9(context, type, value) : value;
+}
+
+// node_modules/typebox/build/value/shared/union_priority_sort.mjs
+function Modifiers(type, next) {
+ for (const key of guard_default.Keys(type)) {
+ if (guard_default.HasPropertyKey(next, key))
+ continue;
+ next[key] = type[key];
+ }
+ return next;
+}
+function FromProperties4(properties) {
+ const result = {};
+ for (const key of guard_default.Keys(properties))
+ result[key] = FromType20(properties[key]);
+ return result;
+}
+function FromPriorityTypes(types) {
+ return FromTypes6(Priority(types));
+}
+function FromTypes6(types) {
+ return types.map((type) => FromType20(type));
+}
+function FromType20(type) {
+ const next = IsArray3(type) ? _Array_(FromType20(type.items), ArrayOptions(type)) : IsIntersect(type) ? Intersect(FromTypes6(type.allOf)) : IsUnion(type) ? Union(FromPriorityTypes(type.anyOf)) : IsObject3(type) ? _Object_(FromProperties4(type.properties)) : IsRecord(type) ? Record(RecordKey(type), FromType20(RecordValue(type))) : IsTuple(type) ? Tuple(FromTypes6(type.items)) : type;
+ return Modifiers(type, next);
+}
+function UnionPrioritySort(type) {
+ const result = FromType20(type);
+ return result;
+}
+
+// node_modules/typebox/build/value/clean/clean.mjs
+function Clean(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ const sorted = settings_exports.Get().unionPrioritySort ? UnionPrioritySort(type) : type;
+ return FromType19(context, sorted, value);
+}
+
+// node_modules/typebox/build/value/convert/try/try.mjs
+var try_exports = {};
+__export(try_exports, {
+ Fail: () => Fail,
+ IsOk: () => IsOk,
+ Ok: () => Ok,
+ TryArray: () => TryArray,
+ TryBigInt: () => TryBigInt,
+ TryBoolean: () => TryBoolean,
+ TryNull: () => TryNull,
+ TryNumber: () => TryNumber,
+ TryString: () => TryString,
+ TryUndefined: () => TryUndefined
+});
+
+// node_modules/typebox/build/value/convert/try/try_result.mjs
+function IsOk(value) {
+ return guard_exports.IsObject(value) && guard_exports.HasPropertyKey(value, "value");
+}
+function Ok(value) {
+ return { value };
+}
+function Fail() {
+ return void 0;
+}
+
+// node_modules/typebox/build/value/convert/try/try_array.mjs
+function TryArray(value) {
+ return guard_exports.IsArray(value) ? Ok(value) : Ok([value]);
+}
+
+// node_modules/typebox/build/value/convert/try/try_bigint.mjs
+function FromBoolean2(value) {
+ return guard_exports.IsEqual(value, true) ? Ok(BigInt(1)) : Ok(BigInt(0));
+}
+var bigintPattern = /^-?(0|[1-9]\d*)n$/;
+var decimalPattern = /^-?(0|[1-9]\d*)\.\d+$/;
+var integerPattern = /^-?(0|[1-9]\d*)$/;
+function IsStringBigIntLike(value) {
+ return bigintPattern.test(value);
+}
+function IsStringDecimalLike(value) {
+ return decimalPattern.test(value);
+}
+function IsStringIntegerLike(value) {
+ return integerPattern.test(value);
+}
+function FromString2(value) {
+ const lowercase = value.toLowerCase();
+ return IsStringBigIntLike(value) ? Ok(BigInt(value.slice(0, value.length - 1))) : IsStringDecimalLike(value) ? Ok(BigInt(value.split(".")[0])) : IsStringIntegerLike(value) ? Ok(BigInt(value)) : guard_exports.IsEqual(lowercase, "false") ? Ok(BigInt(0)) : guard_exports.IsEqual(lowercase, "true") ? Ok(BigInt(1)) : Fail();
+}
+function TryBigInt(value) {
+ return guard_exports.IsBigInt(value) ? Ok(value) : guard_exports.IsBoolean(value) ? FromBoolean2(value) : guard_exports.IsNumber(value) ? Ok(BigInt(Math.trunc(value))) : guard_exports.IsNull(value) ? Ok(BigInt(0)) : guard_exports.IsString(value) ? FromString2(value) : guard_exports.IsUndefined(value) ? Ok(BigInt(0)) : Fail();
+}
+
+// node_modules/typebox/build/value/convert/try/try_boolean.mjs
+function FromBigInt2(value) {
+ return guard_exports.IsEqual(value, BigInt(0)) ? Ok(false) : guard_exports.IsEqual(value, BigInt(1)) ? Ok(true) : Fail();
+}
+function FromNumber2(value) {
+ return guard_exports.IsEqual(value, 0) ? Ok(false) : guard_exports.IsEqual(value, 1) ? Ok(true) : Fail();
+}
+function FromString3(value) {
+ return guard_exports.IsEqual(value.toLowerCase(), "false") ? Ok(false) : guard_exports.IsEqual(value.toLowerCase(), "true") ? Ok(true) : guard_exports.IsEqual(value, "0") ? Ok(false) : guard_exports.IsEqual(value, "1") ? Ok(true) : Fail();
+}
+function TryBoolean(value) {
+ return guard_exports.IsBigInt(value) ? FromBigInt2(value) : guard_exports.IsBoolean(value) ? Ok(value) : guard_exports.IsNumber(value) ? FromNumber2(value) : guard_exports.IsNull(value) ? Ok(false) : guard_exports.IsString(value) ? FromString3(value) : guard_exports.IsUndefined(value) ? Ok(false) : Fail();
+}
+
+// node_modules/typebox/build/value/convert/try/try_null.mjs
+function FromBigInt3(value) {
+ return guard_exports.IsEqual(value, BigInt(0)) ? Ok(null) : Fail();
+}
+function FromBoolean3(value) {
+ return guard_exports.IsEqual(value, false) ? Ok(null) : Fail();
+}
+function FromNumber3(value) {
+ return guard_exports.IsEqual(value, 0) ? Ok(null) : Fail();
+}
+function FromString4(value) {
+ const lowercase = value.toLowerCase();
+ const predicate = guard_exports.IsEqual(lowercase, "undefined") || guard_exports.IsEqual(lowercase, "null") || guard_exports.IsEqual(value, "") || guard_exports.IsEqual(value, "0");
+ return predicate ? Ok(null) : Fail();
+}
+function TryNull(value) {
+ return guard_exports.IsBigInt(value) ? FromBigInt3(value) : guard_exports.IsBoolean(value) ? FromBoolean3(value) : guard_exports.IsNumber(value) ? FromNumber3(value) : guard_exports.IsNull(value) ? Ok(null) : guard_exports.IsString(value) ? FromString4(value) : guard_exports.IsUndefined(value) ? Ok(null) : Fail();
+}
+
+// node_modules/typebox/build/value/convert/try/try_number.mjs
+var maxBigInt = BigInt(Number.MAX_SAFE_INTEGER);
+var minBigInt = BigInt(Number.MIN_SAFE_INTEGER);
+function FromBigInt4(value) {
+ return value <= maxBigInt && value >= minBigInt ? Ok(Number(value)) : Fail();
+}
+function FromBoolean4(value) {
+ return Ok(value ? 1 : 0);
+}
+function FromString5(value) {
+ const coerced = +value;
+ if (guard_exports.IsNumber(coerced))
+ return Ok(coerced);
+ const lowercase = value.toLowerCase();
+ if (guard_exports.IsEqual(lowercase, "false"))
+ return Ok(0);
+ if (guard_exports.IsEqual(lowercase, "true"))
+ return Ok(1);
+ const result = TryBigInt(value);
+ if (IsOk(result))
+ return result.value <= maxBigInt && result.value >= minBigInt ? Ok(Number(result.value)) : Fail();
+ return Fail();
+}
+function TryNumber(value) {
+ return guard_exports.IsBigInt(value) ? FromBigInt4(value) : guard_exports.IsBoolean(value) ? FromBoolean4(value) : guard_exports.IsNumber(value) ? Ok(value) : guard_exports.IsNull(value) ? Ok(0) : guard_exports.IsString(value) ? FromString5(value) : guard_exports.IsUndefined(value) ? Ok(0) : Fail();
+}
+
+// node_modules/typebox/build/value/convert/try/try_string.mjs
+function TryString(value) {
+ return guard_exports.IsBigInt(value) ? Ok(value.toString()) : guard_exports.IsBoolean(value) ? Ok(value.toString()) : guard_exports.IsNumber(value) ? Ok(value.toString()) : guard_exports.IsNull(value) ? Ok("null") : guard_exports.IsString(value) ? Ok(value) : guard_exports.IsUndefined(value) ? Ok("") : Fail();
+}
+
+// node_modules/typebox/build/value/convert/try/try_undefined.mjs
+function FromBigInt5(value) {
+ return guard_exports.IsEqual(value, BigInt(0)) ? Ok(void 0) : Fail();
+}
+function FromBoolean5(value) {
+ return guard_exports.IsEqual(value, false) ? Ok(void 0) : Fail();
+}
+function FromNumber4(value) {
+ return guard_exports.IsEqual(value, 0) ? Ok(void 0) : Fail();
+}
+function FromString6(value) {
+ const lowercase = value.toLowerCase();
+ const predicate = guard_exports.IsEqual(lowercase, "undefined") || guard_exports.IsEqual(lowercase, "null") || guard_exports.IsEqual(value, "") || guard_exports.IsEqual(value, "0");
+ return predicate ? Ok(void 0) : Fail();
+}
+function TryUndefined(value) {
+ return guard_exports.IsBigInt(value) ? FromBigInt5(value) : guard_exports.IsBoolean(value) ? FromBoolean5(value) : guard_exports.IsNumber(value) ? FromNumber4(value) : guard_exports.IsNull(value) ? Ok(void 0) : guard_exports.IsString(value) ? FromString6(value) : guard_exports.IsUndefined(value) ? Ok(value) : Fail();
+}
+
+// node_modules/typebox/build/value/convert/from_array.mjs
+function FromArray8(context, type, value) {
+ const result = try_exports.TryArray(value);
+ return result.value.map((value2) => FromType21(context, type.items, value2));
+}
+
+// node_modules/typebox/build/value/convert/from_bigint.mjs
+function FromBigInt6(_context, _type, value) {
+ const result = try_exports.TryBigInt(value);
+ return try_exports.IsOk(result) ? result.value : value;
+}
+
+// node_modules/typebox/build/value/convert/from_boolean.mjs
+function FromBoolean6(_context, _type, value) {
+ const result = try_exports.TryBoolean(value);
+ return try_exports.IsOk(result) ? result.value : value;
+}
+
+// node_modules/typebox/build/value/convert/from_cyclic.mjs
+function FromCyclic7(context, type, value) {
+ return FromType21({ ...context, ...type.$defs }, Ref2(type.$ref), value);
+}
+
+// node_modules/typebox/build/value/convert/from_enum.mjs
+function FromEnum3(context, type, value) {
+ return FromType21(context, Evaluate2(type), value);
+}
+
+// node_modules/typebox/build/value/convert/from_integer.mjs
+function FromInteger(_context, _type, value) {
+ const result = try_exports.TryNumber(value);
+ return try_exports.IsOk(result) ? Math.trunc(result.value) : value;
+}
+
+// node_modules/typebox/build/value/convert/from_intersect.mjs
+function FromIntersect7(context, type, value) {
+ const instantiated = Instantiate(context, type);
+ const evaluated = Evaluate2(instantiated);
+ return FromType21(context, evaluated, value);
+}
+
+// node_modules/typebox/build/value/convert/from_literal.mjs
+function FromLiteralBigInt(_context, type, value) {
+ const result = try_exports.TryBigInt(value);
+ return try_exports.IsOk(result) && guard_exports.IsEqual(type.const, result.value) ? result.value : value;
+}
+function FromLiteralBoolean(_context, type, value) {
+ const result = try_exports.TryBoolean(value);
+ return try_exports.IsOk(result) && guard_exports.IsEqual(type.const, result.value) ? result.value : value;
+}
+function FromLiteralNumber(_context, type, value) {
+ const result = try_exports.TryNumber(value);
+ return try_exports.IsOk(result) && guard_exports.IsEqual(type.const, result.value) ? result.value : value;
+}
+function FromLiteralString(_context, type, value) {
+ const result = try_exports.TryString(value);
+ return try_exports.IsOk(result) && guard_exports.IsEqual(type.const, result.value) ? result.value : value;
+}
+function FromLiteral6(context, type, value) {
+ if (guard_exports.IsEqual(type.const, value))
+ return value;
+ return IsLiteralBigInt(type) ? FromLiteralBigInt(context, type, value) : IsLiteralBoolean(type) ? FromLiteralBoolean(context, type, value) : IsLiteralNumber(type) ? FromLiteralNumber(context, type, value) : IsLiteralString(type) ? FromLiteralString(context, type, value) : Unreachable();
+}
+
+// node_modules/typebox/build/value/convert/from_null.mjs
+function FromNull2(_context, _type, value) {
+ const result = try_exports.TryNull(value);
+ return try_exports.IsOk(result) ? result.value : value;
+}
+
+// node_modules/typebox/build/value/convert/from_number.mjs
+function FromNumber5(_context, _type, value) {
+ const result = try_exports.TryNumber(value);
+ return try_exports.IsOk(result) ? result.value : value;
+}
+
+// node_modules/typebox/build/value/convert/from_additional.mjs
+function FromAdditionalProperties(context, entries, additionalProperties, value) {
+ const keys = guard_exports.Keys(value);
+ for (const [regexp, _] of entries) {
+ for (const key of keys) {
+ if (!regexp.test(key)) {
+ value[key] = FromType21(context, additionalProperties, value[key]);
+ }
+ }
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/shared/optional_undefined.mjs
+function IsOptionalUndefined(property, key, value) {
+ return IsOptional(property) && guard_exports.IsUndefined(value[key]);
+}
+
+// node_modules/typebox/build/value/convert/from_object.mjs
+function FromProperties5(context, type, value) {
+ const entries = guard_exports.EntriesRegExp(type.properties);
+ const keys = guard_exports.Keys(value);
+ for (const [regexp, property] of entries) {
+ for (const key of keys) {
+ if (!regexp.test(key) || IsOptionalUndefined(property, key, value))
+ continue;
+ value[key] = FromType21(context, property, value[key]);
+ }
+ }
+ return guard_exports.HasPropertyKey(type, "additionalProperties") && guard_exports.IsObject(type.additionalProperties) ? FromAdditionalProperties(context, entries, type.additionalProperties, value) : value;
+}
+function FromObject12(context, type, value) {
+ return guard_exports.IsObjectNotArray(value) ? FromProperties5(context, type, value) : value;
+}
+
+// node_modules/typebox/build/value/convert/from_record.mjs
+function FromPatternProperties(context, type, value) {
+ const entries = guard_exports.EntriesRegExp(type.patternProperties);
+ const keys = guard_exports.Keys(value);
+ for (const [regexp, schema] of entries) {
+ for (const key of keys) {
+ if (regexp.test(key)) {
+ value[key] = FromType21(context, schema, value[key]);
+ }
+ }
+ }
+ return guard_exports.HasPropertyKey(type, "additionalProperties") && guard_exports.IsObject(type.additionalProperties) ? FromAdditionalProperties(context, entries, type.additionalProperties, value) : value;
+}
+function FromRecord4(context, type, value) {
+ return guard_exports.IsObjectNotArray(value) ? FromPatternProperties(context, type, value) : value;
+}
+
+// node_modules/typebox/build/value/convert/from_ref.mjs
+function FromRef6(context, type, value) {
+ return guard_exports.HasPropertyKey(context, type.$ref) ? FromType21(context, context[type.$ref], value) : value;
+}
+
+// node_modules/typebox/build/value/convert/from_string.mjs
+function FromString7(_context, _type, value) {
+ const result = try_exports.TryString(value);
+ return try_exports.IsOk(result) ? result.value : value;
+}
+
+// node_modules/typebox/build/value/convert/from_template_literal.mjs
+function FromTemplateLiteral4(context, type, value) {
+ return FromType21(context, Evaluate2(type), value);
+}
+
+// node_modules/typebox/build/value/convert/from_tuple.mjs
+function FromTuple6(context, type, value) {
+ if (!guard_exports.IsArray(value))
+ return value;
+ for (let index3 = 0; index3 < Math.min(type.items.length, value.length); index3++) {
+ value[index3] = FromType21(context, type.items[index3], value[index3]);
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/convert/from_undefined.mjs
+function FromUndefined2(_context, _type, value) {
+ const result = try_exports.TryUndefined(value);
+ return try_exports.IsOk(result) ? result.value : value;
+}
+
+// node_modules/typebox/build/value/convert/from_union.mjs
+function FromUnion10(context, type, value) {
+ const matched = type.anyOf.some((type2) => Check2(context, type2, value));
+ if (matched)
+ return value;
+ const candidates = type.anyOf.map((type2) => FromType21(context, type2, Clone2(value)));
+ const selected = candidates.find((value2) => Check2(context, type, value2));
+ return guard_exports.IsUndefined(selected) ? value : selected;
+}
+
+// node_modules/typebox/build/value/convert/from_void.mjs
+function FromVoid(_context, _type, value) {
+ const result = try_exports.TryUndefined(value);
+ return try_exports.IsOk(result) ? void 0 : value;
+}
+
+// node_modules/typebox/build/value/convert/from_type.mjs
+function FromType21(context, type, value) {
+ return IsArray3(type) ? FromArray8(context, type, value) : IsBigInt3(type) ? FromBigInt6(context, type, value) : IsBoolean4(type) ? FromBoolean6(context, type, value) : IsCyclic(type) ? FromCyclic7(context, type, value) : IsEnum2(type) ? FromEnum3(context, type, value) : IsInteger3(type) ? FromInteger(context, type, value) : IsIntersect(type) ? FromIntersect7(context, type, value) : IsLiteral(type) ? FromLiteral6(context, type, value) : IsNull3(type) ? FromNull2(context, type, value) : IsNumber4(type) ? FromNumber5(context, type, value) : IsObject3(type) ? FromObject12(context, type, value) : IsRecord(type) ? FromRecord4(context, type, value) : IsRef2(type) ? FromRef6(context, type, value) : IsString4(type) ? FromString7(context, type, value) : IsTemplateLiteral(type) ? FromTemplateLiteral4(context, type, value) : IsTuple(type) ? FromTuple6(context, type, value) : IsUndefined3(type) ? FromUndefined2(context, type, value) : IsUnion(type) ? FromUnion10(context, type, value) : IsVoid(type) ? FromVoid(context, type, value) : value;
+}
+
+// node_modules/typebox/build/value/convert/convert.mjs
+function Convert(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ return FromType21(context, type, value);
+}
+
+// node_modules/typebox/build/value/default/from_array.mjs
+function FromArray9(context, type, value) {
+ if (!guard_exports.IsArray(value))
+ return value;
+ for (let i = 0; i < value.length; i++) {
+ value[i] = FromType22(context, type.items, value[i]);
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/default/from_cyclic.mjs
+function FromCyclic8(context, type, value) {
+ return FromType22({ ...context, ...type.$defs }, Ref2(type.$ref), value);
+}
+
+// node_modules/typebox/build/value/default/from_default.mjs
+function FromDefault(type, value) {
+ if (!guard_exports.IsUndefined(value))
+ return value;
+ return guard_exports.IsFunction(type.default) ? type.default() : Clone2(type.default);
+}
+
+// node_modules/typebox/build/value/default/from_intersect.mjs
+function FromIntersect8(context, type, value) {
+ const instantiated = Instantiate(context, type);
+ const evaluated = Evaluate2(instantiated);
+ return FromType22(context, evaluated, value);
+}
+
+// node_modules/typebox/build/value/default/from_object.mjs
+function FromObject13(context, type, value) {
+ if (!guard_exports.IsObject(value))
+ return value;
+ const knownPropertyKeys = guard_exports.Keys(type.properties);
+ for (const key of knownPropertyKeys) {
+ const propertyValue = FromType22(context, type.properties[key], value[key]);
+ const isUnassignableUndefined = guard_exports.IsUndefined(propertyValue) && (IsOptional(type.properties[key]) || !guard_exports.HasPropertyKey(type.properties[key], "default"));
+ if (isUnassignableUndefined)
+ continue;
+ value[key] = propertyValue;
+ }
+ if (!IsAdditionalProperties(type) || guard_exports.IsBoolean(type.additionalProperties))
+ return value;
+ for (const key of guard_exports.Keys(value)) {
+ if (knownPropertyKeys.includes(key))
+ continue;
+ value[key] = FromType22(context, type.additionalProperties, value[key]);
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/default/from_record.mjs
+function FromRecord5(context, type, value) {
+ if (!guard_exports.IsObject(value))
+ return value;
+ const [recordKey, recordValue] = [new RegExp(RecordPattern(type)), RecordValue(type)];
+ for (const key of guard_exports.Keys(value)) {
+ if (!(recordKey.test(key) && IsDefault(recordValue)))
+ continue;
+ value[key] = FromType22(context, recordValue, value[key]);
+ }
+ if (!IsAdditionalProperties(type))
+ return value;
+ for (const key of guard_exports.Keys(value)) {
+ if (recordKey.test(key))
+ continue;
+ value[key] = FromType22(context, type.additionalProperties, value[key]);
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/default/from_ref.mjs
+function FromRef7(context, type, value) {
+ return guard_exports.HasPropertyKey(context, type.$ref) ? FromType22(context, context[type.$ref], value) : value;
+}
+
+// node_modules/typebox/build/value/default/from_tuple.mjs
+function FromTuple7(context, schema, value) {
+ if (!guard_exports.IsArray(value))
+ return value;
+ const [items, max] = [schema.items, Math.max(schema.items.length, value.length)];
+ for (let i = 0; i < max; i++) {
+ if (i < items.length)
+ value[i] = FromType22(context, items[i], value[i]);
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/default/from_union.mjs
+function FromUnion11(context, schema, value) {
+ for (const inner of schema.anyOf) {
+ const result = FromType22(context, inner, Clone2(value));
+ if (Check2(context, inner, result)) {
+ return result;
+ }
+ }
+ return value;
+}
+
+// node_modules/typebox/build/value/default/from_type.mjs
+function FromType22(context, type, value) {
+ const defaulted = IsDefault(type) ? FromDefault(type, value) : value;
+ return IsArray3(type) ? FromArray9(context, type, defaulted) : IsCyclic(type) ? FromCyclic8(context, type, defaulted) : IsIntersect(type) ? FromIntersect8(context, type, defaulted) : IsObject3(type) ? FromObject13(context, type, defaulted) : IsRecord(type) ? FromRecord5(context, type, defaulted) : IsRef2(type) ? FromRef7(context, type, defaulted) : IsTuple(type) ? FromTuple7(context, type, defaulted) : IsUnion(type) ? FromUnion11(context, type, defaulted) : defaulted;
+}
+
+// node_modules/typebox/build/value/default/default.mjs
+function Default(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ return FromType22(context, type, value);
+}
+
+// node_modules/typebox/build/value/pipeline/pipeline.mjs
+function Pipeline(pipeline) {
+ return (...args) => {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ return pipeline.reduce((result, func) => func(context, type, result), value);
+ };
+}
+
+// node_modules/typebox/build/value/codec/callback.mjs
+function Decode3(_context, type, value) {
+ return type["~codec"].decode(value);
+}
+function Encode3(_context, type, value) {
+ return type["~codec"].encode(value);
+}
+function Callback(direction, context, type, value) {
+ if (!IsCodec(type))
+ return value;
+ return guard_exports.IsEqual(direction, "Decode") ? Decode3(context, type, value) : Encode3(context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/from_array.mjs
+function Decode4(direction, context, type, value) {
+ if (!guard_exports.IsArray(value))
+ return value;
+ for (let i = 0; i < value.length; i++) {
+ value[i] = FromType23(direction, context, type.items, value[i]);
+ }
+ return Callback(direction, context, type, value);
+}
+function Encode4(direction, context, type, value) {
+ const exterior = Callback(direction, context, type, value);
+ if (!guard_exports.IsArray(exterior))
+ return exterior;
+ for (let i = 0; i < exterior.length; i++) {
+ exterior[i] = FromType23(direction, context, type.items, exterior[i]);
+ }
+ return exterior;
+}
+function FromArray10(direction, context, type, value) {
+ return guard_exports.IsEqual(direction, "Decode") ? Decode4(direction, context, type, value) : Encode4(direction, context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/from_cyclic.mjs
+function FromCyclic9(direction, context, type, value) {
+ value = FromType23(direction, { ...context, ...type.$defs }, Ref2(type.$ref), value);
+ return Callback(direction, context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/from_intersect.mjs
+function MergeInteriors(interiors) {
+ return interiors.reduce((results, interior) => ({ ...results, ...interior }), {});
+}
+function NonMatchingInterior(value, interiors) {
+ for (const interior of interiors)
+ if (!guard_exports.IsDeepEqual(value, interior))
+ return interior;
+ return value;
+}
+function Decode5(direction, context, type, value) {
+ if (guard_exports.IsEqual(type.allOf.length, 0))
+ return Callback(direction, context, type, value);
+ const interiors = type.allOf.map((schema) => FromType23(direction, context, schema, Clean(schema, Clone2(value))));
+ const structural = interiors.every((result) => guard_exports.IsObject(result));
+ const exterior = structural ? MergeInteriors(interiors) : NonMatchingInterior(value, interiors);
+ return Callback(direction, context, type, exterior);
+}
+function Encode5(direction, context, type, value) {
+ if (guard_exports.IsEqual(type.allOf.length, 0))
+ return Callback(direction, context, type, value);
+ const exterior = Callback(direction, context, type, value);
+ const interiors = type.allOf.map((schema) => FromType23(direction, context, schema, Clean(schema, Clone2(exterior))));
+ const structural = interiors.every((result) => guard_exports.IsObject(result));
+ if (structural)
+ return MergeInteriors(interiors);
+ return NonMatchingInterior(exterior, interiors);
+}
+function FromIntersect9(direction, context, type, value) {
+ return guard_exports.IsEqual(direction, "Decode") ? Decode5(direction, context, type, value) : Encode5(direction, context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/from_object.mjs
+function Decode6(direction, context, type, value) {
+ if (!guard_exports.IsObjectNotArray(value))
+ return value;
+ for (const key of guard_exports.Keys(type.properties)) {
+ if (!guard_exports.HasPropertyKey(value, key) || IsOptionalUndefined(type.properties[key], key, value))
+ continue;
+ value[key] = FromType23(direction, context, type.properties[key], value[key]);
+ }
+ return Callback(direction, context, type, value);
+}
+function Encode6(direction, context, type, value) {
+ const exterior = Callback(direction, context, type, value);
+ if (!guard_exports.IsObjectNotArray(exterior))
+ return exterior;
+ for (const key of guard_exports.Keys(type.properties)) {
+ if (!guard_exports.HasPropertyKey(exterior, key) || IsOptionalUndefined(type.properties[key], key, exterior))
+ continue;
+ exterior[key] = FromType23(direction, context, type.properties[key], exterior[key]);
+ }
+ return exterior;
+}
+function FromObject14(direction, context, type, value) {
+ return guard_exports.IsEqual(direction, "Decode") ? Decode6(direction, context, type, value) : Encode6(direction, context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/from_record.mjs
+function Decode7(direction, context, type, value) {
+ if (!guard_exports.IsObjectNotArray(value))
+ return value;
+ const regexp = new RegExp(RecordPattern(type));
+ for (const key of guard_exports.Keys(value)) {
+ if (!regexp.test(key))
+ continue;
+ value[key] = FromType23(direction, context, RecordValue(type), value[key]);
+ }
+ return Callback(direction, context, type, value);
+}
+function Encode7(direction, context, type, value) {
+ const exterior = Callback(direction, context, type, value);
+ if (!guard_exports.IsObjectNotArray(exterior))
+ return exterior;
+ const regexp = new RegExp(RecordPattern(type));
+ for (const key of guard_exports.Keys(exterior)) {
+ if (!regexp.test(key))
+ continue;
+ exterior[key] = FromType23(direction, context, RecordValue(type), exterior[key]);
+ }
+ return exterior;
+}
+function FromRecord6(direction, context, type, value) {
+ return guard_exports.IsEqual(direction, "Decode") ? Decode7(direction, context, type, value) : Encode7(direction, context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/from_ref.mjs
+function ResolveRef2(direction, context, type, value) {
+ return guard_exports.HasPropertyKey(context, type.$ref) ? FromType23(direction, context, context[type.$ref], value) : value;
+}
+function FromRef8(direction, context, type, value) {
+ return guard_exports.IsEqual(direction, "Decode") ? Callback(direction, context, type, ResolveRef2(direction, context, type, value)) : ResolveRef2(direction, context, type, Callback(direction, context, type, value));
+}
+
+// node_modules/typebox/build/value/codec/from_tuple.mjs
+function Decode8(direction, context, type, value) {
+ if (!guard_exports.IsArray(value))
+ return value;
+ for (let i = 0; i < Math.min(type.items.length, value.length); i++) {
+ value[i] = FromType23(direction, context, type.items[i], value[i]);
+ }
+ return Callback(direction, context, type, value);
+}
+function Encode8(direction, context, type, value) {
+ const exterior = Callback(direction, context, type, value);
+ if (!guard_exports.IsArray(exterior))
+ return value;
+ for (let i = 0; i < Math.min(type.items.length, exterior.length); i++) {
+ exterior[i] = FromType23(direction, context, type.items[i], exterior[i]);
+ }
+ return exterior;
+}
+function FromTuple8(direction, context, type, value) {
+ return guard_exports.IsEqual(direction, "Decode") ? Decode8(direction, context, type, value) : Encode8(direction, context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/from_union.mjs
+function Decode9(direction, context, type, value) {
+ for (const schema of type.anyOf) {
+ if (!Check2(context, schema, value))
+ continue;
+ const variant = FromType23(direction, context, schema, value);
+ return Callback(direction, context, type, variant);
+ }
+ return value;
+}
+function Encode9(direction, context, type, value) {
+ const exterior = Callback(direction, context, type, value);
+ for (const schema of type.anyOf) {
+ const variant = FromType23(direction, context, schema, Clone2(exterior));
+ if (!Check2(context, schema, variant))
+ continue;
+ return variant;
+ }
+ return exterior;
+}
+function FromUnion12(direction, context, type, value) {
+ return guard_exports.IsEqual(direction, "Decode") ? Decode9(direction, context, type, value) : Encode9(direction, context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/from_type.mjs
+function FromType23(direction, context, type, value) {
+ return IsArray3(type) ? FromArray10(direction, context, type, value) : IsCyclic(type) ? FromCyclic9(direction, context, type, value) : IsIntersect(type) ? FromIntersect9(direction, context, type, value) : IsObject3(type) ? FromObject14(direction, context, type, value) : IsRecord(type) ? FromRecord6(direction, context, type, value) : IsRef2(type) ? FromRef8(direction, context, type, value) : IsTuple(type) ? FromTuple8(direction, context, type, value) : IsUnion(type) ? FromUnion12(direction, context, type, value) : Callback(direction, context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/decode.mjs
+var DecodeError = class extends AssertError {
+ constructor(value, errors) {
+ super("Decode", value, errors);
+ }
+};
+function Assert2(context, type, value) {
+ if (!Check2(context, type, value))
+ throw new DecodeError(value, Errors2(context, type, value));
+ return value;
+}
+function DecodeUnsafe(context, type, value) {
+ const sorted = settings_exports.Get().unionPrioritySort ? UnionPrioritySort(type) : type;
+ return FromType23("Decode", context, sorted, value);
+}
+var Decoder = Pipeline([
+ (_context, _type, value) => Clone2(value),
+ (context, type, value) => Default(context, type, value),
+ (context, type, value) => Convert(context, type, value),
+ (context, type, value) => Clean(context, type, value),
+ (context, type, value) => Assert2(context, type, value),
+ (context, type, value) => DecodeUnsafe(context, type, value)
+]);
+function Decode10(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ return Decoder(context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/encode.mjs
+var EncodeError = class extends AssertError {
+ constructor(value, errors) {
+ super("Encode", value, errors);
+ }
+};
+function Assert3(context, type, value) {
+ if (!Check2(context, type, value))
+ throw new EncodeError(value, Errors2(context, type, value));
+ return value;
+}
+function EncodeUnsafe(context, type, value) {
+ const sorted = settings_exports.Get().unionPrioritySort ? UnionPrioritySort(type) : type;
+ return FromType23("Encode", context, sorted, value);
+}
+var Encoder = Pipeline([
+ (_context, _type, value) => Clone2(value),
+ (context, type, value) => EncodeUnsafe(context, type, value),
+ (context, type, value) => Default(context, type, value),
+ (context, type, value) => Convert(context, type, value),
+ (context, type, value) => Clean(context, type, value),
+ (context, type, value) => Assert3(context, type, value)
+]);
+function Encode10(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ return Encoder(context, type, value);
+}
+
+// node_modules/typebox/build/value/codec/has.mjs
+function FromArray11(context, type) {
+ return IsCodec(type) || FromType24(context, type.items);
+}
+function FromCyclic10(context, type) {
+ return IsCodec(type) || FromRef9({ ...context, ...type.$defs }, Ref2(type.$ref));
+}
+function FromIntersect10(context, type) {
+ return IsCodec(type) || type.allOf.some((type2) => FromType24(context, type2));
+}
+function FromObject15(context, type) {
+ return IsCodec(type) || guard_exports.Keys(type.properties).some((key) => {
+ return FromType24(context, type.properties[key]);
+ });
+}
+function FromRecord7(context, type) {
+ return IsCodec(type) || FromType24(context, RecordValue(type));
+}
+function FromRef9(context, type) {
+ if (visited.has(type.$ref))
+ return false;
+ visited.add(type.$ref);
+ return IsCodec(type) || guard_exports.HasPropertyKey(context, type.$ref) && FromType24(context, context[type.$ref]);
+}
+function FromTuple9(context, type) {
+ return IsCodec(type) || type.items.some((type2) => FromType24(context, type2));
+}
+function FromUnion13(context, type) {
+ return IsCodec(type) || type.anyOf.some((type2) => FromType24(context, type2));
+}
+function FromType24(context, type) {
+ return IsArray3(type) ? FromArray11(context, type) : IsCyclic(type) ? FromCyclic10(context, type) : IsIntersect(type) ? FromIntersect10(context, type) : IsObject3(type) ? FromObject15(context, type) : IsRecord(type) ? FromRecord7(context, type) : IsRef2(type) ? FromRef9(context, type) : IsTuple(type) ? FromTuple9(context, type) : IsUnion(type) ? FromUnion13(context, type) : IsCodec(type);
+}
+var visited = /* @__PURE__ */ new Set();
+function HasCodec(...args) {
+ const [context, type] = arguments_exports.Match(args, {
+ 2: (context2, type2) => [context2, type2],
+ 1: (type2) => [{}, type2]
+ });
+ visited.clear();
+ return FromType24(context, type);
+}
+
+// node_modules/typebox/build/value/create/error.mjs
+var CreateError = class extends Error {
+ constructor(type, message) {
+ super(message);
+ this.type = type;
+ }
+};
+
+// node_modules/typebox/build/value/create/from_default.mjs
+function FromDefault2(_context, schema) {
+ return guard_exports.IsFunction(schema.default) ? schema.default(schema) : guard_exports.IsObject(schema.default) ? Clone2(schema.default) : schema.default;
+}
+
+// node_modules/typebox/build/value/create/from_array.mjs
+function FromArray12(context, type) {
+ if (IsUniqueItems(type) && !IsDefault(type))
+ throw new CreateError(type, "Arrays with uniqueItems constraints must specify a default annotation");
+ const length = IsMinItems(type) ? type.minItems : 0;
+ return Array.from({ length }, () => FromType25(context, type.items));
+}
+
+// node_modules/typebox/build/value/create/from_bigint.mjs
+function FromBigInt7(_context, type) {
+ return IsExclusiveMinimum(type) ? BigInt(type.exclusiveMinimum) + BigInt(1) : IsMinimum(type) ? BigInt(type.minimum) : BigInt(0);
+}
+
+// node_modules/typebox/build/value/create/from_boolean.mjs
+function FromBoolean7(_context, _type) {
+ return false;
+}
+
+// node_modules/typebox/build/value/create/from_constructor.mjs
+function FromConstructor2(context, type) {
+ const instanceType = FromType25(context, type.instanceType);
+ return class {
+ constructor() {
+ Object.assign(this, instanceType);
+ }
+ };
+}
+
+// node_modules/typebox/build/value/create/from_cyclic.mjs
+function FromCyclic11(context, type) {
+ return FromType25({ ...context, ...type.$defs }, Ref2(type.$ref));
+}
+
+// node_modules/typebox/build/value/create/from_enum.mjs
+function FromEnum4(context, type) {
+ return FromType25(context, Evaluate2(type));
+}
+
+// node_modules/typebox/build/value/create/from_function.mjs
+function FromFunction2(context, type) {
+ const returnType = FromType25(context, type.returnType);
+ return () => returnType;
+}
+
+// node_modules/typebox/build/value/create/from_integer.mjs
+function FromInteger2(_context, type) {
+ return IsExclusiveMinimum(type) && guard_exports.IsNumber(type.exclusiveMinimum) ? type.exclusiveMinimum + 1 : IsMinimum(type) ? type.minimum : 0;
+}
+
+// node_modules/typebox/build/value/create/from_intersect.mjs
+function FromIntersect11(context, type) {
+ const instantiated = Instantiate(context, type);
+ const evaluated = Evaluate2(instantiated);
+ return FromType25(context, evaluated);
+}
+
+// node_modules/typebox/build/value/create/from_literal.mjs
+function FromLiteral7(_context, type) {
+ return type.const;
+}
+
+// node_modules/typebox/build/value/create/from_never.mjs
+function FromNever(_context, type) {
+ throw new CreateError(type, "Cannot create TNever types");
+}
+
+// node_modules/typebox/build/value/create/from_null.mjs
+function FromNull3(_context, _type) {
+ return null;
+}
+
+// node_modules/typebox/build/value/create/from_number.mjs
+function FromNumber6(_context, type) {
+ return IsExclusiveMinimum(type) && guard_exports.IsNumber(type.exclusiveMinimum) ? type.exclusiveMinimum + 1 : IsMinimum(type) ? type.minimum : 0;
+}
+
+// node_modules/typebox/build/value/create/from_object.mjs
+function FromObject16(context, type) {
+ const required = guard_exports.IsUndefined(type.required) ? [] : type.required;
+ return required.reduce((result, key) => {
+ return { ...result, [key]: FromType25(context, type.properties[key]) };
+ }, {});
+}
+
+// node_modules/typebox/build/value/create/from_record.mjs
+function FromRecord8(_context, type) {
+ if (IsMinProperties(type) && !IsDefault(type))
+ throw new CreateError(type, "Record with the minProperties constraint must have a default annotation");
+ return {};
+}
+
+// node_modules/typebox/build/value/create/from_ref.mjs
+function FromRef10(context, type) {
+ return guard_exports.HasPropertyKey(context, type.$ref) ? FromType25(context, context[type.$ref]) : (() => {
+ throw new CreateError(type, "Unable to deref Ref");
+ })();
+}
+
+// node_modules/typebox/build/value/create/from_string.mjs
+function FromString8(_context, type) {
+ const needsDefault = (IsPattern(type) || IsFormat(type)) && !IsDefault(type);
+ if (needsDefault)
+ throw Error("Strings with format or pattern constraints must specify default");
+ const minLength = IsMinLength4(type) ? type.minLength : 0;
+ return "".padEnd(minLength);
+}
+
+// node_modules/typebox/build/value/create/from_symbol.mjs
+function FromSymbol2(_context, _type) {
+ return Symbol();
+}
+
+// node_modules/typebox/build/value/create/from_template_literal.mjs
+function FromTemplateLiteral5(context, type) {
+ const decoded = TemplateLiteralDecode(type.pattern);
+ if (IsString4(decoded))
+ throw new CreateError(type, "Unable to create TemplateLiteral due to infinite type expansion");
+ return FromType25(context, decoded);
+}
+
+// node_modules/typebox/build/value/create/from_tuple.mjs
+function FromTuple10(context, type) {
+ return Array.from({ length: type.minItems }, (_, i) => FromType25(context, type.items[i]));
+}
+
+// node_modules/typebox/build/value/create/from_undefined.mjs
+function FromUndefined3(_context, _type) {
+ return void 0;
+}
+
+// node_modules/typebox/build/value/create/from_union.mjs
+function FromUnion14(context, type) {
+ if (guard_exports.IsEqual(type.anyOf.length, 0)) {
+ throw Error("Unable to create Union with no variants");
+ }
+ return FromType25(context, type.anyOf[0]);
+}
+
+// node_modules/typebox/build/value/create/from_void.mjs
+function FromVoid2(_context, _type) {
+ return void 0;
+}
+
+// node_modules/typebox/build/value/create/from_type.mjs
+function FromType25(context, type) {
+ return (
+ // -----------------------------------------------------
+ // Default
+ // -----------------------------------------------------
+ IsDefault(type) ? FromDefault2(context, type) : (
+ // -----------------------------------------------------
+ // Types
+ // -----------------------------------------------------
+ IsArray3(type) ? FromArray12(context, type) : IsBigInt3(type) ? FromBigInt7(context, type) : IsBoolean4(type) ? FromBoolean7(context, type) : IsConstructor3(type) ? FromConstructor2(context, type) : IsCyclic(type) ? FromCyclic11(context, type) : IsEnum2(type) ? FromEnum4(context, type) : IsFunction3(type) ? FromFunction2(context, type) : IsInteger3(type) ? FromInteger2(context, type) : IsIntersect(type) ? FromIntersect11(context, type) : IsLiteral(type) ? FromLiteral7(context, type) : IsNever(type) ? FromNever(context, type) : IsNull3(type) ? FromNull3(context, type) : IsNumber4(type) ? FromNumber6(context, type) : IsObject3(type) ? FromObject16(context, type) : IsRecord(type) ? FromRecord8(context, type) : IsRef2(type) ? FromRef10(context, type) : IsString4(type) ? FromString8(context, type) : IsSymbol3(type) ? FromSymbol2(context, type) : IsTemplateLiteral(type) ? FromTemplateLiteral5(context, type) : IsTuple(type) ? FromTuple10(context, type) : IsUndefined3(type) ? FromUndefined3(context, type) : IsUnion(type) ? FromUnion14(context, type) : IsVoid(type) ? FromVoid2(context, type) : void 0
+ )
+ );
+}
+
+// node_modules/typebox/build/value/create/create.mjs
+function Create2(...args) {
+ const [context, type] = arguments_exports.Match(args, {
+ 2: (context2, type2) => [context2, type2],
+ 1: (type2) => [{}, type2]
+ });
+ return FromType25(context, type);
+}
+
+// node_modules/typebox/build/value/equal/equal.mjs
+function Equal(left, right) {
+ return guard_exports.IsDeepEqual(left, right);
+}
+
+// node_modules/typebox/build/value/hash/hash.mjs
+function Hash2(value) {
+ return hash_exports.Hash(value);
+}
+
+// node_modules/typebox/build/value/parse/parse.mjs
+var ParseError = class extends AssertError {
+ constructor(value, errors) {
+ super("Parse", value, errors);
+ }
+};
+function Assert4(context, type, value) {
+ if (!Check2(context, type, value))
+ throw new ParseError(value, Errors2(context, type, value));
+ return value;
+}
+var Parser = Pipeline([
+ (_context, _type, value) => Clone2(value),
+ (context, type, value) => Default(context, type, value),
+ (context, type, value) => Convert(context, type, value),
+ (context, type, value) => Clean(context, type, value),
+ (context, type, value) => Assert4(context, type, value)
+]);
+function Parse(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ const checked = Check2(context, type, value);
+ if (checked)
+ return value;
+ if (settings_exports.Get().correctiveParse)
+ return Parser(context, type, value);
+ throw new ParseError(value, Errors2(context, type, value));
+}
+
+// node_modules/typebox/build/value/delta/diff.mjs
+function CreateUpdate(path5, value) {
+ return { type: "update", path: path5, value };
+}
+function CreateInsert(path5, value) {
+ return { type: "insert", path: path5, value };
+}
+function CreateDelete(path5) {
+ return { type: "delete", path: path5 };
+}
+function AssertCanDiffObject(value) {
+ if (guard_exports.IsObject(value) && guard_exports.IsEqual(guard_exports.Symbols(value).length, 0))
+ return;
+ throw new Error("Cannot create diffs for objects with symbols keys");
+}
+function* FromObject17(path5, left, right) {
+ if (!guard_exports.IsObject(right) || guard_exports.IsArray(right))
+ return yield CreateUpdate(path5, right);
+ AssertCanDiffObject(left);
+ AssertCanDiffObject(right);
+ const leftKeys = guard_exports.Keys(left);
+ const rightKeys = guard_exports.Keys(right);
+ for (const key of rightKeys) {
+ if (guard_exports.HasPropertyKey(left, key))
+ continue;
+ if (guard_exports.IsUnsafePropertyKey(key))
+ continue;
+ yield CreateInsert(`${path5}/${key}`, right[key]);
+ }
+ for (const key of leftKeys) {
+ if (!guard_exports.HasPropertyKey(right, key))
+ continue;
+ if (guard_exports.IsUnsafePropertyKey(key))
+ continue;
+ if (Equal(left, right))
+ continue;
+ yield* FromValue4(`${path5}/${key}`, left[key], right[key]);
+ }
+ for (const key of leftKeys) {
+ if (guard_exports.HasPropertyKey(right, key))
+ continue;
+ if (guard_exports.IsUnsafePropertyKey(key))
+ continue;
+ yield CreateDelete(`${path5}/${key}`);
+ }
+}
+function* FromArray13(path5, left, right) {
+ if (!guard_exports.IsArray(right))
+ return yield CreateUpdate(path5, right);
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
+ yield* FromValue4(`${path5}/${i}`, left[i], right[i]);
+ }
+ for (let i = 0; i < right.length; i++) {
+ if (i < left.length)
+ continue;
+ yield CreateInsert(`${path5}/${i}`, right[i]);
+ }
+ for (let i = left.length - 1; i >= 0; i--) {
+ if (i < right.length)
+ continue;
+ yield CreateDelete(`${path5}/${i}`);
+ }
+}
+function* FromTypedArray2(path5, left, right) {
+ const typeLeft = globalThis.Object.getPrototypeOf(left).constructor.name;
+ const typeRight = globalThis.Object.getPrototypeOf(right).constructor.name;
+ const predicate = globals_exports.IsTypeArray(right) && guard_exports.IsEqual(left.length, right.length) && guard_exports.IsEqual(typeLeft, typeRight);
+ if (predicate) {
+ for (let index3 = 0; index3 < Math.min(left.length, right.length); index3++) {
+ yield* FromValue4(`${path5}/${index3}`, left[index3], right[index3]);
+ }
+ } else {
+ return yield CreateUpdate(path5, right);
+ }
+}
+function* FromUnknown(path5, left, right) {
+ if (left === right)
+ return;
+ yield CreateUpdate(path5, right);
+}
+function* FromValue4(path5, left, right) {
+ return globals_exports.IsTypeArray(left) ? yield* FromTypedArray2(path5, left, right) : guard_exports.IsArray(left) ? yield* FromArray13(path5, left, right) : guard_exports.IsObject(left) ? yield* FromObject17(path5, left, right) : yield* FromUnknown(path5, left, right);
+}
+function Diff(current, next) {
+ return [...FromValue4("", current, next)];
+}
+
+// node_modules/typebox/build/value/delta/edit.mjs
+var Insert2 = _Object_({
+ type: Literal("insert"),
+ path: String2(),
+ value: Unknown()
+});
+var Update2 = Object({
+ type: Literal("update"),
+ path: String2(),
+ value: Unknown()
+});
+var Delete2 = _Object_({
+ type: Literal("delete"),
+ path: String2()
+});
+var Edit = Union([Insert2, Update2, Delete2]);
+
+// node_modules/typebox/build/value/delta/patch.mjs
+function IsRoot(edits) {
+ return edits.length > 0 && edits[0].path === "" && edits[0].type === "update";
+}
+function IsEmpty(edits) {
+ return edits.length === 0;
+}
+function Patch(current, edits) {
+ if (IsRoot(edits))
+ return Clone2(edits[0].value);
+ if (IsEmpty(edits))
+ return Clone2(current);
+ const clone2 = Clone2(current);
+ for (const edit of edits) {
+ switch (edit.type) {
+ case "insert": {
+ pointer_exports.Set(clone2, edit.path, edit.value);
+ break;
+ }
+ case "update": {
+ pointer_exports.Set(clone2, edit.path, edit.value);
+ break;
+ }
+ case "delete": {
+ pointer_exports.Delete(clone2, edit.path);
+ break;
+ }
+ }
+ }
+ return clone2;
+}
+
+// node_modules/typebox/build/value/repair/error.mjs
+var RepairError = class extends Error {
+ constructor(context, type, value, message) {
+ super(message);
+ this.context = context;
+ this.type = type;
+ this.value = value;
+ }
+};
+
+// node_modules/typebox/build/value/repair/from_array.mjs
+function MakeUnique(values) {
+ const [hashes, result] = [/* @__PURE__ */ new Set(), []];
+ for (const value of values) {
+ const hash = Hash2(value);
+ if (hashes.has(hash))
+ continue;
+ hashes.add(hash);
+ result.push(value);
+ }
+ return result;
+}
+function FromArray14(context, type, value) {
+ if (Check2(context, type, value))
+ return value;
+ const created = guard_exports.IsArray(value) ? value : Create2(context, type);
+ const minimum = IsMinItems(type) && created.length < type.minItems ? [...created, ...Array.from({ length: type.minItems - created.length }, () => Create2(context, type))] : created;
+ const maximum = IsMaxItems(type) && minimum.length > type.maxItems ? minimum.slice(0, type.maxItems) : minimum;
+ const repaired = maximum.map((value2) => FromType26(context, type.items, value2));
+ if (!IsUniqueItems(type) || IsUniqueItems(type) && !guard_exports.IsEqual(type.uniqueItems, true))
+ return repaired;
+ const unique = MakeUnique(repaired);
+ if (!Check2(context, type, unique))
+ throw new RepairError(context, type, value, "Failed to repair Array due to uniqueItems constraint");
+ return unique;
+}
+
+// node_modules/typebox/build/value/repair/from_enum.mjs
+function FromEnum5(context, type, value) {
+ return FromType26(context, Evaluate2(type), value);
+}
+
+// node_modules/typebox/build/value/repair/from_intersect.mjs
+function FromIntersect12(context, type, value) {
+ const instantiated = Instantiate(context, type);
+ const evaluated = Evaluate2(instantiated);
+ return FromType26(context, evaluated, value);
+}
+
+// node_modules/typebox/build/value/repair/from_object.mjs
+function FromObject18(context, type, value) {
+ if (Check2(context, type, value))
+ return value;
+ if (!guard_exports.IsObjectNotArray(value))
+ return Create2(context, type);
+ const required = new Set(guard_exports.IsUndefined(type.required) ? [] : type.required);
+ const result = {};
+ for (const [key, schema] of guard_exports.Entries(type.properties)) {
+ if (!required.has(key) && guard_exports.IsUndefined(value[key]))
+ continue;
+ result[key] = key in value ? FromType26(context, schema, value[key]) : Create2(context, schema);
+ }
+ const evaluatedKeys = guard_exports.Keys(type.properties);
+ if (IsAdditionalProperties(type) && guard_exports.IsObject(type.additionalProperties)) {
+ for (const key of guard_exports.Keys(value)) {
+ if (evaluatedKeys.includes(key))
+ continue;
+ result[key] = FromType26(context, type.additionalProperties, value[key]);
+ }
+ }
+ return result;
+}
+
+// node_modules/typebox/build/value/repair/from_record.mjs
+function FromRecord9(context, type, value) {
+ if (Check2(context, type, value))
+ return value;
+ if (guard_exports.IsNull(value) || !guard_exports.IsObject(value) || guard_exports.IsArray(value))
+ return Create2(context, type);
+ const recordKey = new RegExp(RecordPattern(type));
+ const recordValue = RecordValue(type);
+ const evaluatedKeys = /* @__PURE__ */ new Set();
+ const result = {};
+ for (const [key, value_] of guard_exports.Entries(value)) {
+ if (!recordKey.test(key))
+ continue;
+ result[key] = FromType26(context, recordValue, value_);
+ evaluatedKeys.add(key);
+ }
+ if (IsAdditionalProperties(type)) {
+ for (const key of guard_exports.Keys(value)) {
+ if (evaluatedKeys.has(key))
+ continue;
+ result[key] = FromType26(context, type.additionalProperties, value[key]);
+ }
+ }
+ return result;
+}
+
+// node_modules/typebox/build/value/repair/from_ref.mjs
+function FromRef11(context, type, value) {
+ return guard_exports.HasPropertyKey(context, type.$ref) ? FromType26(context, context[type.$ref], value) : (() => {
+ throw new RepairError(context, type, value, "Unable to de-reference target type");
+ })();
+}
+
+// node_modules/typebox/build/value/repair/from_template_literal.mjs
+function FromTemplateLiteral6(context, type, value) {
+ const decoded = TemplateLiteralDecode(type.pattern);
+ return FromType26(context, decoded, value);
+}
+
+// node_modules/typebox/build/value/repair/from_tuple.mjs
+function FromTuple11(context, schema, value) {
+ if (Check2(context, schema, value))
+ return value;
+ if (!guard_exports.IsArray(value))
+ return Create2(context, schema);
+ return schema.items.map((schema2, index3) => FromType26(context, schema2, value[index3]));
+}
+
+// node_modules/typebox/build/value/shared/union_score_select.mjs
+function Deref(context, type, value) {
+ return IsRef2(type) ? guard_exports.HasPropertyKey(context, type.$ref) ? Deref(context, context[type.$ref], value) : (() => {
+ throw new Error("Unable to Deref target");
+ })() : type;
+}
+function ScoreVariant(context, type, value) {
+ if (!(IsObject3(type) && guard_exports.IsObject(value)))
+ return 0;
+ const keys = guard_exports.Keys(value);
+ const entries = guard_exports.Entries(type.properties);
+ return entries.reduce((result, [key, schema]) => {
+ const literal = IsLiteral(schema) && guard_exports.IsEqual(schema.const, value[key]) ? 100 : 0;
+ const checks = Check2(context, schema, value[key]) ? 10 : 0;
+ const exists = keys.includes(key) ? 1 : 0;
+ return result + (literal + checks + exists);
+ }, 0);
+}
+function UnionScoreSelect(context, type, value) {
+ const schemas = type.anyOf.map((schema) => Deref(context, schema, value));
+ let [select, best] = [schemas[0], 0];
+ for (const schema of schemas) {
+ const score = ScoreVariant(context, schema, value);
+ if (score > best) {
+ select = schema;
+ best = score;
+ }
+ }
+ return select;
+}
+
+// node_modules/typebox/build/value/repair/from_union.mjs
+function RepairUnion(context, type, value) {
+ const union = Union(Flatten(type.anyOf));
+ const schema = UnionScoreSelect(context, union, value);
+ return FromType26(context, schema, value);
+}
+function FromUnion15(context, type, value) {
+ if (Check2(context, type, value))
+ return Clone2(value);
+ if (IsDefault(type))
+ return Create2(context, type);
+ return RepairUnion(context, type, value);
+}
+
+// node_modules/typebox/build/value/repair/from_unknown.mjs
+function FromUnknown2(context, type, value) {
+ if (Check2(context, type, value))
+ return value;
+ const converted = Convert(context, type, value);
+ if (Check2(context, type, converted))
+ return converted;
+ return Create2(context, type);
+}
+
+// node_modules/typebox/build/value/repair/from_type.mjs
+function AssertRepairableValue(context, type, value) {
+ const unsupported = globals_exports.IsDate(value) || globals_exports.IsMap(value) || globals_exports.IsSet(value) || globals_exports.IsTypeArray(value) || guard_exports.IsConstructor(value) || guard_exports.IsFunction(value);
+ if (unsupported) {
+ throw new RepairError(context, type, value, "Value is not repairable");
+ }
+}
+function AssertRepairableType(context, type, value) {
+ const unsupported = IsConstructor3(type) || IsFunction3(type) || IsNever(type);
+ if (unsupported) {
+ throw new RepairError(context, type, value, "Type is not repairable");
+ }
+}
+function CreateWhenUndefined(context, type, value) {
+ return guard_exports.IsUndefined(value) && !IsUndefined3(type) ? Create2(context, type) : value;
+}
+function FinalizeRepair(context, type, repaired) {
+ return IsRefine2(type) ? Check2(context, type, repaired) ? repaired : Create2(context, type) : repaired;
+}
+function FromType26(context, type, value) {
+ AssertRepairableValue(context, type, value);
+ AssertRepairableType(context, type, value);
+ const candidate = CreateWhenUndefined(context, type, value);
+ const repaired = IsArray3(type) ? FromArray14(context, type, candidate) : IsEnum2(type) ? FromEnum5(context, type, candidate) : IsIntersect(type) ? FromIntersect12(context, type, candidate) : IsObject3(type) ? FromObject18(context, type, candidate) : IsRecord(type) ? FromRecord9(context, type, candidate) : IsRef2(type) ? FromRef11(context, type, candidate) : IsTemplateLiteral(type) ? FromTemplateLiteral6(context, type, candidate) : IsTuple(type) ? FromTuple11(context, type, candidate) : IsUnion(type) ? FromUnion15(context, type, candidate) : FromUnknown2(context, type, candidate);
+ return FinalizeRepair(context, type, repaired);
+}
+
+// node_modules/typebox/build/value/repair/repair.mjs
+function Repair(...args) {
+ const [context, type, value] = arguments_exports.Match(args, {
+ 3: (context2, type2, value2) => [context2, type2, value2],
+ 2: (type2, value2) => [{}, type2, value2]
+ });
+ const repaired = FromType26(context, type, value);
+ Assert(context, type, repaired);
+ return repaired;
+}
+
+// node_modules/typebox/build/value/value.mjs
+var value_exports = {};
+__export(value_exports, {
+ Assert: () => Assert,
+ Check: () => Check2,
+ Clean: () => Clean,
+ Clone: () => Clone2,
+ Convert: () => Convert,
+ Create: () => Create2,
+ Decode: () => Decode10,
+ Default: () => Default,
+ Diff: () => Diff,
+ Encode: () => Encode10,
+ Equal: () => Equal,
+ Errors: () => Errors2,
+ HasCodec: () => HasCodec,
+ Hash: () => Hash2,
+ Parse: () => Parse,
+ Patch: () => Patch,
+ Pointer: () => pointer_exports,
+ Repair: () => Repair
+});
+
+// node_modules/typebox/build/compile/validator.mjs
+var Validator = class {
+ /** Constructs a Validator. */
+ constructor(context, type) {
+ this.hasCodec = HasCodec(context, type);
+ this.buildResult = Build(context, type);
+ this.evaluateResult = this.buildResult.Evaluate();
+ }
+ // ----------------------------------------------------------------
+ // IsAccelerated
+ // ----------------------------------------------------------------
+ /** Returns true if this Validator is using JIT acceleration. */
+ IsAccelerated() {
+ return this.evaluateResult.IsAccelerated();
+ }
+ // ----------------------------------------------------------------
+ // Context & Type
+ // ----------------------------------------------------------------
+ /** Returns the Context for this validator. */
+ Context() {
+ return this.buildResult.Context();
+ }
+ /** Returns the underlying Type used to construct this Validator. */
+ Type() {
+ return this.buildResult.Schema();
+ }
+ // ----------------------------------------------------------------
+ // Code
+ // ----------------------------------------------------------------
+ /** Returns the generated code for this validator. */
+ Code() {
+ return this.evaluateResult.Code();
+ }
+ // ----------------------------------------------------------------
+ // Standard Validator
+ // ----------------------------------------------------------------
+ /** Performs a type-guard check on the provided value. */
+ Check(value) {
+ return this.evaluateResult.Check(value);
+ }
+ /** Validates a value and returns it. Will throw if invalid. */
+ Parse(value) {
+ const checked = this.Check(value);
+ if (checked)
+ return value;
+ if (settings_exports.Get().correctiveParse)
+ return Parser(this.Context(), this.Type(), value);
+ throw new ParseError(value, this.Errors(value));
+ }
+ /** Returns an array of validation errors for the given value. */
+ Errors(value) {
+ if (this.IsAccelerated() && this.Check(value))
+ return [];
+ return Errors2(this.Context(), this.Type(), value);
+ }
+ // ----------------------------------------------------------------
+ // Value.* Operations
+ // ----------------------------------------------------------------
+ /** Cleans a value using the Validator type. */
+ Clean(value) {
+ return Clean(this.Context(), this.Type(), value);
+ }
+ /** Converts a value using the Validator type. */
+ Convert(value) {
+ return Convert(this.Context(), this.Type(), value);
+ }
+ /** Creates a value using the Validator type. */
+ Create() {
+ return Create2(this.Context(), this.Type());
+ }
+ /** Creates defaults using the Validator type. */
+ Default(value) {
+ return Default(this.Context(), this.Type(), value);
+ }
+ /** Decodes a value */
+ Decode(value) {
+ const result = this.hasCodec ? Decode10(this.Context(), this.Type(), value) : this.Parse(value);
+ return result;
+ }
+ /** Encodes a value */
+ Encode(value) {
+ const result = this.hasCodec ? Encode10(this.Context(), this.Type(), value) : this.Parse(value);
+ return result;
+ }
+};
+
+// node_modules/typebox/build/compile/compile.mjs
+function Compile(...args) {
+ const [context, type] = arguments_exports.Match(args, {
+ 2: (context2, type2) => [context2, type2],
+ 1: (type2) => [{}, type2]
+ });
+ return new Validator(context, type);
+}
+
+// node_modules/@earendil-works/pi-ai/dist/utils/validation.js
+var validatorCache = /* @__PURE__ */ new WeakMap();
+var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
+function getSchemaTypes(schema) {
+ if (typeof schema.type === "string") {
+ return [schema.type];
+ }
+ if (Array.isArray(schema.type)) {
+ return schema.type.filter((type) => typeof type === "string");
+ }
+ return [];
+}
+function matchesJsonType(value, type) {
+ switch (type) {
+ case "number":
+ return typeof value === "number";
+ case "integer":
+ return typeof value === "number" && Number.isInteger(value);
+ case "boolean":
+ return typeof value === "boolean";
+ case "string":
+ return typeof value === "string";
+ case "null":
+ return value === null;
+ case "array":
+ return Array.isArray(value);
+ case "object":
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+ default:
+ return false;
+ }
+}
+function getSubSchemaValidator(schema) {
+ try {
+ return getValidator(schema);
+ } catch {
+ return void 0;
+ }
+}
+function coercePrimitiveByType(value, type) {
+ switch (type) {
+ case "number": {
+ if (value === null) {
+ return 0;
+ }
+ if (typeof value === "string" && value.trim() !== "") {
+ const parsed = Number(value);
+ if (Number.isFinite(parsed)) {
+ return parsed;
+ }
+ }
+ if (typeof value === "boolean") {
+ return value ? 1 : 0;
+ }
+ return value;
+ }
+ case "integer": {
+ if (value === null) {
+ return 0;
+ }
+ if (typeof value === "string" && value.trim() !== "") {
+ const parsed = Number(value);
+ if (Number.isInteger(parsed)) {
+ return parsed;
+ }
+ }
+ if (typeof value === "boolean") {
+ return value ? 1 : 0;
+ }
+ return value;
+ }
+ case "boolean": {
+ if (value === null) {
+ return false;
+ }
+ if (typeof value === "string") {
+ if (value === "true") {
+ return true;
+ }
+ if (value === "false") {
+ return false;
+ }
+ }
+ if (typeof value === "number") {
+ if (value === 1) {
+ return true;
+ }
+ if (value === 0) {
+ return false;
+ }
+ }
+ return value;
+ }
+ case "string": {
+ if (value === null) {
+ return "";
+ }
+ if (typeof value === "number" || typeof value === "boolean") {
+ return String(value);
+ }
+ return value;
+ }
+ case "null": {
+ if (value === "" || value === 0 || value === false) {
+ return null;
+ }
+ return value;
+ }
+ default:
+ return value;
+ }
+}
+function applySchemaObjectCoercion(value, schema) {
+ const properties = schema.properties;
+ const definedKeys = new Set(properties ? Object.keys(properties) : []);
+ if (properties) {
+ for (const [key, propertySchema] of Object.entries(properties)) {
+ if (!(key in value)) {
+ continue;
+ }
+ value[key] = coerceWithJsonSchema(value[key], propertySchema);
+ }
+ }
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
+ for (const [key, propertyValue] of Object.entries(value)) {
+ if (definedKeys.has(key)) {
+ continue;
+ }
+ value[key] = coerceWithJsonSchema(propertyValue, schema.additionalProperties);
+ }
+ }
+}
+function applySchemaArrayCoercion(value, schema) {
+ if (Array.isArray(schema.items)) {
+ for (let index3 = 0; index3 < value.length; index3++) {
+ const itemSchema = schema.items[index3];
+ if (!itemSchema) {
+ continue;
+ }
+ value[index3] = coerceWithJsonSchema(value[index3], itemSchema);
+ }
+ return;
+ }
+ if (schema.items && typeof schema.items === "object") {
+ for (let index3 = 0; index3 < value.length; index3++) {
+ value[index3] = coerceWithJsonSchema(value[index3], schema.items);
+ }
+ }
+}
+function coerceWithUnionSchema(value, schemas) {
+ for (const schema of schemas) {
+ const validator = getSubSchemaValidator(schema);
+ if (validator?.Check(value)) {
+ return value;
+ }
+ }
+ for (const schema of schemas) {
+ const candidate = structuredClone(value);
+ const coerced = coerceWithJsonSchema(candidate, schema);
+ const validator = getSubSchemaValidator(schema);
+ if (validator?.Check(coerced)) {
+ return coerced;
+ }
+ }
+ return value;
+}
+function coerceWithJsonSchema(value, schema) {
+ let nextValue = value;
+ if (Array.isArray(schema.allOf)) {
+ for (const nested of schema.allOf) {
+ nextValue = coerceWithJsonSchema(nextValue, nested);
+ }
+ }
+ if (Array.isArray(schema.anyOf)) {
+ nextValue = coerceWithUnionSchema(nextValue, schema.anyOf);
+ }
+ if (Array.isArray(schema.oneOf)) {
+ nextValue = coerceWithUnionSchema(nextValue, schema.oneOf);
+ }
+ const schemaTypes = getSchemaTypes(schema);
+ const matchesUnionMember = schemaTypes.length > 1 && schemaTypes.some((schemaType) => matchesJsonType(nextValue, schemaType));
+ if (schemaTypes.length > 0 && !matchesUnionMember) {
+ for (const schemaType of schemaTypes) {
+ const candidate = coercePrimitiveByType(nextValue, schemaType);
+ if (candidate !== nextValue) {
+ nextValue = candidate;
+ break;
+ }
+ }
+ }
+ if (schemaTypes.includes("object") && typeof nextValue === "object" && nextValue !== null && !Array.isArray(nextValue)) {
+ applySchemaObjectCoercion(nextValue, schema);
+ }
+ if (schemaTypes.includes("array") && Array.isArray(nextValue)) {
+ applySchemaArrayCoercion(nextValue, schema);
+ }
+ return nextValue;
+}
+function normalizeOptionalNulls(value, schema) {
+ if (Array.isArray(value)) {
+ if (Array.isArray(schema.items)) {
+ for (let index3 = 0; index3 < value.length; index3++) {
+ const itemSchema = schema.items[index3];
+ if (itemSchema)
+ normalizeOptionalNulls(value[index3], itemSchema);
+ }
+ } else if (schema.items) {
+ for (const item of value)
+ normalizeOptionalNulls(item, schema.items);
+ }
+ return;
+ }
+ if (typeof value !== "object" || value === null || !schema.properties)
+ return;
+ const object = value;
+ const required = new Set(schema.required ?? []);
+ for (const [key, propertySchema] of Object.entries(schema.properties)) {
+ if (!(key in object))
+ continue;
+ if (object[key] === null && !required.has(key) && typeof propertySchema.$ref !== "string" && getSubSchemaValidator(propertySchema)?.Check(null) === false) {
+ delete object[key];
+ } else {
+ normalizeOptionalNulls(object[key], propertySchema);
+ }
+ }
+}
+function getValidator(schema) {
+ const key = schema;
+ const cached = validatorCache.get(key);
+ if (cached) {
+ return cached;
+ }
+ const validator = Compile(schema);
+ validatorCache.set(key, validator);
+ return validator;
+}
+function formatValidationPath(error) {
+ if (error.keyword === "required") {
+ const requiredProperties = error.params.requiredProperties;
+ const requiredProperty = requiredProperties?.[0];
+ if (requiredProperty) {
+ const basePath = error.instancePath.replace(/^\//, "").replace(/\//g, ".");
+ return basePath ? `${basePath}.${requiredProperty}` : requiredProperty;
+ }
+ }
+ const path5 = error.instancePath.replace(/^\//, "").replace(/\//g, ".");
+ return path5 || "root";
+}
+function validateToolArguments(tool, toolCall) {
+ const args = structuredClone(toolCall.arguments);
+ normalizeOptionalNulls(args, tool.parameters);
+ value_exports.Convert(tool.parameters, args);
+ const validator = getValidator(tool.parameters);
+ if (!Object.getOwnPropertySymbols(tool.parameters).includes(TYPEBOX_KIND)) {
+ const coerced = coerceWithJsonSchema(args, tool.parameters);
+ if (coerced !== args) {
+ if (typeof args === "object" && args !== null && typeof coerced === "object" && coerced !== null) {
+ for (const key of Object.keys(args)) {
+ delete args[key];
+ }
+ Object.assign(args, coerced);
+ } else {
+ return validator.Check(coerced) ? coerced : args;
+ }
+ }
+ }
+ if (validator.Check(args)) {
+ return args;
+ }
+ const errors = validator.Errors(args).map((error) => ` - ${formatValidationPath(error)}: ${error.message}`).join("\n") || "Unknown validation error";
+ const errorMessage = `Validation failed for tool "${toolCall.name}":
+${errors}
+
+Received arguments:
+${JSON.stringify(toolCall.arguments, null, 2)}`;
+ throw new Error(errorMessage);
+}
+
+// node_modules/@earendil-works/pi-durable/dist/truncate.js
+var DEFAULT_MAX_LINES = 2e3;
+var DEFAULT_MAX_BYTES = 50 * 1024;
+var runtimeBuffer = globalThis.Buffer;
+var nonAsciiPattern = /[^\x00-\x7f]/;
+function utf8ByteLength(content) {
+ if (runtimeBuffer)
+ return runtimeBuffer.byteLength(content, "utf8");
+ const firstNonAscii = content.search(nonAsciiPattern);
+ if (firstNonAscii === -1)
+ return content.length;
+ let bytes = firstNonAscii;
+ for (let i = firstNonAscii; i < content.length; i++) {
+ const code = content.charCodeAt(i);
+ if (code <= 127) {
+ bytes += 1;
+ } else if (code <= 2047) {
+ bytes += 2;
+ } else if (code >= 55296 && code <= 56319 && i + 1 < content.length) {
+ const next = content.charCodeAt(i + 1);
+ if (next >= 56320 && next <= 57343) {
+ bytes += 4;
+ i++;
+ } else {
+ bytes += 3;
+ }
+ } else {
+ bytes += 3;
+ }
+ }
+ return bytes;
+}
+function splitLinesForCounting(content) {
+ if (content.length === 0)
+ return [];
+ const lines2 = content.split("\n");
+ if (content.endsWith("\n"))
+ lines2.pop();
+ return lines2;
+}
+function formatSize(bytes) {
+ if (bytes < 1024) {
+ return `${bytes}B`;
+ } else if (bytes < 1024 * 1024) {
+ return `${(bytes / 1024).toFixed(1)}KB`;
+ } else {
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
+ }
+}
+function truncateHeadOf(prefix, totals, options = {}) {
+ const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
+ const totalBytes = totals.bytes;
+ const lines2 = splitLinesForCounting(prefix);
+ const totalLines = totals.lines;
+ if (totalLines <= maxLines && totalBytes <= maxBytes) {
+ return {
+ content: prefix,
+ truncated: false,
+ truncatedBy: null,
+ totalLines,
+ totalBytes,
+ outputLines: totalLines,
+ outputBytes: totalBytes,
+ lastLinePartial: false,
+ firstLineExceedsLimit: false,
+ maxLines,
+ maxBytes
+ };
+ }
+ const firstLineBytes = utf8ByteLength(lines2[0]);
+ if (firstLineBytes > maxBytes) {
+ return {
+ content: "",
+ truncated: true,
+ truncatedBy: "bytes",
+ totalLines,
+ totalBytes,
+ outputLines: 0,
+ outputBytes: 0,
+ lastLinePartial: false,
+ firstLineExceedsLimit: true,
+ maxLines,
+ maxBytes
+ };
+ }
+ const outputLinesArr = [];
+ let outputBytesCount = 0;
+ let truncatedBy = "lines";
+ for (let i = 0; i < lines2.length && i < maxLines; i++) {
+ const line = lines2[i];
+ const lineBytes = utf8ByteLength(line) + (i > 0 ? 1 : 0);
+ if (outputBytesCount + lineBytes > maxBytes) {
+ truncatedBy = "bytes";
+ break;
+ }
+ outputLinesArr.push(line);
+ outputBytesCount += lineBytes;
+ }
+ if (truncatedBy !== "bytes")
+ truncatedBy = outputLinesArr.length < totalLines ? "lines" : "bytes";
+ const outputContent = outputLinesArr.join("\n");
+ const finalOutputBytes = utf8ByteLength(outputContent);
+ return {
+ content: outputContent,
+ truncated: true,
+ truncatedBy,
+ totalLines,
+ totalBytes,
+ outputLines: outputLinesArr.length,
+ outputBytes: finalOutputBytes,
+ lastLinePartial: false,
+ firstLineExceedsLimit: false,
+ maxLines,
+ maxBytes
+ };
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/output.js
+var NEWLINE = 10;
+var INVALID_OUTPUT = /[\x00-\x08\x0b-\x1f\ufff9-\ufffb]/g;
+var encoder2 = new TextEncoder();
+var decoder = new TextDecoder();
+function sanitizeOutput(text) {
+ return text.replace(INVALID_OUTPUT, "");
+}
+function boundOutput(text, limits) {
+ const bytes = encoder2.encode(text);
+ const [from, to] = limits.retain === "head" ? headRange(bytes, limits) : tailRange(bytes, limits);
+ const kept = bytes.subarray(from, to);
+ return {
+ text: kept.length === bytes.length ? text : decoder.decode(kept),
+ bytes: kept.length,
+ droppedBytes: bytes.length - kept.length,
+ droppedLines: lineCount(bytes) - lineCount(kept)
+ };
+}
+function headRange(bytes, limits) {
+ if (limits.maxLines === 0 || limits.maxBytes === 0)
+ return [0, 0];
+ let end = bytes.length;
+ let lines2 = 0;
+ for (let index3 = bytes.indexOf(NEWLINE); index3 !== -1; index3 = bytes.indexOf(NEWLINE, index3 + 1)) {
+ if (++lines2 === limits.maxLines) {
+ end = index3 + 1;
+ break;
+ }
+ }
+ if (end > limits.maxBytes) {
+ const newline = bytes.lastIndexOf(NEWLINE, limits.maxBytes - 1);
+ end = newline === -1 ? characterEnd(bytes, limits.maxBytes) : newline + 1;
+ }
+ return [0, end];
+}
+function tailRange(bytes, limits) {
+ if (limits.maxLines === 0 || limits.maxBytes === 0)
+ return [bytes.length, bytes.length];
+ const last = bytes[bytes.length - 1] === NEWLINE ? bytes.length - 2 : bytes.length - 1;
+ let start = 0;
+ let lines2 = 1;
+ for (let index3 = last < 0 ? -1 : bytes.lastIndexOf(NEWLINE, last); index3 !== -1; ) {
+ if (lines2 === limits.maxLines) {
+ start = index3 + 1;
+ break;
+ }
+ lines2++;
+ index3 = index3 === 0 ? -1 : bytes.lastIndexOf(NEWLINE, index3 - 1);
+ }
+ if (bytes.length - start > limits.maxBytes) {
+ const from = bytes.length - limits.maxBytes;
+ const newline = bytes.indexOf(NEWLINE, from - 1);
+ start = newline !== -1 && newline + 1 < bytes.length ? newline + 1 : characterStart(bytes, from);
+ }
+ return [start, bytes.length];
+}
+function characterEnd(bytes, index3) {
+ let end = index3;
+ while (end > 0 && ((bytes[end] ?? 0) & 192) === 128)
+ end--;
+ return end;
+}
+function characterStart(bytes, index3) {
+ let start = index3;
+ while (start < bytes.length && ((bytes[start] ?? 0) & 192) === 128)
+ start++;
+ return start;
+}
+function lineCount(bytes) {
+ if (bytes.length === 0)
+ return 0;
+ let newlines = 0;
+ for (let index3 = bytes.indexOf(NEWLINE); index3 !== -1; index3 = bytes.indexOf(NEWLINE, index3 + 1))
+ newlines++;
+ return newlines + (bytes[bytes.length - 1] === NEWLINE ? 0 : 1);
+}
+var OutputBuffer = class {
+ #limits;
+ #decoder = new TextDecoder();
+ /** Stored chunks: for head the start of the stream, for tail a suffix that still contains the next window. */
+ #chunks = [];
+ #storedBytes = 0;
+ #storedNewlines = 0;
+ #full = false;
+ #totalBytes = 0;
+ #totalNewlines = 0;
+ #endsWithNewline = true;
+ constructor(limits) {
+ this.#limits = limits;
+ }
+ /** Bytes currently held; bounded by the limits plus one chunk. */
+ get storedBytes() {
+ return this.#storedBytes;
+ }
+ /**
+ * Accept a chunk; returns whether anything was accepted. `skipped` is output omitted right before the chunk, which
+ * must be more than the tail window by at least one byte or line (`ShellOutputInfo.skipped`); only tail retention
+ * accepts it.
+ */
+ push(chunk, skipped) {
+ const pending = typeof chunk === "string" || skipped !== void 0 ? this.#decoder.decode() : "";
+ const text = typeof chunk === "string" ? chunk : this.#decoder.decode(chunk, { stream: true });
+ if (skipped === void 0)
+ return this.#accept(pending + text);
+ if (this.#limits.retain !== "tail")
+ throw new Error("Skipped output requires tail retention");
+ this.#accept(pending);
+ this.#skip(skipped);
+ this.#accept(text);
+ return true;
+ }
+ /** Count omitted output; nothing stored before it can be in the window once the text after it arrives. */
+ #skip(skipped) {
+ if (skipped.bytes === 0)
+ return;
+ this.#totalBytes += skipped.bytes;
+ this.#totalNewlines += skipped.newlines;
+ this.#endsWithNewline = skipped.endsWithNewline;
+ this.#chunks = [];
+ this.#storedBytes = 0;
+ this.#storedNewlines = 0;
+ }
+ /** Flush an incomplete trailing character as a replacement character; call when the stream ends. */
+ end() {
+ this.#accept(this.#decoder.decode());
+ }
+ #accept(text) {
+ if (text.length === 0)
+ return false;
+ const bytes = utf8ByteLength(text);
+ const newlines = countNewlines(text);
+ this.#totalBytes += bytes;
+ this.#totalNewlines += newlines;
+ this.#endsWithNewline = text.endsWith("\n");
+ if (this.#full)
+ return true;
+ this.#chunks.push({ text, bytes, newlines });
+ this.#storedBytes += bytes;
+ this.#storedNewlines += newlines;
+ if (this.#limits.retain === "head") {
+ this.#full = this.#storedBytes > this.#limits.maxBytes || this.#storedNewlines >= this.#limits.maxLines;
+ return true;
+ }
+ while (this.#chunks.length > 1) {
+ const first = this.#chunks[0];
+ const bytesAfter = this.#storedBytes - first.bytes;
+ const newlinesAfter = this.#storedNewlines - first.newlines;
+ if (bytesAfter <= this.#limits.maxBytes + 1 && newlinesAfter <= this.#limits.maxLines + 1)
+ break;
+ this.#chunks.shift();
+ this.#storedBytes = bytesAfter;
+ this.#storedNewlines = newlinesAfter;
+ }
+ return true;
+ }
+ /** Retained, sanitized output and what the limits dropped from the whole stream. */
+ snapshot() {
+ const stored = this.#chunks.length === 1 ? this.#chunks[0].text : this.#chunks.map((chunk) => chunk.text).join("");
+ const kept = boundOutput(stored, this.#limits);
+ const storedLines = lines(this.#storedNewlines, stored === "" || stored.endsWith("\n"));
+ const keptLines = storedLines - kept.droppedLines;
+ if (this.#limits.retain === "tail" || this.#chunks.length > 1) {
+ const text = this.#limits.retain === "tail" ? tailMargin(stored, this.#limits) : stored;
+ const bytes = this.#limits.retain === "tail" ? utf8ByteLength(text) : this.#storedBytes;
+ this.#chunks = text === "" ? [] : [{ text, bytes, newlines: countNewlines(text) }];
+ this.#storedBytes = bytes;
+ this.#storedNewlines = this.#chunks[0]?.newlines ?? 0;
+ }
+ return {
+ text: sanitizeOutput(kept.text),
+ droppedBytes: this.#totalBytes - kept.bytes,
+ droppedLines: lines(this.#totalNewlines, this.#endsWithNewline) - keptLines
+ };
+ }
+};
+function tailMargin(text, limits) {
+ const bytes = encoder2.encode(text);
+ const byteStart = bytes.length > limits.maxBytes ? characterEnd(bytes, bytes.length - limits.maxBytes - 1) : 0;
+ let lineStart = 0;
+ let newlines = 0;
+ for (let index3 = bytes.lastIndexOf(NEWLINE); index3 !== -1; index3 = bytes.lastIndexOf(NEWLINE, index3 - 1)) {
+ if (++newlines > limits.maxLines) {
+ lineStart = index3;
+ break;
+ }
+ if (index3 === 0)
+ break;
+ }
+ const start = Math.max(byteStart, lineStart);
+ return start === 0 ? text : decoder.decode(bytes.subarray(start));
+}
+function lines(newlines, terminated) {
+ return newlines + (terminated ? 0 : 1);
+}
+function countNewlines(text) {
+ let count = 0;
+ for (let index3 = text.indexOf("\n"); index3 !== -1; index3 = text.indexOf("\n", index3 + 1))
+ count++;
+ return count;
+}
+var PROGRESS_BYTES_PER_SECOND = 100 * 1024;
+var Progress = class {
+ #write;
+ #onError;
+ #minIntervalMs;
+ #waiters = [];
+ #timer;
+ #inFlight;
+ #nextAt = 0;
+ #dirty = false;
+ #stopped = false;
+ constructor(write, onError, minIntervalMs) {
+ this.#write = write;
+ this.#onError = onError;
+ this.#minIntervalMs = minIntervalMs;
+ }
+ /** Schedule a commit. */
+ mark() {
+ this.#dirty = true;
+ this.#schedule();
+ }
+ /** Schedule a commit; the promise settles with the commit that includes this change. */
+ markAndWait() {
+ const waiter = Promise.withResolvers();
+ this.#waiters.push(waiter);
+ this.mark();
+ return waiter.promise;
+ }
+ /** Stop committing and wait for the commit in flight; returns the waiters the final commit must settle. */
+ async stop() {
+ this.#stopped = true;
+ clearTimeout(this.#timer);
+ this.#timer = void 0;
+ await this.#inFlight;
+ return this.#waiters.splice(0);
+ }
+ #schedule() {
+ if (this.#stopped || this.#timer !== void 0 || this.#inFlight !== void 0)
+ return;
+ const wait = this.#nextAt - Date.now();
+ if (wait <= 0)
+ this.#flush();
+ else
+ this.#timer = setTimeout(() => {
+ this.#timer = void 0;
+ this.#flush();
+ }, wait);
+ }
+ #flush() {
+ if (this.#stopped || !this.#dirty)
+ return;
+ this.#dirty = false;
+ const waiters = this.#waiters.splice(0);
+ const started = Date.now();
+ this.#inFlight = this.#write().then((bytes) => {
+ this.#nextAt = started + Math.max(this.#minIntervalMs, bytes * 1e3 / PROGRESS_BYTES_PER_SECOND);
+ for (const waiter of waiters)
+ waiter.resolve();
+ }, (error) => {
+ this.#nextAt = started + this.#minIntervalMs;
+ for (const waiter of waiters)
+ waiter.reject(error);
+ this.#onError(error);
+ }).finally(() => {
+ this.#inFlight = void 0;
+ if (this.#dirty)
+ this.#schedule();
+ });
+ }
+};
+
+// node_modules/@earendil-works/pi-durable/dist/harness/usage.js
+var UsageDoc = defineDoc({
+ kind: "pi.usage",
+ version: 1,
+ scope: "conversation",
+ history: "latest",
+ fork: "initial",
+ initial: () => ({ models: {}, tools: {} }),
+ checkpointWhen: () => true
+});
+async function recordUsage(tx, conversationId, bucket, key, usage) {
+ const totals = (await tx.doc(UsageDoc, conversationId))[bucket];
+ const total = Object.hasOwn(totals, key) ? totals[key] : void 0;
+ if (total === void 0)
+ totals[key] = copyJson(usage, { omitUndefinedProperties: true });
+ else
+ addUsage(total, usage);
+}
+function addUsage(total, usage) {
+ total.input += usage.input;
+ total.output += usage.output;
+ total.cacheRead += usage.cacheRead;
+ total.cacheWrite += usage.cacheWrite;
+ total.totalTokens += usage.totalTokens;
+ if (usage.cacheWrite1h !== void 0)
+ total.cacheWrite1h = (total.cacheWrite1h ?? 0) + usage.cacheWrite1h;
+ if (usage.reasoning !== void 0)
+ total.reasoning = (total.reasoning ?? 0) + usage.reasoning;
+ total.cost.input += usage.cost.input;
+ total.cost.output += usage.cost.output;
+ total.cost.cacheRead += usage.cost.cacheRead;
+ total.cost.cacheWrite += usage.cost.cacheWrite;
+ total.cost.total += usage.cost.total;
+}
+function addUsageState(sum, state3) {
+ for (const bucket of ["models", "tools"]) {
+ for (const [key, usage] of Object.entries(state3[bucket])) {
+ const total = Object.hasOwn(sum[bucket], key) ? sum[bucket][key] : void 0;
+ if (total !== void 0)
+ addUsage(total, usage);
+ else
+ Object.defineProperty(sum[bucket], key, {
+ value: structuredClone(usage),
+ enumerable: true,
+ writable: true
+ });
+ }
+ }
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/tool.js
+var ToolTask = defineTask({
+ name: "pi.tool",
+ version: 1,
+ initial: () => ({ phase: "call" }),
+ phases: {
+ call: async (task, runtime, context) => {
+ const call = await readCall(runtime, task.input, context);
+ const tool = (await runtime.agent(context)).tools.find((each) => each.name === call.name);
+ if (tool === void 0) {
+ const error = harnessError("tool_unavailable", `Tool ${call.name} is not available`);
+ return settle(runtime, call, COMPLETED, () => error, context);
+ }
+ const prepared = prepare(tool, call.arguments);
+ const checked = "error" in prepared ? prepared : validate(tool, call, prepared.args);
+ if ("error" in checked)
+ return settle(runtime, call, COMPLETED, () => invalid(checked.error), context);
+ let args = checked.args;
+ let block;
+ await runtime.hooks.each("beforeTool", async (hook2) => {
+ if (block !== void 0)
+ return;
+ try {
+ const decision = await hook2({ ...call, arguments: args }, runtime, context);
+ if (decision?.block !== void 0)
+ block = decision.block;
+ else if (decision?.arguments !== void 0)
+ args = decision.arguments;
+ } catch (error) {
+ if (runtime.signal.aborted)
+ throw error;
+ block = errorText(error);
+ }
+ });
+ if (block !== void 0) {
+ const blocked = harnessError("blocked", `Tool call blocked: ${block}`);
+ return settle(runtime, call, COMPLETED, () => blocked, context);
+ }
+ const validated = validate(tool, call, args);
+ if ("error" in validated)
+ return settle(runtime, call, COMPLETED, () => invalid(validated.error), context);
+ const final = validated.args;
+ await runtime.commit(async (tx) => {
+ const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
+ if (slot !== void 0)
+ slot.status = "running";
+ const intent = { phase: "execute", arguments: final, replay: tool.replay ?? "unsafe" };
+ return { status: "running", checkpoint: intent };
+ }, context);
+ await run(runtime, call, tool, final, context);
+ },
+ /** Recovery after intent: rerun only when the stored and the current policy both say `safe`. */
+ execute: async (task, runtime, context) => {
+ const { arguments: args, replay } = task.state.checkpoint;
+ const call = await readCall(runtime, task.input, context);
+ const tool = (await runtime.agent(context)).tools.find((each) => each.name === call.name);
+ if (replay === "safe" && tool?.replay === "safe") {
+ await runtime.commit(async (tx) => {
+ const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
+ if (slot !== void 0)
+ clearProgress(slot);
+ return void 0;
+ }, context);
+ return run(runtime, call, tool, args, context);
+ }
+ const message = `Tool ${call.name} was interrupted and may have partially run`;
+ const ending = { status: "failed", message };
+ await settle(runtime, call, ending, (slot) => fromSlot(slot, "interrupted", message), context);
+ }
+ },
+ abort: async (task, runtime, context) => {
+ const call = await readCall(runtime, task.input, context);
+ const message = `Tool ${call.name} was aborted`;
+ await settle(runtime, call, { status: "aborted" }, (slot) => fromSlot(slot, "aborted", message), context);
+ }
+});
+async function readCall(runtime, input, context) {
+ const entry = await runtime.entry(AssistantEntry, input.assistant, context);
+ const message = entry?.model?.[0];
+ const call = message?.role === "assistant" ? message.content.find((content) => content.type === "toolCall" && content.id === input.callId) : void 0;
+ if (call === void 0)
+ throw new Error(`Entry ${input.assistant} has no tool call ${input.callId}`);
+ return call;
+}
+function prepare(tool, args) {
+ if (tool.prepareArguments === void 0)
+ return { args };
+ try {
+ return { args: tool.prepareArguments(args) };
+ } catch (error) {
+ return { error: errorText(error) };
+ }
+}
+function validate(tool, call, args) {
+ try {
+ return { args: validateToolArguments(tool, { ...call, arguments: args }) };
+ } catch (error) {
+ return { error: errorText(error) };
+ }
+}
+function invalid(message) {
+ return harnessError("invalid_arguments", message);
+}
+async function run(runtime, call, tool, args, context) {
+ const limits = {
+ maxBytes: tool.outputLimits?.maxBytes ?? DEFAULT_MAX_BYTES,
+ maxLines: tool.outputLimits?.maxLines ?? DEFAULT_MAX_LINES,
+ retain: tool.outputLimits?.retain ?? "head"
+ };
+ const reported = { output: new OutputBuffer(limits), limits, diagnostics: [], details: void 0 };
+ const progress = publishProgress(runtime, reported, context);
+ let ended = false;
+ const assertLive = () => {
+ if (ended)
+ throw new Error(`Tool call ${call.id} has settled`);
+ };
+ const api = {
+ taskId: runtime.taskId,
+ conversationId: runtime.conversationId,
+ callId: call.id,
+ registry: runtime.registry,
+ agent: runtime.agent,
+ output: (chunk, skipped) => {
+ assertLive();
+ if (reported.output.push(chunk, skipped))
+ progress.mark();
+ },
+ outputWindow: limits.retain === "tail" ? {
+ maxBytes: limits.maxBytes,
+ maxLines: limits.maxLines,
+ minIntervalMs: runtime.settings.progress.outputIntervalMs,
+ bytesPerSecond: PROGRESS_BYTES_PER_SECOND
+ } : void 0,
+ diagnostic: (diagnostic) => {
+ assertLive();
+ reported.diagnostics.push(copyJson(diagnostic, { omitUndefinedProperties: true }));
+ progress.mark();
+ },
+ details: async (value, detailsContext) => {
+ assertLive();
+ detailsContext.abortSignal?.throwIfAborted();
+ reported.details = copyJson(value, { omitUndefinedProperties: true });
+ const committed = progress.markAndWait();
+ committed.catch(() => {
+ });
+ return awaitWithContext(committed, detailsContext);
+ },
+ commit: async (change, commitContext) => {
+ let result2;
+ await runtime.commit(async (tx) => {
+ result2 = await change(tx);
+ return void 0;
+ }, commitContext);
+ return result2;
+ },
+ memo: runtime.memo,
+ createTask: async (task, input, options, taskContext) => {
+ let id;
+ await runtime.commit(async (tx) => {
+ id = await tx.createTask(task, input, options);
+ return void 0;
+ }, taskContext);
+ return id;
+ },
+ getTask: runtime.getTask,
+ waitForTask: runtime.waitForTask,
+ conversation: runtime.conversation,
+ snapshot: runtime.snapshot,
+ snapshotAsOf: runtime.snapshotAsOf,
+ watchDoc: runtime.watchDoc
+ };
+ let result;
+ let ending = COMPLETED;
+ try {
+ const env = await runtime.env(context);
+ result = await tool.execute(args, { ...api, env }, context);
+ } catch (error) {
+ if (runtime.signal.aborted) {
+ ended = true;
+ for (const waiter of await progress.stop())
+ waiter.reject(error);
+ throw error;
+ }
+ result = { isError: true, diagnostics: [toolDiagnostic("tool_error", errorText(error))] };
+ ending = { status: "failed", message: `Tool ${call.name} threw` };
+ }
+ ended = true;
+ reported.output.end();
+ const pending = await progress.stop();
+ try {
+ const settled = await finalResult(runtime, call, result, reported, context);
+ await settle(runtime, call, ending, () => settled, context);
+ } catch (error) {
+ for (const waiter of pending)
+ waiter.reject(error);
+ throw error;
+ }
+ for (const waiter of pending)
+ waiter.resolve();
+}
+function publishProgress(runtime, reported, context) {
+ let written = { text: "", details: void 0, diagnostics: 0 };
+ return new Progress(async () => {
+ const snapshot = reported.output.snapshot();
+ const current = { text: snapshot.text, details: reported.details, diagnostics: reported.diagnostics.length };
+ const added = reported.diagnostics.slice(written.diagnostics, current.diagnostics);
+ const detailsChanged = current.details !== written.details;
+ let bytes = 0;
+ if (snapshot.text !== written.text) {
+ const shared = snapshot.text.startsWith(written.text) ? written.text.length : overlap(written.text, snapshot.text, 65536);
+ bytes += utf8ByteLength(snapshot.text.slice(shared));
+ }
+ if (detailsChanged)
+ bytes += utf8ByteLength(JSON.stringify(current.details ?? null));
+ if (added.length > 0)
+ bytes += utf8ByteLength(JSON.stringify(added));
+ await runtime.commit(async (tx) => {
+ const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
+ if (slot === void 0)
+ return void 0;
+ if ((slot.output ?? "") !== snapshot.text)
+ slot.output = snapshot.text;
+ if (snapshot.droppedBytes > 0)
+ slot.droppedBytes = snapshot.droppedBytes;
+ if (snapshot.droppedLines > 0)
+ slot.droppedLines = snapshot.droppedLines;
+ if (detailsChanged && current.details !== void 0) {
+ assignJson(slot, "details", current.details);
+ }
+ if (added.length > 0) {
+ if (slot.diagnostics === void 0)
+ slot.diagnostics = [];
+ for (const diagnostic of added)
+ slot.diagnostics.push(diagnostic);
+ }
+ return void 0;
+ }, context);
+ written = current;
+ return bytes;
+ }, (error) => {
+ if (!runtime.signal.aborted)
+ runtime.report(error);
+ }, runtime.settings.progress.outputIntervalMs);
+}
+async function finalResult(runtime, call, result, reported, context) {
+ const harness = [];
+ const retained = result.content === void 0 ? reported.output.snapshot() : void 0;
+ const content = retained === void 0 ? result.content : retained.text === "" ? [] : [{ type: "text", text: retained.text }];
+ let final = {
+ ...result,
+ content,
+ details: result.details === void 0 ? reported.details : result.details,
+ diagnostics: [...reported.diagnostics, ...result.diagnostics ?? []]
+ };
+ await runtime.hooks.each("afterTool", async (hook2) => {
+ final = await hook2(call, final, runtime, context) ?? final;
+ });
+ if (retained !== void 0 && retained.droppedBytes > 0 && final.content === content) {
+ harness.push(truncated(retained, reported.limits.retain));
+ }
+ const bounded = boundContent(final.content ?? [], reported.limits);
+ if (bounded.droppedBytes > 0)
+ harness.push(truncated(bounded, reported.limits.retain));
+ return { ...final, content: bounded.content, diagnostics: [...final.diagnostics ?? [], ...harness] };
+}
+async function settle(runtime, call, ending, build, context) {
+ await runtime.commit(async (tx) => {
+ const slot = toolSlot(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
+ const result = build(slot);
+ const entry = await appendToolResult(tx, runtime.conversationId, call, result, runtime.now());
+ if (slot !== void 0)
+ finishSlot(slot, entry.id);
+ const entryId = entry.id;
+ if (ending.status === "aborted")
+ return { status: "terminal", outcome: { status: "aborted", result: { entryId } } };
+ if (ending.status === "failed") {
+ const error = { message: ending.message };
+ return { status: "terminal", outcome: { status: "failed", error, result: { entryId } } };
+ }
+ const control = result.control === void 0 ? {} : { control: copyJson(result.control, { omitUndefinedProperties: true }) };
+ return { status: "terminal", outcome: { status: "completed", result: { entryId, ...control } } };
+ }, context);
+}
+var COMPLETED = { status: "completed" };
+function fromSlot(slot, code, message) {
+ const diagnostics = [...slot?.diagnostics ?? []];
+ const droppedBytes = slot?.droppedBytes ?? 0;
+ if (droppedBytes > 0)
+ diagnostics.push(truncated({ droppedBytes, droppedLines: slot?.droppedLines ?? 0 }));
+ diagnostics.push(toolDiagnostic(code, message));
+ return {
+ content: slot?.output === void 0 || slot.output === "" ? [] : [{ type: "text", text: slot.output }],
+ isError: true,
+ ...slot?.details === void 0 ? {} : { details: slot.details },
+ diagnostics
+ };
+}
+function harnessError(code, message) {
+ return { content: [], isError: true, diagnostics: [toolDiagnostic(code, message)] };
+}
+function toolDiagnostic(code, message) {
+ return { severity: "error", code, message };
+}
+function truncated(dropped, retain) {
+ const kept = retain === void 0 ? "" : ` to its ${retain === "head" ? "beginning" : "end"}`;
+ return {
+ severity: "warn",
+ code: "truncated",
+ message: `Output truncated${kept}: ${dropped.droppedLines} lines, ${dropped.droppedBytes} bytes dropped`
+ };
+}
+async function appendToolResult(tx, conversationId, call, result, timestamp) {
+ const diagnostics = [...result.diagnostics ?? []];
+ const content = [...result.content ?? []];
+ if (diagnostics.length > 0)
+ content.push({ type: "text", text: renderDiagnostics(diagnostics) });
+ const message = {
+ role: "toolResult",
+ toolCallId: call.id,
+ toolName: call.name,
+ content,
+ ...result.details === void 0 ? {} : { details: result.details },
+ ...result.usage === void 0 ? {} : { usage: result.usage },
+ isError: result.isError ?? false,
+ timestamp
+ };
+ if (result.usage !== void 0)
+ await recordUsage(tx, conversationId, "tools", call.name, result.usage);
+ return tx.appendEntry(ToolResultEntry, conversationId, { model: [message], data: { diagnostics } });
+}
+function renderDiagnostics(diagnostics) {
+ return `
+${diagnostics.map((diagnostic) => `[${diagnostic.severity}] ${diagnostic.message}`).join("\n")}
+`;
+}
+function boundContent(content, limits) {
+ const texts = content.filter((item) => item.type === "text");
+ const bounded = boundOutput(texts.map((item) => item.text).join(""), limits);
+ if (bounded.droppedBytes === 0)
+ return { content, droppedBytes: 0, droppedLines: 0 };
+ const keep = limits.retain === "head" ? texts[0] : texts.at(-1);
+ const result = [];
+ for (const item of content) {
+ if (item.type !== "text")
+ result.push(item);
+ else if (item === keep)
+ result.push({ ...item, text: bounded.text });
+ }
+ return { content: result, droppedBytes: bounded.droppedBytes, droppedLines: bounded.droppedLines };
+}
+function errorText(error) {
+ return error instanceof Error ? error.message : String(error);
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/generation.js
+var DEFAULT_POLL_AFTER_MS = 5e3;
+var GenerationTask = defineTask({
+ name: "pi.generation",
+ version: 1,
+ initial: () => ({ phase: "prepare", attempt: 1 }),
+ phases: {
+ /**
+ * Render the system prompt and tool loadout and append the positional `pi.system` entries they need, then move to
+ * `request`. The agent and settings resolved here are fixed for this request. Only the Harness writes to a busy
+ * conversation, so the transcript read here is still the tail at the commit.
+ */
+ prepare: async (task, runtime, context) => {
+ const { conversationId } = runtime;
+ const agent = await runtime.agent(context);
+ const settings2 = runtime.settings;
+ const { model, thinkingLevel } = agent;
+ const resolved = model === void 0 ? void 0 : runtime.models.getModel(model.provider, model.modelId);
+ if (model === void 0 || resolved === void 0)
+ return failNoModel(runtime, model, context);
+ const { attempt, compacted, overflow } = task.state.checkpoint;
+ if (compacted !== void 0 && overflow !== void 0) {
+ const [outcome] = await runtime.outcomes([compacted], context);
+ if (outcome?.status !== "completed" || outcome.result.entryId === void 0) {
+ return failModelError(runtime, overflow, context);
+ }
+ }
+ const view = await runtime.context(conversationId, context);
+ const shown = replaySections(view.messages);
+ const report = (error) => runtime.report(error);
+ let env;
+ try {
+ env = await runtime.env(context);
+ } catch (error) {
+ if (context.abortSignal?.aborted)
+ throw error;
+ report(error);
+ }
+ const input = { conversationId, agent, env, shown: Object.fromEntries(shown), read: runtime };
+ const desired = await renderSections(agent.sections, input, shown, report, context);
+ const entries = planSystemEntries(view, desired, agent.tools, runtime.now());
+ const threshold = compacted === void 0 ? thresholdCompaction(view, entries, resolved.contextWindow, settings2.compaction) : void 0;
+ if (threshold === "blocking") {
+ await runtime.commit(async (tx) => {
+ const child = await createCompaction(tx, conversationId, { reason: "threshold" }, runtime.taskId);
+ const checkpoint = { phase: "prepare", attempt, compacted: child };
+ return { status: "waiting", checkpoint, on: [child], policy: "allSettled" };
+ }, context);
+ return;
+ }
+ await runtime.commit(async (tx) => {
+ let cutoff = (await tx.scanEntries({ conversationId }, 1)).items[0]?.id;
+ for (const entry of entries)
+ cutoff = (await tx.appendEntry(SystemEntry, conversationId, entry)).id;
+ if (cutoff === void 0)
+ throw new Error(`Conversation ${conversationId} has no entries to send`);
+ if (threshold === "background" && (await tx.doc(LiveDoc, conversationId)).compactions === void 0) {
+ await createCompaction(tx, conversationId, { reason: "threshold" });
+ }
+ const request = {
+ attempt,
+ ...compacted === void 0 ? {} : { compacted },
+ model,
+ thinkingLevel,
+ streamOptions: settings2.stream,
+ cutoff
+ };
+ return { status: "running", checkpoint: { phase: "request", ...request } };
+ }, context);
+ },
+ request: async (task, runtime, context) => {
+ const { attempt, compacted, model: ref, thinkingLevel, streamOptions, cutoff } = task.state.checkpoint;
+ const conversationId = runtime.conversationId;
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, conversationId);
+ await convertPartial(tx, live, conversationId);
+ live.generation = { attempt };
+ return void 0;
+ }, context);
+ const model = runtime.models.getModel(ref.provider, ref.modelId);
+ if (model === void 0)
+ return failNoModel(runtime, ref, context);
+ const view = await runtime.context(conversationId, context, cutoff);
+ let messages = view.messages;
+ await runtime.hooks.each("beforeRequest", async (hook2) => {
+ const replaced = await hook2({ messages }, runtime, context);
+ if (replaced !== void 0)
+ messages = replaced.messages;
+ });
+ const options = {
+ ...streamOptions,
+ signal: runtime.signal,
+ sessionId: await ensureProviderSessionId(runtime, context),
+ ...thinkingLevel === "off" ? {} : { reasoning: thinkingLevel }
+ };
+ const message = await streamResponse(runtime, model, messages, options, attempt, context);
+ const request = { attempt, compacted, model: ref, cutoff, messages: view.messages };
+ await classify(runtime, request, message, context);
+ },
+ retry: async (task, runtime, context) => {
+ const { attempt, compacted, until } = task.state.checkpoint;
+ await runtime.sleep(until, context);
+ await runtime.commit(async (tx) => {
+ (await tx.doc(LiveDoc, runtime.conversationId)).generation = { attempt: attempt + 1 };
+ const checkpoint = {
+ phase: "prepare",
+ attempt: attempt + 1,
+ ...compacted === void 0 ? {} : { compacted }
+ };
+ return { status: "running", checkpoint };
+ }, context);
+ },
+ poll: async (task, runtime, context) => {
+ const { attempt, compacted, model: ref, cutoff, handle, pollAt } = task.state.checkpoint;
+ const model = runtime.models.getModel(ref.provider, ref.modelId);
+ if (model === void 0)
+ return failNoModel(runtime, ref, context);
+ await runtime.sleep(pollAt, context);
+ const message = await runtime.models.fetchDeferred(model, handle, { signal: runtime.signal });
+ const request = { attempt, compacted, model: ref, cutoff, pollAt };
+ await classify(runtime, request, message, context);
+ },
+ tools: async (task, runtime, context) => {
+ const { assistant, tools, pending } = task.state.checkpoint;
+ const [next, ...rest] = pending;
+ if (next === void 0)
+ return finishToolRound(runtime, assistant, tools, context);
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, runtime.conversationId);
+ const taskId = await createToolTask(tx, runtime, assistant, next);
+ const slot = live.tools?.find((slot2) => slot2.callId === next && slot2.taskId === void 0);
+ if (slot !== void 0)
+ slot.taskId = taskId;
+ const checkpoint = {
+ phase: "tools",
+ assistant,
+ tools: [...tools, taskId],
+ pending: rest
+ };
+ return { status: "waiting", checkpoint, on: [taskId], policy: "allSettled" };
+ }, context);
+ }
+ },
+ abort: async (task, runtime, context) => {
+ const checkpoint = task.state.checkpoint;
+ if (checkpoint.phase === "poll") {
+ const model = runtime.models.getModel(checkpoint.model.provider, checkpoint.model.modelId);
+ if (model !== void 0) {
+ try {
+ await runtime.models.cancelDeferred(model, checkpoint.handle, { signal: runtime.signal });
+ } catch (error) {
+ runtime.report(error);
+ }
+ }
+ }
+ const conversationId = runtime.conversationId;
+ const unstarted = checkpoint.phase === "tools" ? await readCalls(runtime, checkpoint.assistant, checkpoint.pending, context) : [];
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, conversationId);
+ await convertPartial(tx, live, conversationId);
+ for (const call of unstarted) {
+ const result = harnessError("aborted", `Tool ${call.name} was aborted`);
+ await appendToolResult(tx, conversationId, call, result, runtime.now());
+ }
+ endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "aborted" });
+ return { status: "terminal", outcome: { status: "aborted" } };
+ }, context);
+ }
+});
+async function readCalls(runtime, assistant, callIds, context) {
+ const message = (await runtime.entry(AssistantEntry, assistant, context))?.model?.[0];
+ const calls = message?.role === "assistant" ? message.content.filter((content) => content.type === "toolCall") : [];
+ return callIds.flatMap((id) => calls.filter((call) => call.id === id).slice(0, 1));
+}
+function createToolTask(tx, runtime, assistant, callId) {
+ return tx.createTask(ToolTask, { assistant, callId }, { ownership: { kind: "task", taskId: runtime.taskId } });
+}
+function thresholdCompaction(view, planned, contextWindow, policy) {
+ if (!policy.enabled || contextWindow <= 0)
+ return void 0;
+ const tokens = estimateContext(view, planned.flatMap((entry) => entry.model ?? []));
+ const blocking = contextWindow - policy.reserveTokens;
+ const background = blocking - policy.backgroundTokens;
+ const over = tokens > blocking ? "blocking" : policy.backgroundTokens > 0 && tokens > background ? "background" : void 0;
+ if (over === void 0 || selectCut(view, policy.keepRecentTokens) === void 0)
+ return void 0;
+ return over;
+}
+async function failModelError(runtime, text, context) {
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, runtime.conversationId);
+ endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "model_error", detail: text });
+ return {
+ status: "terminal",
+ outcome: { status: "failed", error: { message: text, detail: { reason: "model_error" } } }
+ };
+ }, context);
+}
+async function failNoModel(runtime, ref, context) {
+ const message = ref === void 0 ? "No model is configured" : `Model ${ref.provider}/${ref.modelId} is not available`;
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, runtime.conversationId);
+ endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "no_model" });
+ return { status: "terminal", outcome: { status: "failed", error: { message, detail: { reason: "no_model" } } } };
+ }, context);
+}
+async function convertPartial(tx, live, conversationId) {
+ const partial = live.generation?.message;
+ if (partial === void 0)
+ return;
+ const message = copyJson(partial);
+ await appendAssistant(tx, conversationId, { ...message, stopReason: "aborted" });
+}
+async function streamResponse(runtime, model, messages, options, attempt, context) {
+ const interval = runtime.settings.progress.partialIntervalMs;
+ let pending;
+ let timer;
+ let inFlight;
+ let stopped = false;
+ const flush = () => {
+ timer = void 0;
+ const partial = pending;
+ pending = void 0;
+ if (partial === void 0 || stopped)
+ return;
+ inFlight = (async () => {
+ const message = copyJson(partial, { omitUndefinedProperties: true });
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, runtime.conversationId);
+ live.generation ??= { attempt };
+ assignJson(live.generation, "message", message);
+ return void 0;
+ }, context);
+ })().catch((error) => {
+ if (!runtime.signal.aborted)
+ runtime.report(error);
+ }).finally(() => {
+ inFlight = void 0;
+ if (pending !== void 0 && !stopped)
+ timer = setTimeout(flush, interval);
+ });
+ };
+ try {
+ const events = runtime.models.streamSimple(model, { messages: [...messages] }, options);
+ for await (const event of events) {
+ if (event.type === "done" || event.type === "error" || event.partial.content.length === 0)
+ continue;
+ pending = event.partial;
+ if (timer === void 0 && inFlight === void 0)
+ timer = setTimeout(flush, interval);
+ }
+ return await events.result();
+ } finally {
+ stopped = true;
+ clearTimeout(timer);
+ await inFlight;
+ }
+}
+async function classify(runtime, request, message, context) {
+ runtime.signal.throwIfAborted();
+ const conversationId = runtime.conversationId;
+ const { attempt, compacted, model: ref, cutoff } = request;
+ if (message.stopReason === "deferred" && message.deferred !== void 0) {
+ const handle = message.deferred;
+ const pollAt = Math.max(runtime.now() + (handle.pollAfterMs ?? DEFAULT_POLL_AFTER_MS), request.pollAt === void 0 ? Number.NEGATIVE_INFINITY : request.pollAt + 1);
+ await runtime.commit(async (tx) => {
+ (await tx.doc(LiveDoc, conversationId)).generation = { attempt, deferred: { pollAt } };
+ const checkpoint = {
+ phase: "poll",
+ attempt,
+ ...compacted === void 0 ? {} : { compacted },
+ model: ref,
+ cutoff,
+ handle,
+ pollAt
+ };
+ return { status: "running", checkpoint };
+ }, context);
+ return;
+ }
+ await runtime.hooks.each("afterResponse", (hook2) => hook2(message, runtime, context));
+ const calls = message.content.filter((content) => content.type === "toolCall");
+ if (message.stopReason === "toolUse" && calls.length > 0) {
+ return startToolRound(runtime, request, message, calls, context);
+ }
+ if (message.stopReason === "stop" || message.stopReason === "length" || message.stopReason === "toolUse") {
+ return answer(runtime, message, context);
+ }
+ const settings2 = runtime.settings;
+ const overflow = message.stopReason === "error" && isContextOverflow(message);
+ if (overflow && compacted === void 0 && settings2.compaction.enabled) {
+ const policy2 = settings2.compaction;
+ const view = await runtime.context(conversationId, context, cutoff);
+ if (selectCut(view, policy2.keepRecentTokens) !== void 0) {
+ const text = message.errorMessage ?? "Context overflow";
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, conversationId);
+ await appendAssistant(tx, conversationId, message);
+ delete live.generation;
+ const child = await createCompaction(tx, conversationId, { reason: "overflow" }, runtime.taskId);
+ const checkpoint = { phase: "prepare", attempt, compacted: child, overflow: text };
+ return { status: "waiting", checkpoint, on: [child], policy: "allSettled" };
+ }, context);
+ return;
+ }
+ }
+ const policy = settings2.retry;
+ const retry = message.stopReason === "error" && !overflow && isRetryableAssistantError(message) && policy.enabled && attempt <= policy.maxRetries;
+ const until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, conversationId);
+ await appendAssistant(tx, conversationId, message);
+ if (retry) {
+ live.generation = { attempt, retry: { at: until, error: message.errorMessage ?? "" } };
+ const checkpoint = {
+ phase: "retry",
+ attempt,
+ ...compacted === void 0 ? {} : { compacted },
+ until
+ };
+ return { status: "running", checkpoint };
+ }
+ const text = message.errorMessage ?? `Model response ended with stop reason ${message.stopReason}`;
+ endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "model_error", detail: text });
+ return {
+ status: "terminal",
+ outcome: { status: "failed", error: { message: text, detail: { reason: "model_error" } } }
+ };
+ }, context);
+}
+async function answer(runtime, message, context) {
+ let continuation;
+ await runtime.hooks.each("onYield", async (hook2) => {
+ if (continuation !== void 0)
+ return;
+ continuation = (await hook2(message, runtime, context))?.continue;
+ });
+ const conversationId = runtime.conversationId;
+ await runtime.commit(async (tx) => {
+ const boundary = await prepareBoundary(tx, conversationId, runtime.settings);
+ const live = await tx.doc(LiveDoc, conversationId);
+ const entry = await appendAssistant(tx, conversationId, message);
+ const result = { status: "terminal", outcome: { status: "completed", result: { entryId: entry.id } } };
+ const { users, reset } = await applyBoundary(tx, boundary, "final", runtime.now());
+ if (continuation !== void 0 && users.length === 0 && !reset) {
+ const user = { role: "user", content: continuation, timestamp: runtime.now() };
+ await tx.appendEntry(UserEntry, conversationId, { model: [user] });
+ handOver(live, runtime.taskId, await createGeneration(tx, conversationId));
+ delete live.generation;
+ return result;
+ }
+ endRun(tx, live, runtime.taskId, { status: "done", answer: entry.id });
+ if (users.length > 0)
+ await startRun(tx, conversationId, live, users);
+ return result;
+ }, context);
+}
+async function startToolRound(runtime, request, message, calls, context) {
+ const conversationId = runtime.conversationId;
+ const messages = request.messages ?? (await runtime.context(conversationId, context, request.cutoff)).messages;
+ const offered = new Set(getCurrentTools(messages).map((tool) => tool.name));
+ const tools = (await runtime.agent(context)).tools;
+ const sequential = runtime.settings.toolExecution === "sequential" || calls.some((call) => offered.has(call.name) && tools.find((tool) => tool.name === call.name)?.executionMode === "sequential");
+ await runtime.commit(async (tx) => {
+ const live = await tx.doc(LiveDoc, conversationId);
+ const entry = await appendAssistant(tx, conversationId, message);
+ const slots = [];
+ const tools2 = [];
+ const pending = [];
+ for (const call of calls) {
+ if (!offered.has(call.name)) {
+ const unavailable = harnessError("tool_unavailable", `Tool ${call.name} is not available`);
+ const result = await appendToolResult(tx, conversationId, call, unavailable, runtime.now());
+ slots.push({ callId: call.id, name: call.name, status: "done", entry: result.id });
+ continue;
+ }
+ if (sequential && tools2.length > 0) {
+ pending.push(call.id);
+ slots.push({ callId: call.id, name: call.name, status: "pending" });
+ continue;
+ }
+ const taskId = await createToolTask(tx, runtime, entry.id, call.id);
+ tools2.push(taskId);
+ slots.push({ callId: call.id, name: call.name, taskId, status: "pending" });
+ }
+ delete live.generation;
+ live.tools = slots;
+ const checkpoint = { phase: "tools", assistant: entry.id, tools: tools2, pending };
+ return { status: "waiting", checkpoint, on: tools2, policy: "allSettled" };
+ }, context);
+}
+async function finishToolRound(runtime, assistant, tools, context) {
+ const conversationId = runtime.conversationId;
+ const controls = /* @__PURE__ */ new Map();
+ const outcomes = await runtime.outcomes(tools, context);
+ tools.forEach((id, index3) => {
+ const outcome = outcomes[index3];
+ controls.set(id, outcome.status === "completed" ? outcome.result.control : void 0);
+ });
+ const slots = (await runtime.snapshot(LiveDoc, conversationId, context))?.tools ?? [];
+ const results = slots.flatMap((slot) => slot.entry === void 0 ? [] : [slot.entry]);
+ await runtime.hooks.each("afterTools", (hook2) => hook2(assistant, results, runtime, context));
+ const terminate = slots.length > 0 && slots.every((slot) => slot.taskId !== void 0 && controls.get(slot.taskId)?.terminate === true);
+ const added = [...controls.values()].flatMap((control) => control?.addTools ?? []);
+ const handoff = [...controls.values()].findLast((control) => control?.handoff !== void 0)?.handoff;
+ await runtime.commit(async (tx) => {
+ const boundary = await prepareBoundary(tx, conversationId, runtime.settings);
+ if (added.length > 0)
+ await addTools(tx, conversationId, added);
+ const live = await tx.doc(LiveDoc, conversationId);
+ const now = runtime.now();
+ if (terminate || handoff !== void 0) {
+ if (handoff !== void 0) {
+ const message = { role: "user", content: handoff, timestamp: now };
+ const entry = await tx.appendEntry(ResetEntry, conversationId, { head: "self", model: [message] });
+ boundary.head = entry.id;
+ }
+ const { users } = await applyBoundary(tx, boundary, "final", now);
+ endRun(tx, live, runtime.taskId, { status: "done", answer: assistant });
+ if (users.length > 0)
+ await startRun(tx, conversationId, live, users);
+ } else {
+ const { users, reset } = await applyBoundary(tx, boundary, "postTools", now);
+ if (reset) {
+ endRun(tx, live, runtime.taskId, { status: "unanswered", reason: "reset" });
+ if (users.length > 0)
+ await startRun(tx, conversationId, live, users);
+ } else {
+ delete live.tools;
+ if (live.run?.taskId === runtime.taskId)
+ live.run.inputs.push(...users);
+ handOver(live, runtime.taskId, await createGeneration(tx, conversationId));
+ }
+ }
+ return { status: "terminal", outcome: { status: "completed", result: { entryId: assistant } } };
+ }, context);
+}
+async function appendAssistant(tx, conversationId, message) {
+ await recordUsage(tx, conversationId, "models", `${message.provider}/${message.model}`, message.usage);
+ return tx.appendEntry(AssistantEntry, conversationId, { model: [message] });
+}
+async function startRun(tx, conversationId, live, inputs) {
+ live.run = { taskId: await createGeneration(tx, conversationId), inputs };
+}
+function createGeneration(tx, conversationId) {
+ return tx.createTask(GenerationTask, {}, { ownership: { kind: "conversation" }, conversationId });
+}
+function handOver(live, from, to) {
+ if (live.run?.taskId === from)
+ live.run.taskId = to;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/live.js
+var LiveDoc = defineDoc({
+ kind: "pi.live",
+ version: 1,
+ scope: "conversation",
+ history: "latest",
+ fork: "initial",
+ initial: () => ({}),
+ // REMINDER: a complete base whenever nothing runs (spec §8.2): no generation and no running tool slot. That holds
+ // while idle, in the commit handing a generation over to its tool round, and between tools, so the delta chain
+ // spans at most one generation or the overlapping execution of one round's tools. A slot holds output only while
+ // running, so every base is small. Do not add a delta-count bound; the tool output benchmark checks this rule.
+ checkpointWhen: (value) => value.generation === void 0 && !(value.tools ?? []).some((slot) => slot.status === "running")
+});
+var RUN_TASK_KINDS = /* @__PURE__ */ new Set(["pi.generation"]);
+var TOOL_TASK_KIND = "pi.tool";
+var COMPACTION_TASK_KIND = "pi.compaction";
+function endRun(tx, live, taskId, settlement) {
+ if (live.run?.taskId === taskId) {
+ for (const id of live.run.inputs)
+ tx.settleSubmission(id, settlement);
+ delete live.run;
+ }
+ delete live.generation;
+ delete live.tools;
+}
+function addCompactionStatus(live, status) {
+ live.compactions ??= [];
+ live.compactions.push(status);
+}
+function compactionStatus(live, taskId) {
+ return live.compactions?.find((status) => status.taskId === taskId);
+}
+function removeCompactionStatus(live, taskId) {
+ const statuses = live.compactions;
+ if (statuses === void 0)
+ return;
+ const index3 = statuses.findIndex((status) => status.taskId === taskId);
+ if (index3 >= 0)
+ statuses.splice(index3, 1);
+ if (statuses.length === 0)
+ delete live.compactions;
+}
+function toolSlot(live, taskId) {
+ return live.tools?.find((slot) => slot.taskId === taskId);
+}
+function finishSlot(slot, entry) {
+ slot.status = "done";
+ if (entry !== void 0)
+ slot.entry = entry;
+ clearProgress(slot);
+}
+function clearProgress(slot) {
+ delete slot.output;
+ delete slot.droppedBytes;
+ delete slot.droppedLines;
+ delete slot.details;
+ delete slot.diagnostics;
+}
+async function settleSchedulerOutcome(tx, record, outcome) {
+ if (record.kind === TOOL_TASK_KIND) {
+ const slot = toolSlot(await tx.doc(LiveDoc, record.conversationId), record.id);
+ if (slot !== void 0)
+ finishSlot(slot, void 0);
+ return;
+ }
+ if (record.kind === COMPACTION_TASK_KIND) {
+ removeCompactionStatus(await tx.doc(LiveDoc, record.conversationId), record.id);
+ return;
+ }
+ if (!RUN_TASK_KINDS.has(record.kind))
+ return;
+ const live = await tx.doc(LiveDoc, record.conversationId);
+ if (live.run?.taskId !== record.id)
+ return;
+ await convertPartial(tx, live, record.conversationId);
+ endRun(tx, live, record.id, outcome.status === "faulted" ? { status: "unanswered", reason: "faulted", detail: outcome.error.message } : { status: "unanswered", reason: outcome.reason });
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/util.js
+var Waiters = class {
+ #sets = /* @__PURE__ */ new Map();
+ add(key, context) {
+ const signal = context.abortSignal;
+ if (signal?.aborted)
+ return Promise.reject(signal.reason);
+ const waiter = Promise.withResolvers();
+ const set = this.#sets.get(key) ?? /* @__PURE__ */ new Set();
+ this.#sets.set(key, set.add(waiter));
+ if (signal !== void 0) {
+ const onAbort = () => {
+ set.delete(waiter);
+ if (set.size === 0 && this.#sets.get(key) === set)
+ this.#sets.delete(key);
+ waiter.reject(signal.reason);
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ const detach = () => signal.removeEventListener("abort", onAbort);
+ waiter.promise.then(detach, detach);
+ }
+ return waiter.promise;
+ }
+ keys() {
+ return [...this.#sets.keys()];
+ }
+ resolve(key, value) {
+ const set = this.#sets.get(key);
+ this.#sets.delete(key);
+ for (const waiter of set ?? [])
+ waiter.resolve(value);
+ }
+ rejectAll(error) {
+ const sets = [...this.#sets.values()];
+ this.#sets.clear();
+ for (const set of sets)
+ for (const waiter of set)
+ waiter.reject(error);
+ }
+};
+async function scanAll(scan) {
+ const items = [];
+ let cursor;
+ do {
+ const page2 = await scan(cursor);
+ items.push(...page2.items);
+ cursor = page2.next;
+ } while (cursor !== void 0);
+ return items;
+}
+function closedError() {
+ return new Error("Harness is closed");
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/submissions.js
+var Submissions = class {
+ #session;
+ #storage;
+ #now;
+ /** Read at each admission, on the Session line. */
+ #queueModes;
+ /** Enable task scheduling; submitting or waiting asks for progress. */
+ #resume;
+ #waiters = new Waiters();
+ #closed = false;
+ constructor(session, storage, now, queueModes, resume) {
+ this.#session = session;
+ this.#storage = storage;
+ this.#now = now;
+ this.#queueModes = queueModes;
+ this.#resume = resume;
+ session.subscribeCommits((publication) => this.#observe(publication));
+ session.subscribeClose(() => {
+ this.#closed = true;
+ this.#waiters.rejectAll(closedError());
+ });
+ }
+ /** Admit a submission in one commit; see `admitSubmission()`. */
+ async submit(conversationId, draft, context) {
+ this.#resume();
+ const id = await this.#session.commitWith((tx) => admitSubmission(tx, conversationId, draft, this.#now(), this.#queueModes()), context);
+ return new SubmissionHandle(id, this);
+ }
+ /** Handle for an existing submission, or `undefined`. */
+ async get(id, context) {
+ const record = await this.#session.readOnLine(() => this.#storage.submission(id, context));
+ return record === void 0 ? void 0 : new SubmissionHandle(record.id, this);
+ }
+ async status(id, context) {
+ const record = await this.#session.readOnLine(() => this.#storage.submission(id, context));
+ if (record === void 0)
+ throw new Error(`Submission ${id} does not exist`);
+ return record;
+ }
+ async wait(id, context) {
+ this.#resume();
+ const found = await this.#session.readOnLine(async () => {
+ const record = await this.#storage.submission(id, context);
+ if (record === void 0)
+ throw new Error(`Submission ${id} does not exist`);
+ if (isSettled(record))
+ return { promise: Promise.resolve(record) };
+ if (this.#closed)
+ throw closedError();
+ return { promise: this.#waiters.add(id, context) };
+ });
+ return found.promise;
+ }
+ /** Withdraw a queued submission and remove its inbox item; placed inputs and settled submissions are reported. */
+ abort(id, context, conversationId) {
+ return this.#session.commitWith(async (tx) => {
+ const record = await tx.submission(id);
+ if (record === void 0 || conversationId !== void 0 && record.conversationId !== conversationId) {
+ return "not_found";
+ }
+ if (record.status === "queued") {
+ tx.settleSubmission(id, { status: "unanswered", reason: "aborted" });
+ await removeInboxItem(tx, record.conversationId, id);
+ return "aborted";
+ }
+ return record.status === "placed" ? "already_placed" : "settled";
+ }, context);
+ }
+ #observe(publication) {
+ for (const change of publication.changes) {
+ if (change.type !== "submission" || !isSettled(change.value))
+ continue;
+ this.#waiters.resolve(change.value.id, change.value);
+ }
+ }
+};
+var SubmissionHandle = class {
+ id;
+ #submissions;
+ constructor(id, submissions) {
+ this.id = id;
+ this.#submissions = submissions;
+ }
+ status(context) {
+ return this.#submissions.status(this.id, context);
+ }
+ wait(context) {
+ return this.#submissions.wait(this.id, context);
+ }
+ async abort(context) {
+ const result = await this.#submissions.abort(this.id, context);
+ if (result === "not_found")
+ throw new Error(`Submission ${this.id} does not exist`);
+ return result;
+ }
+};
+function isSettled(record) {
+ return record.status === "done" || record.status === "unanswered";
+}
+async function admitSubmission(tx, conversationId, draft, now, queueModes) {
+ if (draft.requestId !== void 0) {
+ const existing = await tx.submissionByRequest(conversationId, draft.requestId);
+ if (existing !== void 0) {
+ if (existing.type !== draft.type) {
+ throw new Error(`Request ${draft.requestId} already identifies a submission of type ${existing.type}`);
+ }
+ return existing.id;
+ }
+ }
+ const live = await tx.doc(LiveDoc, conversationId);
+ const busy = live.run !== void 0;
+ if (busy && draft.type === "input" && draft.whenBusy === "reject")
+ throw new ConversationBusy(conversationId);
+ const requestId = draft.requestId === void 0 ? {} : { requestId: draft.requestId };
+ const boundary = busy ? void 0 : await prepareBoundary(tx, conversationId, queueModes);
+ if (boundary === void 0 || boundary.inbox.items.length > 0) {
+ const { id: id2 } = await tx.createSubmission({
+ conversationId,
+ ...requestId,
+ type: draft.type,
+ status: "queued"
+ });
+ const value = copyJson(draft.type === "write" ? draft.entry : draft.content, {
+ omitUndefinedProperties: true
+ });
+ const items = (boundary?.inbox ?? await tx.doc(InboxDoc, conversationId)).items;
+ if (draft.type === "write")
+ items.push({ id: id2, mode: "write", entry: value });
+ else {
+ const mode = draft.whenBusy === "steer" ? "steer" : "followUp";
+ items.push({ id: id2, mode, content: value });
+ }
+ if (boundary === void 0)
+ return id2;
+ const { users } = await applyBoundary(tx, boundary, "final", now);
+ if (users.length > 0)
+ await startRun(tx, conversationId, live, users);
+ return id2;
+ }
+ if (draft.type === "write") {
+ if (isStale(boundary, draft.entry)) {
+ const stale = { status: "unanswered", reason: "stale" };
+ return (await tx.createSubmission({ conversationId, ...requestId, type: "write", ...stale })).id;
+ }
+ const entry2 = await tx.appendEntry(conversationId, draft.entry);
+ const write = { conversationId, ...requestId, type: "write", status: "done", entry: entry2.id };
+ return (await tx.createSubmission(write)).id;
+ }
+ const message = { role: "user", content: draft.content, timestamp: now };
+ const entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });
+ const input = { conversationId, ...requestId, type: "input", status: "placed", entry: entry.id };
+ const { id } = await tx.createSubmission(input);
+ await startRun(tx, conversationId, live, [id]);
+ return id;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/compaction.js
+var TOOL_RESULT_MAX_CHARS = 2e3;
+var SUMMARY_PREFIX = "The conversation history before this point was compacted into the following summary:\n\n\n";
+var SUMMARY_SUFFIX = "\n";
+var SUMMARIZATION_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
+
+Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;
+var SUMMARIZATION_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work. If the conversation starts with an earlier summary, preserve its information and fold the newer messages into it.
+
+Use this EXACT format:
+
+## Goal
+[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
+
+## Constraints & Preferences
+- [Any constraints, preferences, or requirements mentioned by user]
+- [Or "(none)" if none were mentioned]
+
+## Progress
+### Done
+- [x] [Completed tasks/changes]
+
+### In Progress
+- [ ] [Current work]
+
+### Blocked
+- [Issues preventing progress, if any]
+
+## Key Decisions
+- **[Decision]**: [Brief rationale]
+
+## Next Steps
+1. [Ordered list of what should happen next]
+
+## Critical Context
+- [Any data, examples, or references needed to continue]
+- [Or "(none)" if not applicable]
+
+Keep each section concise. Preserve exact file paths, function names, and error messages.`;
+var CompactionTask = defineTask({
+ name: "pi.compaction",
+ version: 1,
+ initial: () => ({ phase: "select" }),
+ phases: {
+ select: async (task, runtime, context) => {
+ const { conversationId } = runtime;
+ const agent = await runtime.agent(context);
+ const settings2 = runtime.settings;
+ const ref = agent.model;
+ const model = ref === void 0 ? void 0 : runtime.models.getModel(ref.provider, ref.modelId);
+ if (ref === void 0 || model === void 0)
+ return failNoModel2(runtime, ref, context);
+ const policy = settings2.compaction;
+ const view = await runtime.context(conversationId, context);
+ const cut = selectCut(view, policy.keepRecentTokens);
+ if (cut === void 0)
+ return complete(runtime, context);
+ const firstKept = view.entries[cut].id;
+ const { reason, instructions: instructions2 } = task.input;
+ const compaction = {
+ reason,
+ entries: view.entries.slice(0, cut),
+ messages: summarizedMessages(view, cut),
+ firstKept,
+ ...instructions2 === void 0 ? {} : { instructions: instructions2 }
+ };
+ let decision;
+ await runtime.hooks.each("beforeCompact", async (hook2) => {
+ if (decision === void 0)
+ decision = await hook2(compaction, runtime, context);
+ });
+ if (decision !== void 0 && "decline" in decision)
+ return complete(runtime, context);
+ if (decision !== void 0)
+ return place(runtime, firstKept, decision.summary, context);
+ const request = {
+ attempt: 1,
+ model: ref,
+ thinkingLevel: agent.thinkingLevel,
+ streamOptions: settings2.stream,
+ maxTokens: Math.min(Math.floor(0.8 * policy.reserveTokens), model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY),
+ tail: view.entries.reduce((tail, entry) => entry.id > tail ? entry.id : tail, firstKept),
+ firstKept
+ };
+ await runtime.commit(() => ({ status: "running", checkpoint: { phase: "summarize", ...request } }), context);
+ },
+ summarize: async (task, runtime, context) => {
+ const { phase: _, ...request } = task.state.checkpoint;
+ const { model: ref, thinkingLevel, streamOptions, maxTokens, tail, firstKept, attempt } = request;
+ const model = runtime.models.getModel(ref.provider, ref.modelId);
+ if (model === void 0)
+ return failNoModel2(runtime, ref, context);
+ const view = await runtime.context(runtime.conversationId, context, tail);
+ const cut = view.entries.findIndex((entry) => entry.id === firstKept);
+ const now = runtime.now();
+ const messages = [
+ { role: "system", content: SUMMARIZATION_SYSTEM_PROMPT, timestamp: now },
+ {
+ role: "user",
+ content: [{ type: "text", text: summaryPrompt(summarizedMessages(view, cut), task.input.instructions) }],
+ timestamp: now
+ }
+ ];
+ const { deferred: _deferred, ...forwarded } = streamOptions;
+ const options = {
+ ...forwarded,
+ cacheRetention: "none",
+ maxTokens,
+ signal: runtime.signal,
+ sessionId: await ensureProviderSessionId(runtime, context),
+ ...thinkingLevel === "off" ? {} : { reasoning: thinkingLevel }
+ };
+ const message = await runtime.models.completeSimple(model, { messages }, options);
+ runtime.signal.throwIfAborted();
+ const summary = summaryText(message);
+ const policy = runtime.settings.retry;
+ const retry = message.stopReason === "error" && isRetryableAssistantError(message) && policy.enabled && attempt <= policy.maxRetries;
+ const until = retry ? runtime.now() + retryDelayMs(policy, attempt) : 0;
+ await runtime.commit(async (tx, current) => {
+ await recordUsage(tx, runtime.conversationId, "models", `${message.provider}/${message.model}`, message.usage);
+ const live = await tx.doc(LiveDoc, runtime.conversationId);
+ if (summary !== void 0)
+ return placeSummary(tx, runtime, current, live, firstKept, summary);
+ if (retry) {
+ const status = compactionStatus(live, runtime.taskId);
+ if (status !== void 0)
+ status.retry = { at: until, error: message.errorMessage ?? "" };
+ return { status: "running", checkpoint: { phase: "retry", ...request, until } };
+ }
+ removeCompactionStatus(live, runtime.taskId);
+ const text = summaryFailure(message);
+ return {
+ status: "terminal",
+ outcome: { status: "failed", error: { message: text, detail: { reason: "model_error" } } }
+ };
+ }, context);
+ },
+ retry: async (task, runtime, context) => {
+ const { phase: _, until, ...request } = task.state.checkpoint;
+ await runtime.sleep(until, context);
+ const attempt = request.attempt + 1;
+ await runtime.commit(async (tx) => {
+ const status = compactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
+ if (status !== void 0) {
+ status.attempt = attempt;
+ delete status.retry;
+ }
+ return { status: "running", checkpoint: { phase: "summarize", ...request, attempt } };
+ }, context);
+ }
+ },
+ abort: async (_task, runtime, context) => {
+ await runtime.commit(async (tx) => {
+ removeCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
+ return { status: "terminal", outcome: { status: "aborted" } };
+ }, context);
+ }
+});
+async function createCompaction(tx, conversationId, input, owner) {
+ const ownership = owner === void 0 ? { kind: "conversation" } : { kind: "task", taskId: owner };
+ const background = owner === void 0 && input.reason !== "manual";
+ const taskId = await tx.createTask(CompactionTask, input, { ownership, conversationId, background });
+ const status = { taskId, reason: input.reason, blocking: owner !== void 0, attempt: 1 };
+ addCompactionStatus(await tx.doc(LiveDoc, conversationId), status);
+ return taskId;
+}
+function selectCut(view, keepRecentTokens) {
+ const { contributions } = view;
+ const start = view.head === void 0 ? 0 : 1;
+ const candidates = [];
+ for (let index3 = start; index3 < contributions.length; index3++) {
+ if (isCandidate(contributions, index3))
+ candidates.push(index3);
+ }
+ let kept = 0;
+ let cut;
+ for (let index3 = contributions.length - 1; index3 >= start; index3--) {
+ for (const message of contributions[index3])
+ kept += estimateMessageTokens(message);
+ if (kept < keepRecentTokens)
+ continue;
+ cut = candidates.find((candidate) => candidate >= index3) ?? candidates.at(-1);
+ break;
+ }
+ if (cut === void 0)
+ return void 0;
+ for (let index3 = start; index3 < cut; index3++)
+ if (contributions[index3].length > 0)
+ return cut;
+ return void 0;
+}
+function isCandidate(contributions, index3) {
+ const first = contributions[index3][0];
+ if (first?.role === "assistant")
+ return true;
+ if (first?.role !== "user")
+ return false;
+ let calls = /* @__PURE__ */ new Set();
+ for (let before = index3 - 1; before >= 0; before--) {
+ const assistant = contributions[before].findLast((message) => message.role === "assistant");
+ if (assistant === void 0)
+ continue;
+ calls = new Set(assistant.content.flatMap((content) => content.type === "toolCall" ? [content.id] : []));
+ break;
+ }
+ if (calls.size === 0)
+ return true;
+ for (let after = index3; after < contributions.length; after++) {
+ for (const [position, message] of contributions[after].entries()) {
+ if (message.role === "assistant" && (after > index3 || position > 0))
+ return true;
+ if (message.role === "toolResult" && calls.has(message.toolCallId))
+ return false;
+ }
+ }
+ return true;
+}
+function summarizedMessages(view, cut) {
+ return orderToolResults(view.contributions.slice(0, cut).flat());
+}
+function estimateContext(view, extra) {
+ let measured;
+ const after = view.head?.id ?? Number.NEGATIVE_INFINITY;
+ for (let index3 = view.entries.length - 1; index3 >= 0 && measured === void 0; index3--) {
+ if (view.entries[index3].id <= after)
+ continue;
+ measured = view.contributions[index3].findLast((message) => message.role === "assistant" && calculateContextTokens(message.usage) > 0);
+ }
+ const from = measured === void 0 ? 0 : view.messages.lastIndexOf(measured) + 1;
+ let tokens = measured === void 0 ? 0 : calculateContextTokens(measured.usage);
+ for (const message of view.messages.slice(from))
+ tokens += estimateMessageTokens(message);
+ for (const message of extra)
+ tokens += estimateMessageTokens(message);
+ return tokens;
+}
+function summaryText(message) {
+ if (message.stopReason !== "stop" || message.content.some((content) => content.type === "toolCall"))
+ return void 0;
+ const text = message.content.flatMap((content) => content.type === "text" ? [content.text] : []).join("\n").trim();
+ return text.length === 0 ? void 0 : text;
+}
+function summaryFailure(message) {
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
+ return `Summarization failed: ${message.errorMessage ?? message.stopReason}`;
+ }
+ if (message.stopReason === "length")
+ return "Summarization hit the token limit; the summary is incomplete";
+ if (message.content.some((content) => content.type === "toolCall"))
+ return "Summarization attempted to call a tool";
+ return "Summarization produced no text";
+}
+function summaryPrompt(messages, instructions2) {
+ const focus = instructions2 === void 0 ? "" : `
+
+Additional focus: ${instructions2}`;
+ return `
+${serializeConversation(messages)}
+
+
+${SUMMARIZATION_PROMPT}${focus}`;
+}
+function serializeConversation(messages) {
+ const parts2 = [];
+ for (const message of messages) {
+ if (message.role === "user") {
+ const text = contentText2(message.content);
+ if (text.length > 0)
+ parts2.push(`[User]: ${text}`);
+ } else if (message.role === "assistant") {
+ const thinking = message.content.flatMap((content) => content.type === "thinking" ? [content.thinking] : []);
+ const text = message.content.flatMap((content) => content.type === "text" ? [content.text] : []);
+ const calls = message.content.flatMap((content) => content.type === "toolCall" ? [
+ `${content.name}(${Object.entries(content.arguments).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(", ")})`
+ ] : []);
+ if (thinking.length > 0)
+ parts2.push(`[Assistant thinking]: ${thinking.join("\n")}`);
+ if (text.length > 0)
+ parts2.push(`[Assistant]: ${text.join("\n")}`);
+ if (calls.length > 0)
+ parts2.push(`[Assistant tool calls]: ${calls.join("; ")}`);
+ } else if (message.role === "toolResult") {
+ const text = contentText2(message.content);
+ if (text.length > 0)
+ parts2.push(`[Tool result]: ${truncate(text, TOOL_RESULT_MAX_CHARS)}`);
+ }
+ }
+ return parts2.join("\n\n");
+}
+function contentText2(content) {
+ if (typeof content === "string")
+ return content;
+ return content.flatMap((block) => block.type === "text" && block.text !== void 0 ? [block.text] : []).join("\n");
+}
+function truncate(text, maxChars) {
+ if (text.length <= maxChars)
+ return text;
+ return `${text.slice(0, maxChars)}
+
+[... ${text.length - maxChars} more characters truncated]`;
+}
+async function place(runtime, firstKept, summary, context) {
+ await runtime.commit(async (tx, current) => placeSummary(tx, runtime, current, await tx.doc(LiveDoc, runtime.conversationId), firstKept, summary), context);
+}
+async function placeSummary(tx, runtime, current, live, firstKept, summary) {
+ removeCompactionStatus(live, runtime.taskId);
+ const text = `${SUMMARY_PREFIX}${summary}${SUMMARY_SUFFIX}`;
+ const entry = {
+ kind: CompactionEntry.kind,
+ head: firstKept,
+ model: [{ role: "user", content: [{ type: "text", text }], timestamp: runtime.now() }],
+ data: { reason: current.input.reason }
+ };
+ const result = current.owner === void 0 ? {
+ submissionId: await admitSubmission(tx, runtime.conversationId, { type: "write", requestId: `compaction:${runtime.taskId}`, entry }, runtime.now(), runtime.settings)
+ } : { entryId: (await tx.appendEntry(runtime.conversationId, entry)).id };
+ return { status: "terminal", outcome: { status: "completed", result } };
+}
+async function complete(runtime, context) {
+ await runtime.commit(async (tx) => {
+ removeCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
+ return { status: "terminal", outcome: { status: "completed", result: {} } };
+ }, context);
+}
+async function failNoModel2(runtime, ref, context) {
+ const message = ref === void 0 ? "No model is configured" : `Model ${ref.provider}/${ref.modelId} is not available`;
+ await runtime.commit(async (tx) => {
+ removeCompactionStatus(await tx.doc(LiveDoc, runtime.conversationId), runtime.taskId);
+ return { status: "terminal", outcome: { status: "failed", error: { message, detail: { reason: "no_model" } } } };
+ }, context);
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/define.js
+function defineExtension(extension) {
+ return extension;
+}
+function defineTool(tool) {
+ return tool;
+}
+function section(key, render, options) {
+ return options?.tag === void 0 ? { key, render } : { key, render, tag: options.tag };
+}
+
+// node_modules/@earendil-works/pi-durable/dist/session/observation.js
+var MAX_PENDING_WATCH_FRAMES = 100;
+var RETIREMENT_OPERATIONS = [["r", null]];
+var CommittedStateSource = class {
+ #attachments = /* @__PURE__ */ new Set();
+ #release;
+ /** Released on disposal. */
+ #value;
+ #cursor = 0;
+ #retired = false;
+ #closed = false;
+ constructor(value, release) {
+ this.#value = value;
+ this.#release = release;
+ }
+ attach() {
+ if (this.#closed)
+ throw new Error("State source is closed");
+ const attachment = new SessionSourceAttachment({ value: this.#value, cursor: this.#cursor }, () => {
+ this.#attachments.delete(attachment);
+ if (this.#attachments.size === 0)
+ this.#finishDisposal();
+ });
+ this.#attachments.add(attachment);
+ return attachment;
+ }
+ advance(value, ops, context) {
+ if (this.#closed || this.#retired)
+ return;
+ this.#value = value;
+ this.#cursor += 1;
+ if (value === null)
+ this.#retired = true;
+ const frame = {
+ cursor: this.#cursor,
+ value,
+ ops,
+ context
+ };
+ for (const attachment of [...this.#attachments])
+ attachment.publish(frame);
+ }
+ closeSession() {
+ if (this.#closed)
+ return;
+ for (const attachment of [...this.#attachments])
+ attachment.dispose();
+ this.#finishDisposal();
+ }
+ #finishDisposal() {
+ if (this.#closed)
+ return;
+ this.#closed = true;
+ this.#value = void 0;
+ const release = this.#release;
+ this.#release = void 0;
+ release?.();
+ }
+};
+var SessionSourceAttachment = class {
+ snapshot;
+ #release;
+ #frames = [];
+ #listener;
+ #activated = false;
+ #disposed = false;
+ #scheduled = false;
+ #delivering = false;
+ constructor(snapshot, release) {
+ this.snapshot = snapshot;
+ this.#release = release;
+ }
+ activate(listener) {
+ if (this.#activated)
+ throw new Error("State attachment is already active");
+ if (this.#disposed)
+ throw new Error("State attachment is disposed");
+ this.#activated = true;
+ this.#listener = listener;
+ this.#drain();
+ }
+ publish(frame) {
+ if (this.#disposed)
+ return;
+ this.#frames.push(frame);
+ if (!this.#activated || this.#delivering || this.#scheduled)
+ return;
+ this.#scheduled = true;
+ queueMicrotask(() => {
+ this.#scheduled = false;
+ if (this.#disposed)
+ return;
+ try {
+ this.#drain();
+ } catch {
+ this.dispose();
+ }
+ });
+ }
+ dispose() {
+ if (this.#disposed)
+ return;
+ this.#disposed = true;
+ this.#frames.length = 0;
+ this.#listener = void 0;
+ const release = this.#release;
+ this.#release = void 0;
+ release?.();
+ }
+ #drain() {
+ const listener = this.#listener;
+ if (listener === void 0 || this.#delivering || this.#disposed)
+ return;
+ this.#delivering = true;
+ try {
+ while (!this.#disposed) {
+ const frame = this.#frames.shift();
+ if (frame === void 0)
+ break;
+ listener(frame);
+ }
+ } finally {
+ this.#delivering = false;
+ }
+ }
+};
+var CommittedWatch = class {
+ #detach;
+ #replace;
+ #closedPromise;
+ #pending = [];
+ #resolveClosed;
+ #value;
+ #listener;
+ #started = false;
+ #scheduled = false;
+ #running = false;
+ #detached = false;
+ #retired = false;
+ #end;
+ #resolved = false;
+ #cancellationSignal;
+ #cancellationListener;
+ /** `replace` gives the value an overflow delivers; by default the newest value. */
+ constructor(value, detach, replace) {
+ this.#value = value;
+ this.#detach = detach;
+ this.#replace = replace;
+ this.#closedPromise = new Promise((resolve3) => {
+ this.#resolveClosed = resolve3;
+ });
+ }
+ get value() {
+ return this.#value;
+ }
+ get closed() {
+ return this.#closedPromise;
+ }
+ start(listener) {
+ if (this.#started)
+ throw new Error("Watch is already started");
+ if (this.#end !== void 0)
+ throw new Error("Watch is stopped");
+ this.#started = true;
+ this.#listener = listener;
+ if (this.#pending.length > 0)
+ this.#schedule();
+ }
+ stop() {
+ this.#terminate({ reason: "stopped" });
+ return this.#closedPromise;
+ }
+ observeCancellation(signal) {
+ if (this.#cancellationSignal !== void 0)
+ throw new Error("Watch cancellation is already installed");
+ if (this.#end !== void 0)
+ return;
+ this.#cancellationSignal = signal;
+ this.#cancellationListener = () => this.cancel();
+ signal.addEventListener("abort", this.#cancellationListener, { once: true });
+ if (signal.aborted)
+ this.cancel();
+ }
+ cancel() {
+ this.#terminate({ reason: "cancelled" });
+ }
+ closeSession() {
+ this.#terminate({ reason: "session_closed" });
+ }
+ advance(value, ops, context) {
+ if (this.#end !== void 0 || this.#retired)
+ return;
+ if (value === null)
+ this.#retired = true;
+ if (this.#pending.length >= MAX_PENDING_WATCH_FRAMES) {
+ this.#pending.length = 0;
+ const replacement = this.#replace?.() ?? value;
+ this.#pending.push({ value: replacement, ops: [["r", replacement]], context });
+ } else {
+ this.#pending.push({ value, ops, context });
+ }
+ if (this.#started)
+ this.#schedule();
+ }
+ #schedule() {
+ if (this.#scheduled || this.#running || this.#end !== void 0)
+ return;
+ this.#scheduled = true;
+ queueMicrotask(() => {
+ this.#scheduled = false;
+ void this.#drain();
+ });
+ }
+ async #drain() {
+ if (this.#running || this.#end !== void 0 || !this.#started) {
+ this.#finishIfReady();
+ return;
+ }
+ this.#running = true;
+ try {
+ while (this.#end === void 0) {
+ const frame = this.#pending.shift();
+ if (frame === void 0)
+ break;
+ this.#value = frame.value;
+ const deliveryContext = withoutAbortSignal(frame.context);
+ try {
+ await this.#listener(frame.value, frame.ops, deliveryContext);
+ } catch (error) {
+ if (this.#end === void 0) {
+ this.#terminate({ reason: "listener_error", error: toError2(error) });
+ }
+ break;
+ }
+ if (frame.value === null) {
+ this.#terminate({ reason: "retired" });
+ break;
+ }
+ }
+ } finally {
+ this.#running = false;
+ if (this.#end === void 0 && this.#pending.length > 0)
+ this.#schedule();
+ this.#finishIfReady();
+ }
+ }
+ #terminate(end) {
+ if (this.#end !== void 0)
+ return;
+ this.#end = end;
+ this.#detachNow();
+ this.#pending.length = 0;
+ this.#finishIfReady();
+ }
+ #detachNow() {
+ if (this.#detached)
+ return;
+ this.#detached = true;
+ this.#detach();
+ }
+ #finishIfReady() {
+ if (this.#resolved || this.#end === void 0)
+ return;
+ this.#resolved = true;
+ if (this.#cancellationSignal !== void 0 && this.#cancellationListener !== void 0) {
+ this.#cancellationSignal.removeEventListener("abort", this.#cancellationListener);
+ }
+ this.#resolveClosed(this.#end);
+ }
+};
+function toError2(error) {
+ return error instanceof Error ? error : new Error(String(error));
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/view.js
+var MOUNTED = [
+ AgentDoc,
+ LiveDoc,
+ InboxDoc,
+ ProviderDoc,
+ UsageDoc
+];
+var MOUNTED_KINDS = new Set(MOUNTED.map((token) => token.definition.kind));
+var VIEWS = /* @__PURE__ */ new WeakMap();
+function conversationViews(harness) {
+ const views = VIEWS.get(harness);
+ if (views === void 0)
+ throw new Error("Not a Harness");
+ return views;
+}
+var ConversationViews = class {
+ #session;
+ #storage;
+ #mounts = /* @__PURE__ */ new Map();
+ #closed = false;
+ constructor(session, storage) {
+ this.#session = session;
+ this.#storage = storage;
+ VIEWS.set(session, this);
+ session.subscribeCommits((publication, context) => {
+ for (const [id, mount] of this.#mounts)
+ advance(id, mount, publication, context);
+ });
+ session.subscribeClose(() => {
+ this.#closed = true;
+ for (const mount of this.#mounts.values())
+ for (const observer of [...mount.observers])
+ observer.closeSession();
+ this.#mounts.clear();
+ });
+ }
+ /** A disposable read-only Chord state of the view. */
+ async state(id, context) {
+ const { observer, detach } = await this.attach(id, (value, release) => new CommittedStateSource(value, release), context);
+ try {
+ return replicatedState(observer);
+ } catch (error) {
+ detach();
+ throw error;
+ }
+ }
+ /** A serialized exact-frame watch of the view; cancelling `context` stops it. */
+ async watch(id, context) {
+ const { observer } = await this.attach(id, (value, release) => new CommittedWatch(value, release), context);
+ const signal = context.abortSignal;
+ if (signal?.aborted) {
+ observer.cancel();
+ throw signal.reason;
+ }
+ if (signal !== void 0)
+ observer.observeCancellation(signal);
+ return observer;
+ }
+ /**
+ * Register an observer created from the current revision, atomically on the Session line: it sees every later
+ * publication and nothing earlier. `create` may read committed Storage, still on the line. `release` drops it, and
+ * the mount with its last observer.
+ */
+ attach(id, create, context) {
+ return this.#session.readOnLine(async () => {
+ const mount = this.#mounts.get(id) ?? await this.#build(id, context);
+ const detach = () => {
+ mount.observers.delete(observer);
+ if (mount.observers.size === 0 && this.#mounts.get(id) === mount)
+ this.#mounts.delete(id);
+ };
+ const observer = await create(mount.value, detach, this.#storage);
+ if (this.#closed)
+ throw closedError();
+ context.abortSignal?.throwIfAborted();
+ this.#mounts.set(id, mount);
+ mount.observers.add(observer);
+ return { observer, detach };
+ });
+ }
+ async #build(id, context) {
+ const conversation = await this.#storage.conversation(id, context);
+ if (conversation === void 0)
+ throw new Error(`Conversation ${id} does not exist`);
+ const bounds = await captureContextBounds(this.#storage, id, context);
+ const entries = await activeEntries(this.#storage, id, bounds, context);
+ const docs = {};
+ const incarnations = /* @__PURE__ */ new Map();
+ for (const token of MOUNTED) {
+ const loaded = await this.#session.conversationDocumentOnLine(token, id, context);
+ if (loaded === void 0)
+ continue;
+ docs[token.definition.kind] = loaded.value;
+ incarnations.set(token.definition.kind, { id: loaded.record.id, version: loaded.version });
+ }
+ return { value: { conversation, entries, docs }, docs: incarnations, observers: /* @__PURE__ */ new Set() };
+ }
+};
+function advance(id, mount, publication, context) {
+ const docOps = [];
+ const entryOps = [];
+ let entries = mount.value.entries;
+ for (const change of publication.changes) {
+ if (change.type === "entry" && change.value.conversationId === id) {
+ const entry = change.value;
+ const value = entry;
+ if (entry.head === void 0) {
+ entryOps.push(["p", ["entries"], entries.length, 0, [value]]);
+ entries = [...entries, entry];
+ continue;
+ }
+ const target = entry.head;
+ let kept = entries.findIndex((candidate) => candidate.head === void 0 && candidate.id >= target);
+ if (kept < 0)
+ kept = entries.length;
+ entryOps.push(["p", ["entries"], 0, kept, [value]]);
+ entries = [entry, ...entries.slice(kept)];
+ continue;
+ }
+ if (change.type !== "document" || change.conversationId !== id)
+ continue;
+ const kind = change.record.kind;
+ if (!MOUNTED_KINDS.has(kind) || change.record.key !== void 0)
+ continue;
+ const path5 = ["docs", kind];
+ const mounted = mount.docs.get(kind);
+ if (change.value === null) {
+ if (mounted?.id !== change.record.id)
+ continue;
+ mount.docs.delete(kind);
+ docOps.push(["d", path5]);
+ } else if (mounted?.id === change.record.id && mounted.version === change.version) {
+ for (const op of change.ops)
+ docOps.push(prefixed(op, path5));
+ } else {
+ mount.docs.set(kind, { id: change.record.id, version: change.version });
+ docOps.push(["s", path5, change.value]);
+ }
+ }
+ const before = mount.value;
+ const ops = [...docOps, ...entryOps];
+ const frameContext = withoutAbortSignal(context);
+ if (ops.length > 0) {
+ const value = docOps.length === 0 ? mount.value : applyImmutable(mount.value, docOps);
+ mount.value = entries === value.entries ? value : { ...value, entries };
+ for (const observer of [...mount.observers])
+ observer.advance?.(mount.value, ops, frameContext);
+ }
+ for (const observer of [...mount.observers]) {
+ observer.publication?.(before, mount.value, ops, publication, frameContext);
+ }
+}
+function prefixed(op, prefix) {
+ const at = (path5) => [...prefix, ...path5];
+ switch (op[0]) {
+ case "r":
+ return ["s", prefix, op[1]];
+ case "p":
+ return ["p", at(op[1]), op[2], op[3], op[4]];
+ case "m":
+ return ["m", at(op[1]), op[2]];
+ case "s":
+ return ["s", at(op[1]), op[2]];
+ case "d":
+ return ["d", at(op[1])];
+ case "a":
+ return ["a", at(op[1]), op[2]];
+ case "t":
+ return ["t", at(op[1]), op[2]];
+ }
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/events.js
+function parts(view) {
+ return {
+ live: view.docs["pi.live"] ?? {},
+ inbox: view.docs["pi.inbox"],
+ agent: view.docs["pi.agent"],
+ usage: view.docs["pi.usage"]
+ };
+}
+function snapshotOf(view) {
+ const { live, inbox, agent, usage } = parts(view);
+ return {
+ type: "snapshot",
+ entries: view.entries,
+ ...live.run === void 0 ? {} : { run: { inputs: live.run.inputs } },
+ ...live.generation === void 0 ? {} : { generation: live.generation },
+ tools: live.tools ?? [],
+ compactions: live.compactions ?? [],
+ inbox: queued(inbox),
+ agent: agent ?? AgentDoc.definition.initial(),
+ usage: usage ?? UsageDoc.definition.initial()
+ };
+}
+function queued(inbox) {
+ return (inbox?.items ?? []).map((item) => ({ id: item.id, mode: item.mode }));
+}
+async function watchEvents(harness, conversationId, context) {
+ let watch;
+ let snapshot;
+ await conversationViews(harness).attach(conversationId, async (initial, release, storage) => {
+ const query = { conversationId, kind: "pi.generation", status: "completing" };
+ const completing = await scanAll((cursor) => storage.scanTasks(query, 100, cursor, context));
+ const held = new Set(completing.map((record) => record.id));
+ let current = initial;
+ snapshot = snapshotOf(initial);
+ watch = new CommittedWatch([], release, () => [snapshotOf(current)]);
+ return {
+ publication: (before, after, ops, publication, commitContext) => {
+ current = after;
+ const events = translate(conversationId, before, after, ops, publication, held);
+ if (events.length > 0)
+ watch.advance(events, [], commitContext);
+ },
+ closeSession: () => watch.closeSession()
+ };
+ }, context);
+ const signal = context.abortSignal;
+ if (signal?.aborted) {
+ watch.cancel();
+ throw signal.reason;
+ }
+ if (signal !== void 0)
+ watch.observeCancellation(signal);
+ return {
+ snapshot,
+ start: (listener) => watch.start((events, _ops, deliveryContext) => listener(events, deliveryContext)),
+ stop: () => watch.stop(),
+ closed: watch.closed
+ };
+}
+function resultOf(entries, callId) {
+ return entries.find((entry) => {
+ const message = entry.model?.[0];
+ return message?.role === "toolResult" && message.toolCallId === callId;
+ });
+}
+function translate(conversationId, before, after, viewOps, publication, held) {
+ const entries = [];
+ const tasks = /* @__PURE__ */ new Map();
+ const submissions = [];
+ for (const change of publication.changes) {
+ if (change.type === "entry" && change.value.conversationId === conversationId)
+ entries.push(change.value);
+ if (change.type === "task" && change.value.conversationId === conversationId)
+ tasks.set(change.value.id, change.value);
+ if (change.type === "submission" && change.value.conversationId === conversationId) {
+ submissions.push(change.value);
+ }
+ }
+ if (viewOps.length === 0 && entries.length === 0 && tasks.size === 0 && submissions.length === 0)
+ return [];
+ submissions.sort((a, b) => a.id - b.id);
+ const was = parts(before);
+ const now = parts(after);
+ const events = [];
+ const slotsBefore = new Map((was.live.tools ?? []).map((slot) => [slot.callId, slot]));
+ const slots = now.live.tools ?? [];
+ for (const slot of slots) {
+ if (slot.status !== "running" || slotsBefore.get(slot.callId)?.status === "running")
+ continue;
+ const checkpoint = slot.taskId === void 0 ? void 0 : tasks.get(slot.taskId)?.state.checkpoint;
+ const args = checkpoint?.arguments ?? {};
+ events.push({ type: "tool_execution_start", toolCallId: slot.callId, toolName: slot.name, args });
+ }
+ const partialBefore = was.live.generation?.message;
+ const partial = now.live.generation?.message;
+ if (partial !== void 0 && partialBefore === void 0)
+ events.push({ type: "message_start", message: partial });
+ else if (partial !== void 0 && partial !== partialBefore) {
+ events.push({ type: "message_update", usage: partial.usage, changes: messageChanges(viewOps, partial) });
+ }
+ for (const [index3, slot] of slots.entries()) {
+ const previous = slotsBefore.get(slot.callId);
+ if (slot.status !== "running" || previous?.status !== "running")
+ continue;
+ const update = toolUpdate(viewOps, index3, slot, previous);
+ if (update === void 0)
+ continue;
+ events.push({ type: "tool_execution_update", toolCallId: slot.callId, toolName: slot.name, ...update });
+ }
+ const generation = now.live.generation;
+ const generationBefore = was.live.generation;
+ if (generation?.retry !== void 0 && generationBefore?.retry === void 0) {
+ const { at, error } = generation.retry;
+ events.push({ type: "auto_retry_start", attempt: generation.attempt, at, errorMessage: error });
+ }
+ if (generationBefore?.retry !== void 0 && generation?.retry === void 0) {
+ events.push({ type: "auto_retry_end", attempt: generationBefore.attempt });
+ }
+ if (generation?.deferred !== void 0 && generation.deferred.pollAt !== generationBefore?.deferred?.pollAt) {
+ events.push({ type: "deferred_poll", pollAt: generation.deferred.pollAt });
+ }
+ const toolEnds = [];
+ const endTool = (callId, name, entryId) => {
+ const entry = entries.find((candidate) => candidate.id === entryId);
+ toolEnds.push({
+ type: "tool_execution_end",
+ toolCallId: callId,
+ toolName: name,
+ ...entry === void 0 ? {} : { entry }
+ });
+ };
+ for (const previous of slotsBefore.values()) {
+ if (previous.status === "done")
+ continue;
+ const slot = slots.find((candidate) => candidate.callId === previous.callId);
+ if (slot?.status === "done")
+ endTool(previous.callId, previous.name, slot.entry);
+ else if (slot === void 0)
+ endTool(previous.callId, previous.name, resultOf(entries, previous.callId)?.id);
+ }
+ for (const slot of slots) {
+ if (slot.status === "done" && !slotsBefore.has(slot.callId))
+ endTool(slot.callId, slot.name, slot.entry);
+ }
+ let assistantAppended = false;
+ for (const entry of entries) {
+ events.push(...toolEnds.filter((end) => end.entry === entry));
+ const message = entry.model?.[0];
+ if (message === void 0) {
+ events.push({ type: "entry_appended", entry });
+ continue;
+ }
+ const streamed = message.role === "assistant" && partialBefore !== void 0 && !assistantAppended;
+ if (message.role === "assistant")
+ assistantAppended = true;
+ if (!streamed)
+ events.push({ type: "message_start", message });
+ events.push({ type: "message_end", entry });
+ }
+ events.push(...toolEnds.filter((end) => end.entry === void 0));
+ const compactionsBefore = was.live.compactions ?? [];
+ const compactions = now.live.compactions ?? [];
+ for (const { taskId, reason } of compactionsBefore) {
+ if (!compactions.some((status) => status.taskId === taskId)) {
+ events.push({ type: "compaction_end", taskId, reason });
+ }
+ }
+ let turnEnded = false;
+ for (const task of tasks.values()) {
+ const status = task.state.status;
+ if (task.kind === "pi.generation" && status === "completing" && !held.has(task.id)) {
+ held.add(task.id);
+ turnEnded = true;
+ }
+ if (status !== "terminal")
+ continue;
+ if (task.kind === "pi.generation" && !held.delete(task.id))
+ turnEnded = true;
+ const outcome = task.state.outcome;
+ if (outcome.status === "faulted" || outcome.status === "orphaned") {
+ const message = outcome.status === "faulted" ? outcome.error.message : outcome.reason;
+ events.push({ type: "task_failed", taskId: task.id, kind: task.kind, message });
+ }
+ }
+ if (turnEnded)
+ events.push({ type: "turn_end" });
+ const run2 = now.live.run;
+ const runBefore = was.live.run;
+ const runChanged = run2?.inputs[0] !== runBefore?.inputs[0];
+ if (runBefore !== void 0 && runChanged)
+ events.push({ type: "run_end", inputs: runBefore.inputs });
+ for (const record of submissions)
+ events.push({ type: "submission", record });
+ if (now.inbox !== was.inbox)
+ events.push({ type: "inbox_update", items: queued(now.inbox) });
+ if (now.agent !== was.agent) {
+ events.push({ type: "agent_changed", agent: now.agent ?? AgentDoc.definition.initial() });
+ }
+ if (now.usage !== was.usage)
+ events.push({ type: "usage_changed", usage: now.usage ?? UsageDoc.definition.initial() });
+ for (const { taskId, reason, blocking } of compactions) {
+ if (!compactionsBefore.some((status) => status.taskId === taskId)) {
+ events.push({ type: "compaction_start", taskId, reason, blocking });
+ }
+ }
+ if (run2 !== void 0 && runChanged)
+ events.push({ type: "run_start", inputs: run2.inputs });
+ if (run2 !== void 0 && run2.taskId !== runBefore?.taskId && tasks.get(run2.taskId)?.kind === "pi.generation") {
+ events.push({ type: "turn_start" });
+ }
+ return events;
+}
+var PARTIAL_PATH = ["docs", "pi.live", "generation", "message"];
+function messageChanges(viewOps, message) {
+ const changes = [];
+ const whole = /* @__PURE__ */ new Set();
+ for (const op of viewOps) {
+ const path5 = op[1];
+ if (!startsWith(path5, PARTIAL_PATH)) {
+ if (startsWith(PARTIAL_PATH, path5))
+ return [{ type: "message", message }];
+ continue;
+ }
+ const rest = path5.slice(PARTIAL_PATH.length);
+ if (rest[0] === "usage")
+ continue;
+ if (rest[0] !== "content")
+ return [{ type: "message", message }];
+ if (rest.length === 1) {
+ if (op[0] !== "p" || op[3] !== 0)
+ return [{ type: "message", message }];
+ for (const [offset, block] of op[4].entries()) {
+ const type = block.type === "text" ? "text_start" : block.type === "thinking" ? "thinking_start" : "toolcall_start";
+ changes.push({ type, contentIndex: op[2] + offset, block });
+ }
+ continue;
+ }
+ const contentIndex = rest[1];
+ const field = rest[2];
+ if (whole.has(contentIndex))
+ continue;
+ if (op[0] === "a" && rest.length === 3 && (field === "text" || field === "thinking")) {
+ changes.push({ type: field === "text" ? "text_delta" : "thinking_delta", contentIndex, delta: op[2] });
+ } else if (op[0] === "a" && field === "arguments") {
+ changes.push({ type: "toolcall_delta", contentIndex, path: rest.slice(3), delta: op[2] });
+ } else {
+ whole.add(contentIndex);
+ changes.push({ type: "block", contentIndex, block: message.content[contentIndex] });
+ }
+ }
+ return changes;
+}
+function toolUpdate(viewOps, index3, slot, previous) {
+ const outputPath = ["docs", "pi.live", "tools", index3, "output"];
+ let trimStart = 0;
+ let append = "";
+ let set = false;
+ for (const op of viewOps) {
+ if (!startsWith(op[1], outputPath))
+ continue;
+ if (op[0] === "t")
+ trimStart += op[2];
+ else if (op[0] === "a")
+ append += op[2];
+ else
+ set = true;
+ }
+ let output;
+ if (set || slot.output !== previous.output && trimStart === 0 && append === "")
+ output = { set: slot.output ?? "" };
+ else if (trimStart > 0 || append !== "") {
+ output = { ...trimStart > 0 ? { trimStart } : {}, ...append === "" ? {} : { append } };
+ }
+ const update = {
+ ...output === void 0 ? {} : { output },
+ ...slot.details === previous.details ? {} : { details: slot.details ?? null },
+ ...slot.diagnostics === previous.diagnostics ? {} : { diagnostics: slot.diagnostics ?? [] }
+ };
+ return Object.keys(update).length === 0 ? void 0 : update;
+}
+function startsWith(path5, prefix) {
+ return prefix.length <= path5.length && prefix.every((segment, index3) => path5[index3] === segment);
+}
+
+// node_modules/@earendil-works/pi-durable/dist/types.js
+var ROOT_CONVERSATION_ID = 1;
+
+// node_modules/@earendil-works/pi-durable/dist/session/forks.js
+var SCAN_PAGE_SIZE2 = 256;
+async function prepareForkDocumentCopies(storage, parentConversationId, at, childConversationId, context) {
+ const entry = await storage.entry(parentConversationId, at, context);
+ if (entry === void 0)
+ throw new Error(`Entry ${at} is not visible from conversation ${parentConversationId}`);
+ const copies = [];
+ const copiedAddresses = /* @__PURE__ */ new Set();
+ await collectCopies(storage, { kind: "conversation", conversationId: entry.entry.conversationId }, entry.commitSeq, "asOf", childConversationId, copies, copiedAddresses, context);
+ await collectCopies(storage, { kind: "conversation", conversationId: parentConversationId }, "current", "current", childConversationId, copies, copiedAddresses, context);
+ return copies;
+}
+async function collectCopies(storage, scope, at, policy, childConversationId, copies, copiedAddresses, context) {
+ let cursor;
+ do {
+ const page2 = await storage.scanDocuments({ scope, at }, SCAN_PAGE_SIZE2, cursor, context);
+ for (const source of page2.items) {
+ if (source.scope.kind !== "conversation" || source.fork !== policy)
+ continue;
+ const id = await storage.mintId();
+ const identity = {
+ id,
+ kind: source.kind,
+ ...source.key === void 0 ? {} : { key: source.key },
+ scope: { kind: "conversation", conversationId: childConversationId }
+ };
+ const record = source.history === "latest" ? { ...identity, history: "latest", fork: source.fork } : { ...identity, history: "rewindable", fork: source.fork };
+ const copyAddress = addressId(record);
+ if (copiedAddresses.has(copyAddress)) {
+ const member = record.key === void 0 ? record.kind : `${record.kind}/${record.key}`;
+ throw new Error(`Fork selects multiple source documents for ${member}`);
+ }
+ copiedAddresses.add(copyAddress);
+ copies.push({ record, source: { id: source.id, at } });
+ }
+ cursor = page2.next;
+ } while (cursor !== void 0);
+}
+
+// node_modules/@earendil-works/pi-durable/dist/session/transaction.js
+function applySubmissionChange(current, change) {
+ if (current.status === "done" || current.status === "unanswered")
+ return current;
+ if (change.status === "placed") {
+ if (current.status !== "queued")
+ throw new Error(`Submission ${current.id} is not queued`);
+ const status = current.type === "input" ? "placed" : "done";
+ return { ...current, status, entry: change.entry };
+ }
+ if (change.status === "done" && current.status !== "placed") {
+ throw new Error(`Submission ${current.id} is not a placed input`);
+ }
+ return { ...current, ...change };
+}
+var INTERNAL_SCAN_PAGE_SIZE = 256;
+var EMPTY_OPERATIONS = [];
+var TABLE_JSON_COPY_OPTIONS = { omitUndefinedProperties: true };
+var Transaction = class {
+ #host;
+ #context;
+ #scope;
+ #pendingOperations = /* @__PURE__ */ new Set();
+ #sealed = false;
+ #hasTableWrite = false;
+ /** Atomic batch; conversation and entry writes stage eagerly, while task and document writes assemble later. */
+ #writes = [];
+ #createdConversationIds = /* @__PURE__ */ new Set();
+ #forkSourceConversationIds = /* @__PURE__ */ new Set();
+ #forkSourceDocumentIds = /* @__PURE__ */ new Set();
+ /** One entry per task touched by a public read, candidate write, or document-owner lookup. */
+ #tasksById = /* @__PURE__ */ new Map();
+ /** Submissions created by this transaction, by ID. */
+ #submissions = /* @__PURE__ */ new Map();
+ /** Submission settlements and placements in staging order; resolved against the latest candidate record during assembly. */
+ #submissionChanges = [];
+ /** Write and publication plans of every staged incarnation, built during assembly. */
+ #plans = [];
+ /** Every document acquisition or retirement marker in staging order. */
+ #documents = [];
+ /** Latest transaction-local incarnation or retirement marker at each logical address. */
+ #latestDocumentByAddress = /* @__PURE__ */ new Map();
+ constructor(host, context, scope = {}) {
+ this.#host = host;
+ this.#context = context;
+ this.#scope = scope;
+ }
+ // ─── Table reads ────────────────────────────────────────────────────────
+ conversation(id) {
+ return this.#read("conversation", () => this.#host.storage.conversation(id, this.#context));
+ }
+ entry(first, second) {
+ const kind = typeof first === "number" ? void 0 : first.kind;
+ const id = typeof first === "number" ? first : second;
+ return this.#read("entry", async () => {
+ const entry = (await this.#host.storage.entry(id, this.#context))?.entry;
+ return kind === void 0 || entry?.kind === kind ? entry : void 0;
+ });
+ }
+ task(id) {
+ return this.#read("task", () => this.#committedTask(id));
+ }
+ scanConversations(query, limit2, cursor) {
+ return this.#read("scanConversations", () => this.#host.storage.scanConversations(query, limit2, cursor, this.#context));
+ }
+ scanEntries(query, limit2, cursor) {
+ return this.#read("scanEntries", () => this.#host.storage.scanEntries(query, limit2, cursor, this.#context));
+ }
+ latestHeadMarker(conversationId) {
+ return this.#read("latestHeadMarker", () => this.#host.storage.findLatestHeadMarker(conversationId, void 0, this.#context));
+ }
+ scanTasks(query, limit2, cursor) {
+ return this.#read("scanTasks", () => this.#host.storage.scanTasks(query, limit2, cursor, this.#context));
+ }
+ /** Internal: committed submission record. */
+ submission(id) {
+ return this.#read("submission", () => this.#host.storage.submission(id, this.#context));
+ }
+ /** Committed submission with a conversation-scoped request ID. */
+ submissionByRequest(conversationId, requestId) {
+ return this.#read("submissionByRequest", () => this.#host.storage.submissionByRequest(conversationId, requestId, this.#context));
+ }
+ // ─── Table writes ───────────────────────────────────────────────────────
+ createConversation(options) {
+ return this.#write(() => this.#stageConversation(void 0, options.ownership));
+ }
+ /** Internal final-form bootstrap path for the reserved root identity. */
+ createRootConversation() {
+ return this.#write(() => this.#stageConversation(void 0, { kind: "ownerless" }, ROOT_CONVERSATION_ID));
+ }
+ forkConversation(parentConversationId, at, options) {
+ return this.#write(() => this.#stageConversation({ conversationId: parentConversationId, at }, options.ownership));
+ }
+ async #stageConversation(parent, ownership, reservedId) {
+ const ownerTaskId = ownership.kind === "task" ? ownership.taskId : void 0;
+ const id = reservedId ?? await this.#host.storage.mintId();
+ this.#assertOpen();
+ let owner;
+ if (ownerTaskId !== void 0) {
+ const task = await this.#currentTask(ownerTaskId);
+ this.#assertOpen();
+ if (task === void 0)
+ throw new Error(`Conversation owner task ${ownerTaskId} does not exist`);
+ owner = { conversationId: task.conversationId, taskId: ownerTaskId };
+ }
+ const record = {
+ id,
+ ...parent === void 0 ? {} : { parent },
+ ...owner === void 0 ? {} : { owner }
+ };
+ const copies = parent === void 0 ? [] : await prepareForkDocumentCopies(this.#host.storage, parent.conversationId, parent.at, id, this.#context);
+ this.#assertOpen();
+ for (const copy2 of copies) {
+ this.#forkSourceDocumentIds.add(copy2.source.id);
+ const entry = {
+ addressId: addressId(copy2.record),
+ address: copy2.record,
+ target: { kind: "fork-copy", ...copy2 },
+ retireOnCommit: false
+ };
+ this.#documents.push(entry);
+ this.#latestDocumentByAddress.set(entry.addressId, entry);
+ }
+ if (parent !== void 0)
+ this.#forkSourceConversationIds.add(parent.conversationId);
+ this.#createdConversationIds.add(id);
+ this.#writes.push({ type: "conversation", value: record });
+ await this.#host.conversationCreated(this, record);
+ this.#assertOpen();
+ return record;
+ }
+ appendEntry(first, second, third) {
+ if (typeof first === "number")
+ return this.#appendEntry(first, second);
+ return this.#appendEntry(second, { ...third, kind: first.kind });
+ }
+ #appendEntry(conversationId, value) {
+ return this.#write(async () => {
+ await this.#requireConversation(conversationId);
+ this.#assertOpen();
+ const id = await this.#host.storage.mintId();
+ this.#assertOpen();
+ const { head, ...rest } = value;
+ const record = copyJson({
+ ...rest,
+ id,
+ conversationId,
+ head: head === "self" ? id : head,
+ byTaskId: this.#scope.taskId
+ }, TABLE_JSON_COPY_OPTIONS);
+ this.#writes.push({ type: "entry", value: record });
+ return record;
+ });
+ }
+ createTask(task, input, options) {
+ return this.#write(async () => {
+ const ownership = options.ownership;
+ let owner;
+ if (ownership.kind === "task") {
+ owner = await this.#currentTask(ownership.taskId);
+ this.#assertOpen();
+ if (owner === void 0)
+ throw new Error(`Task owner ${ownership.taskId} does not exist`);
+ if (options.background === true)
+ throw new TypeError("A child task cannot be background");
+ if (options.conversationId !== void 0 && options.conversationId !== owner.conversationId) {
+ throw new Error(`A child task lives in its owner's conversation ${owner.conversationId}`);
+ }
+ }
+ const conversationId = owner?.conversationId ?? options.conversationId ?? this.#scope.conversationId;
+ if (conversationId === void 0)
+ throw new TypeError("Tx.createTask() requires options.conversationId");
+ await this.#requireConversation(conversationId);
+ this.#assertOpen();
+ const definition = task.definition;
+ const checkpoint = definition.initial(input);
+ const id = await this.#host.storage.mintId();
+ this.#assertOpen();
+ const record = copyJson({
+ id,
+ conversationId,
+ kind: definition.name,
+ version: definition.version,
+ input,
+ ...owner === void 0 ? {} : { owner: owner.id },
+ background: options.background ?? false,
+ abortRequested: false,
+ state: { status: "pending", checkpoint }
+ }, TABLE_JSON_COPY_OPTIONS);
+ this.#tasksById.set(id, { write: { kind: "create", record } });
+ return id;
+ });
+ }
+ /** Create a raw submission record with a fresh ID; no admission rules apply. */
+ createSubmission(create) {
+ return this.#write(async () => {
+ await this.#requireConversation(create.conversationId);
+ this.#assertOpen();
+ const id = await this.#host.storage.mintId();
+ this.#assertOpen();
+ const record = copyJson({ ...create, id }, TABLE_JSON_COPY_OPTIONS);
+ this.#submissions.set(id, record);
+ return record;
+ });
+ }
+ /**
+ * Settle a submission. Resolved during assembly against the transaction's latest candidate record, falling back to
+ * committed state, so it is not a caller table read and works after the first table write.
+ */
+ settleSubmission(id, settlement) {
+ this.#assertOpen();
+ this.#hasTableWrite = true;
+ this.#submissionChanges.push({ id, change: copyJson(settlement) });
+ }
+ /** Place a queued submission at `entry`; resolved during assembly like `settleSubmission()`. */
+ placeSubmission(id, entry) {
+ this.#assertOpen();
+ this.#hasTableWrite = true;
+ this.#submissionChanges.push({ id, change: { status: "placed", entry } });
+ }
+ /** Internal: replace one task record completely. Tasks change their own state through their runtime. */
+ setTask(value) {
+ this.#assertOpen();
+ this.#hasTableWrite = true;
+ const task = this.#taskEntry(value.id);
+ const candidate = task.write?.record;
+ if (candidate?.state.status === "terminal") {
+ throw new Error(`Task ${value.id} already has a terminal candidate`);
+ }
+ if (candidate !== void 0 && candidate.conversationId !== value.conversationId) {
+ throw new Error(`Task ${value.id} cannot change conversations`);
+ }
+ task.write = {
+ kind: task.write?.kind === "create" ? "create" : "replace",
+ record: copyJson(value, TABLE_JSON_COPY_OPTIONS)
+ };
+ }
+ /** Internal: candidate records of the tasks this transaction created or replaced so far. */
+ stagedTasks() {
+ const records = [];
+ for (const task of this.#tasksById.values())
+ if (task.write !== void 0)
+ records.push(task.write.record);
+ return records;
+ }
+ /** Internal: conversations this transaction created or forked so far. */
+ stagedConversations() {
+ const records = [];
+ for (const write of this.#writes)
+ if (write.type === "conversation")
+ records.push(write.value);
+ return records;
+ }
+ doc(token, ...args) {
+ try {
+ this.#assertOpen();
+ const definition = token.definition;
+ const resolved = resolveAddress(definition, args);
+ this.#assertTaskDocumentsOpen(resolved);
+ const latest = this.#latestDocumentByAddress.get(resolved.id);
+ if (latest !== void 0 && !latest.retireOnCommit) {
+ if (latest.draftPromise !== void 0)
+ return latest.draftPromise;
+ if (latest.target?.kind === "fork-copy") {
+ latest.draftPromise = this.#track(this.#acquireForkCopy(latest, definition, latest.target));
+ return latest.draftPromise;
+ }
+ }
+ const seed = definition.family === true ? copyJson(args[resolved.nextArgument]) : void 0;
+ const docEntry = {
+ addressId: resolved.id,
+ address: resolved.address,
+ definition,
+ retireOnCommit: false
+ };
+ this.#documents.push(docEntry);
+ this.#latestDocumentByAddress.set(docEntry.addressId, docEntry);
+ docEntry.draftPromise = this.#track(this.#acquire(docEntry, seed, latest?.retireOnCommit === true));
+ return docEntry.draftPromise;
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ }
+ retireDoc(token, ...args) {
+ try {
+ this.#assertOpen();
+ const definition = token.definition;
+ const resolved = resolveAddress(definition, args);
+ const latest = this.#latestDocumentByAddress.get(resolved.id);
+ if (latest?.retireOnCommit)
+ return Promise.resolve();
+ if (latest?.target?.kind === "fork-copy") {
+ checkRecordScope(definition, latest.target.record);
+ latest.retireOnCommit = true;
+ return Promise.resolve();
+ }
+ if (latest?.draftPromise !== void 0) {
+ latest.retireOnCommit = true;
+ return this.#track(latest.draftPromise.then(() => void 0));
+ }
+ const entry = {
+ addressId: resolved.id,
+ address: resolved.address,
+ definition,
+ retireOnCommit: true
+ };
+ this.#documents.push(entry);
+ this.#latestDocumentByAddress.set(entry.addressId, entry);
+ return this.#track(this.#findRetirement(entry));
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ }
+ async #acquire(entry, seed, skipLoad) {
+ const definition = entry.definition;
+ const loaded = skipLoad ? void 0 : await this.#host.load(definition, entry.addressId, entry.address, this.#context);
+ this.#assertOpen();
+ if (loaded !== void 0) {
+ checkRecordScope(definition, loaded.record);
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
+ entry.target = { kind: "loaded", document: loaded };
+ entry.change = loaded.tracker.beginChange();
+ return entry.change.state;
+ }
+ const scope = entry.address.scope;
+ if (scope.kind === "conversation")
+ await this.#requireConversation(scope.conversationId);
+ if (scope.kind === "task") {
+ const task = await this.#currentTask(scope.taskId);
+ if (task === void 0)
+ throw new Error(`Task ${scope.taskId} does not exist`);
+ if (task.state.status === "terminal")
+ throw new Error(`Task ${scope.taskId} is terminal`);
+ }
+ this.#assertOpen();
+ const value = copyJson(definition.family === true ? definition.initial(seed) : definition.initial());
+ const id = await this.#host.storage.mintId();
+ this.#assertOpen();
+ const tracker = track(value);
+ entry.target = {
+ kind: "created",
+ record: documentCreate(definition, entry.address, id),
+ version: definition.version,
+ tracker
+ };
+ entry.change = tracker.beginChange();
+ return entry.change.state;
+ }
+ async #acquireForkCopy(entry, definition, target) {
+ const stored = await this.#host.storage.document(target.source.id, target.source.at, this.#context);
+ this.#assertOpen();
+ if (stored === void 0) {
+ throw new Error(`Fork source document ${target.source.id} cannot be read`);
+ }
+ if (stored.record.scope.kind !== "conversation" || stored.record.kind !== target.record.kind || stored.record.key !== target.record.key || stored.record.history !== target.record.history || stored.record.fork !== target.record.fork) {
+ throw new Error(`Fork source document ${target.source.id} does not match the copied record`);
+ }
+ const value = materializeDocumentValue(definition, target.record, stored.version, stored.value);
+ const tracker = track(value);
+ entry.definition = definition;
+ entry.target = { kind: "created", record: target.record, version: definition.version, tracker };
+ entry.change = tracker.beginChange();
+ return entry.change.state;
+ }
+ async #findRetirement(entry) {
+ const record = this.#host.cached(entry.addressId)?.record ?? await this.#host.storage.findDocument(entry.address, "current", this.#context);
+ this.#assertOpen();
+ if (record === void 0)
+ return;
+ checkRecordScope(entry.definition, record);
+ entry.target = { kind: "retire-only", record };
+ }
+ // ─── Settlement ─────────────────────────────────────────────────────────
+ /** Seal after callback failure: abort every change and observe every pending operation. */
+ async settleFailure() {
+ this.#sealed = true;
+ this.#abortChanges();
+ await Promise.allSettled(this.#pendingOperations);
+ }
+ /**
+ * Seal after callback success, prepare every open change, and assemble the atomic batch.
+ * Any failure aborts every change before Storage admission.
+ */
+ async settleSuccess() {
+ this.#sealed = true;
+ if (this.#pendingOperations.size > 0) {
+ this.#abortChanges();
+ await Promise.allSettled(this.#pendingOperations);
+ throw new Error("Session commit callback settled before its pending Tx operations");
+ }
+ try {
+ for (const document of this.#documents) {
+ if (document.change !== void 0)
+ document.prepared = document.change.prepare();
+ }
+ return await this.#assemble();
+ } catch (error) {
+ this.#abortChanges();
+ throw error;
+ }
+ }
+ /** Abort every prepared change after Storage failure or when no write is required. */
+ discard() {
+ this.#abortChanges();
+ }
+ /** Adopt every prepared change by pointer swap after Storage success and describe the publication. */
+ adopt(seq) {
+ const publications = [];
+ for (const plan of this.#plans) {
+ const committed = "createdAt" in plan.record;
+ let record = committed ? plan.record : { ...plan.record, createdAt: seq };
+ if (plan.retire)
+ record = { ...record, retiredAt: seq };
+ const change = plan.change;
+ if (change !== void 0) {
+ const { tracker, prepared, loaded, version } = change;
+ if (loaded === void 0 ? !plan.retire : prepared.ops.length > 0)
+ tracker.adopt(prepared);
+ else
+ prepared.abort();
+ if (loaded !== void 0) {
+ if (loaded.storedVersion < version)
+ loaded.storedVersion = version;
+ if (plan.content?.type === "document.change") {
+ if (plan.content.content.kind === "base")
+ loaded.deltasSinceBase = 0;
+ else
+ loaded.deltasSinceBase++;
+ }
+ } else if (!plan.retire) {
+ this.#host.install({
+ addressId: plan.addressId,
+ record,
+ storedVersion: version,
+ valueVersion: version,
+ deltasSinceBase: 0,
+ tracker
+ });
+ }
+ }
+ const conversationId = plan.conversationId;
+ if (plan.retire) {
+ if (committed)
+ this.#host.evict(plan.addressId, record.id);
+ const retired = { version: void 0, value: null, ops: EMPTY_OPERATIONS };
+ publications.push({ type: "document", record, conversationId, ...retired });
+ } else if (plan.content?.type === "document.copy") {
+ publications.push({
+ type: "document.copy",
+ record,
+ conversationId,
+ source: plan.content.source
+ });
+ } else if (change !== void 0 && publishes(plan)) {
+ const ops = change.loaded === void 0 ? EMPTY_OPERATIONS : change.prepared.ops;
+ publications.push({
+ type: "document",
+ record,
+ conversationId,
+ version: change.version,
+ value: change.prepared.value,
+ ops
+ });
+ }
+ }
+ return publications;
+ }
+ async #assemble() {
+ const storage = this.#host.storage;
+ const plans = this.#plans;
+ for (const document of this.#documents) {
+ const plan = planDocument(document);
+ if (plan !== void 0)
+ plans.push(plan);
+ }
+ this.#rejectForkSourceWrites(plans);
+ await this.#validateOwners();
+ for (const [id, task] of this.#tasksById) {
+ if (task.write?.kind !== "replace")
+ continue;
+ const committed = await this.#committedTask(id);
+ if (committed === void 0)
+ throw new Error(`Task ${id} does not exist`);
+ if (committed.state.status === "terminal")
+ throw new Error(`Task ${id} is already terminal`);
+ if (committed.conversationId !== task.write.record.conversationId) {
+ throw new Error(`Task ${id} cannot change conversations`);
+ }
+ }
+ const terminalTaskIds = /* @__PURE__ */ new Set();
+ for (const task of this.#tasksById.values()) {
+ if (task.write?.record.state.status === "terminal")
+ terminalTaskIds.add(task.write.record.id);
+ }
+ if (terminalTaskIds.size > 0) {
+ const retiring = /* @__PURE__ */ new Set();
+ for (const plan of plans) {
+ const scope = plan.record.scope;
+ if (scope.kind !== "task" || !terminalTaskIds.has(scope.taskId))
+ continue;
+ plan.retire = true;
+ retiring.add(plan.record.id);
+ }
+ for (const taskId of terminalTaskIds) {
+ if (this.#tasksById.get(taskId)?.write?.kind === "create")
+ continue;
+ let cursor;
+ do {
+ const page2 = await storage.scanDocuments({ scope: { kind: "task", taskId }, at: "current" }, INTERNAL_SCAN_PAGE_SIZE, cursor, this.#context);
+ for (const record of page2.items) {
+ if (retiring.has(record.id))
+ continue;
+ plans.push({ addressId: addressId(record), record, retire: true });
+ retiring.add(record.id);
+ }
+ cursor = page2.next;
+ } while (cursor !== void 0);
+ }
+ }
+ for (const plan of plans) {
+ if (!publishes(plan))
+ continue;
+ const scope = plan.record.scope;
+ if (scope.kind === "conversation")
+ plan.conversationId = scope.conversationId;
+ if (scope.kind !== "task")
+ continue;
+ const task = this.#taskEntry(scope.taskId);
+ if (task.publicationConversationId === void 0) {
+ const current = await this.#currentTask(scope.taskId);
+ if (current !== void 0)
+ task.publicationConversationId = current.conversationId;
+ }
+ plan.conversationId = task.publicationConversationId;
+ }
+ for (const { id, change } of this.#submissionChanges) {
+ const current = this.#submissions.get(id) ?? await storage.submission(id, this.#context);
+ if (current === void 0)
+ throw new Error(`Submission ${id} does not exist`);
+ const next = applySubmissionChange(current, change);
+ if (next !== current)
+ this.#submissions.set(id, next);
+ }
+ const writes = this.#writes;
+ for (const value of this.#submissions.values())
+ writes.push({ type: "submission", value });
+ for (const task of this.#tasksById.values()) {
+ if (task.write !== void 0)
+ writes.push({ type: "task", value: task.write.record });
+ }
+ for (const plan of plans) {
+ const change = plan.change;
+ if (plan.content?.type === "document.change" && plan.content.content.kind === "delta" && change?.loaded) {
+ const { prepared, version } = change;
+ const info = { deltasSinceBase: change.loaded.deltasSinceBase };
+ if (change.definition?.checkpointWhen?.(prepared.value, prepared.ops, info)) {
+ plan.content = { ...plan.content, content: { version, kind: "base", value: prepared.value } };
+ }
+ }
+ if (plan.content !== void 0)
+ writes.push(plan.content);
+ if (plan.retire)
+ writes.push({ type: "document.retire", id: plan.record.id });
+ }
+ return writes;
+ }
+ // ─── Helpers ────────────────────────────────────────────────────────────
+ /**
+ * New owned work needs a live owner, judged on the owner's final candidate: not `completing`, terminal, or
+ * abort-marked. A task therefore cannot create owned work in the commit that finishes it (spec §5.5).
+ */
+ async #validateOwners() {
+ const owners = [];
+ for (const write of this.#writes) {
+ if (write.type !== "conversation" || write.value.owner === void 0)
+ continue;
+ owners.push({ what: "Conversation owner task", taskId: write.value.owner.taskId });
+ }
+ for (const task of this.#tasksById.values()) {
+ const record = task.write?.kind === "create" ? task.write.record : void 0;
+ if (record?.owner !== void 0)
+ owners.push({ what: "Task owner", taskId: record.owner });
+ }
+ for (const { what, taskId } of owners) {
+ const task = await this.#currentTask(taskId);
+ if (task === void 0)
+ throw new Error(`${what} ${taskId} does not exist`);
+ if (task.state.status === "terminal" || task.state.status === "completing") {
+ throw new Error(`${what} ${taskId} is ${task.state.status}`);
+ }
+ if (task.abortRequested)
+ throw new Error(`${what} ${taskId} is abort-marked`);
+ }
+ }
+ #rejectForkSourceWrites(plans) {
+ for (const plan of plans) {
+ if (plan.content === void 0 && !plan.retire)
+ continue;
+ const record = plan.record;
+ if (this.#forkSourceDocumentIds.has(record.id)) {
+ throw new Error(`Cannot change fork source document ${record.id} in the fork transaction`);
+ }
+ const scope = plan.record.scope;
+ if (scope.kind === "conversation" && this.#forkSourceConversationIds.has(scope.conversationId) && record.scope.kind === "conversation" && record.fork === "current") {
+ throw new Error(`Cannot fork conversation ${scope.conversationId} while changing its current-policy documents`);
+ }
+ }
+ }
+ #abortChanges() {
+ for (const document of this.#documents)
+ document.change?.abort();
+ }
+ #assertOpen() {
+ if (this.#sealed)
+ throw new Error("Transaction has settled");
+ }
+ #assertTaskDocumentsOpen(resolved) {
+ const scope = resolved.address.scope;
+ if (scope.kind === "task" && this.#tasksById.get(scope.taskId)?.write?.record.state.status === "terminal") {
+ throw new Error(`Task ${scope.taskId} is terminal`);
+ }
+ }
+ /** Register an operation so callback settlement can reject and drain it. */
+ #track(operation) {
+ this.#pendingOperations.add(operation);
+ const settle2 = () => {
+ this.#pendingOperations.delete(operation);
+ };
+ operation.then(settle2, settle2);
+ return operation;
+ }
+ #read(method, read2) {
+ try {
+ this.#assertOpen();
+ if (this.#hasTableWrite)
+ throw new ReadAfterWrite(method);
+ return this.#track(read2());
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ }
+ #write(write) {
+ try {
+ this.#assertOpen();
+ this.#hasTableWrite = true;
+ return this.#track(write());
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ }
+ async #requireConversation(id) {
+ if (this.#createdConversationIds.has(id))
+ return;
+ if (await this.#host.storage.conversation(id, this.#context) === void 0) {
+ throw new Error(`Conversation ${id} does not exist`);
+ }
+ }
+ #taskEntry(id) {
+ let task = this.#tasksById.get(id);
+ if (task === void 0) {
+ task = {};
+ this.#tasksById.set(id, task);
+ }
+ return task;
+ }
+ /** Latest candidate task record, falling back to committed state; not a caller table read. */
+ async #currentTask(id) {
+ return this.#tasksById.get(id)?.write?.record ?? await this.#committedTask(id);
+ }
+ #committedTask(id) {
+ const task = this.#taskEntry(id);
+ task.committedRead ??= this.#host.storage.task(id, this.#context);
+ return task.committedRead;
+ }
+};
+function planDocument(document) {
+ const target = document.target;
+ if (target === void 0)
+ return void 0;
+ const plan = { addressId: document.addressId, retire: document.retireOnCommit };
+ switch (target.kind) {
+ case "created": {
+ const prepared = document.prepared;
+ const { record, version, tracker } = target;
+ const content = { version, kind: "base", value: prepared.value };
+ return {
+ ...plan,
+ record,
+ content: { type: "document.create", record, content },
+ change: { tracker, prepared, version }
+ };
+ }
+ case "fork-copy":
+ return {
+ ...plan,
+ record: target.record,
+ content: { type: "document.copy", record: target.record, source: target.source }
+ };
+ case "retire-only":
+ return { ...plan, record: target.record };
+ case "loaded": {
+ const loaded = target.document;
+ const definition = document.definition;
+ const prepared = document.prepared;
+ const version = definition.version;
+ const id = loaded.record.id;
+ const content = loaded.storedVersion < version ? { type: "document.change", id, content: { version, kind: "base", value: prepared.value } } : prepared.ops.length > 0 ? { type: "document.change", id, content: { version, kind: "delta", ops: prepared.ops } } : void 0;
+ const change = {
+ tracker: loaded.tracker,
+ prepared,
+ version,
+ loaded,
+ definition
+ };
+ return { ...plan, record: loaded.record, change, ...content === void 0 ? {} : { content } };
+ }
+ }
+}
+function publishes(plan) {
+ return plan.retire || plan.change?.loaded === void 0 || plan.content !== void 0;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/session/session.js
+var SessionImpl = class {
+ #storage;
+ #documents = /* @__PURE__ */ new Map();
+ #commitListeners = /* @__PURE__ */ new Set();
+ #closeListeners = /* @__PURE__ */ new Set();
+ #host;
+ #tail = Promise.resolve();
+ #closing;
+ #poison;
+ constructor(storage) {
+ this.#storage = storage;
+ this.#host = {
+ storage,
+ cached: (id) => this.#documents.get(id),
+ load: (definition, addressId2, address, context) => this.#loadDocument(definition, addressId2, address, context),
+ install: (document) => {
+ this.#documents.set(document.addressId, document);
+ },
+ evict: (id, recordId) => {
+ if (this.#documents.get(id)?.record.id === recordId)
+ this.#documents.delete(id);
+ },
+ conversationCreated: (tx, record) => this.conversationCreated(tx, record)
+ };
+ }
+ commit(change, context) {
+ return this.commitWith(change, context);
+ }
+ /**
+ * Internal commit exposing the concrete transaction and its internal operations, such as the reserved-ID root
+ * bootstrap and task replacement. `scope` sets the default `tx.createTask()` conversation and the task attributed to
+ * appended entries.
+ */
+ commitWith(change, context, scope) {
+ try {
+ this.#assertUsable();
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ return this.#enqueue(() => this.#runCommit(change, context, scope));
+ }
+ /** Internal: run a read-only job on the mutation line so multi-read derivations observe one committed state. */
+ readOnLine(job) {
+ try {
+ this.#assertUsable();
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ return this.#enqueue(async () => {
+ this.#assertHealthy();
+ return job();
+ });
+ }
+ /**
+ * Internal: a conversation document's current incarnation and value, for a job already running on the line (see
+ * `readOnLine()`). Absent documents are `undefined`.
+ */
+ async conversationDocumentOnLine(token, conversationId, context) {
+ const definition = token.definition;
+ const resolved = resolveAddress(definition, [conversationId, context]);
+ const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);
+ if (loaded === void 0)
+ return void 0;
+ checkRecordScope(definition, loaded.record);
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
+ return { record: loaded.record, version: loaded.valueVersion, value: loaded.tracker.value };
+ }
+ async snapshot(token, ...args) {
+ this.#assertUsable();
+ const definition = token.definition;
+ const resolved = resolveAddress(definition, args);
+ const context = args[resolved.nextArgument];
+ const cached = this.#documents.get(resolved.id);
+ const loaded = cached?.valueVersion === definition.version ? cached : await this.#enqueue(async () => {
+ this.#assertHealthy();
+ return this.#loadDocument(definition, resolved.id, resolved.address, context);
+ });
+ if (loaded === void 0)
+ return void 0;
+ checkRecordScope(definition, loaded.record);
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
+ return loaded.tracker.value;
+ }
+ documentState(token, ...args) {
+ try {
+ this.#assertUsable();
+ const definition = token.definition;
+ const resolved = resolveAddress(definition, args);
+ const context = args[resolved.nextArgument];
+ return this.#enqueue(async () => {
+ this.#assertHealthy();
+ const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);
+ if (loaded === void 0)
+ return void 0;
+ const { observer: source, detach } = this.#attachDocument(definition, loaded, (value, release) => new CommittedStateSource(value, release));
+ try {
+ return replicatedState(source);
+ } catch (error) {
+ detach();
+ throw error;
+ }
+ });
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ }
+ async watchDoc(token, ...args) {
+ this.#assertUsable();
+ const definition = token.definition;
+ const resolved = resolveAddress(definition, args);
+ const context = args[resolved.nextArgument];
+ const signal = context.abortSignal;
+ let cancelled = signal?.aborted ?? false;
+ const markCancelled = () => {
+ cancelled = true;
+ };
+ signal?.addEventListener("abort", markCancelled, { once: true });
+ try {
+ const watch = await this.#enqueue(async () => {
+ this.#assertHealthy();
+ if (cancelled)
+ throw cancellationError(signal);
+ const loaded = await this.#loadDocument(definition, resolved.id, resolved.address, context);
+ if (cancelled)
+ throw cancellationError(signal);
+ if (loaded === void 0)
+ return void 0;
+ return this.#attachDocument(definition, loaded, (value, release) => new CommittedWatch(value, release)).observer;
+ });
+ if (watch === void 0)
+ return void 0;
+ if (cancelled) {
+ watch.cancel();
+ throw cancellationError(signal);
+ }
+ if (signal !== void 0)
+ watch.observeCancellation(signal);
+ return watch;
+ } finally {
+ signal?.removeEventListener("abort", markCancelled);
+ }
+ }
+ async snapshotAsOf(token, ...args) {
+ this.#assertUsable();
+ const definition = token.definition;
+ const resolved = resolveAddress(definition, args);
+ if (resolved.address.scope.kind !== "conversation") {
+ throw new TypeError("Session.snapshotAsOf() requires a conversation document");
+ }
+ const conversationId = resolved.address.scope.conversationId;
+ const atValue = args[resolved.nextArgument];
+ if (typeof atValue !== "number" || !Number.isSafeInteger(atValue)) {
+ throw new TypeError("Session.snapshotAsOf() requires an entry ID");
+ }
+ const at = idFromNumber(atValue);
+ const context = args[resolved.nextArgument + 1];
+ return this.#enqueue(async () => {
+ this.#assertHealthy();
+ const storedEntry = await this.#storage.entry(conversationId, at, context);
+ if (storedEntry === void 0) {
+ throw new Error(`Entry ${at} is not visible from conversation ${conversationId}`);
+ }
+ const address = {
+ ...resolved.address,
+ scope: { kind: "conversation", conversationId: storedEntry.entry.conversationId }
+ };
+ const record = await this.#storage.findDocument(address, storedEntry.commitSeq, context);
+ if (record === void 0)
+ return void 0;
+ const stored = await this.#storage.document(record.id, storedEntry.commitSeq, context);
+ if (stored === void 0) {
+ throw new Error(`Historical document ${record.id} (${record.kind}) cannot be read`);
+ }
+ return materializeDocument(definition, stored);
+ });
+ }
+ close(context) {
+ if (this.#closing === void 0) {
+ const cleanup = withoutAbortSignal(context);
+ this.#closing = Promise.resolve().then(() => this.beforeClose()).then(() => this.#enqueue(async () => {
+ this.#commitListeners.clear();
+ this.#documents.clear();
+ await this.#storage.close(cleanup);
+ }));
+ const listeners = [...this.#closeListeners];
+ this.#closeListeners.clear();
+ for (const listener of listeners)
+ listener();
+ }
+ return awaitWithContext(this.#closing, context);
+ }
+ /**
+ * Runs inside every transaction that creates or forks a conversation, after the conversation record is staged. A
+ * plain Session stages nothing; a Harness stages its built-in documents.
+ */
+ conversationCreated(_tx, _record) {
+ return Promise.resolve();
+ }
+ /** Runs after close seals admission and before the line closes Storage; must not reject. */
+ beforeClose() {
+ return Promise.resolve();
+ }
+ /** Register a synchronous post-adoption listener. It must not throw, block, or call Session operations. */
+ subscribeCommits(listener) {
+ this.#assertUsable();
+ this.#commitListeners.add(listener);
+ return () => this.#commitListeners.delete(listener);
+ }
+ /** Register a listener called synchronously when close begins. It must not throw, block, or call Session operations. */
+ subscribeClose(listener) {
+ this.#assertUsable();
+ this.#closeListeners.add(listener);
+ return () => this.#closeListeners.delete(listener);
+ }
+ /** Drop every loaded tracker on the mutation line; later access cold-loads from Storage. */
+ unloadDocuments() {
+ return this.#enqueue(async () => {
+ this.#documents.clear();
+ });
+ }
+ async #runCommit(change, context, scope) {
+ this.#assertHealthy();
+ context.abortSignal?.throwIfAborted();
+ const tx = new Transaction(this.#host, context, scope);
+ let result;
+ try {
+ result = await change(tx);
+ } catch (error) {
+ await tx.settleFailure();
+ throw error;
+ }
+ const writes = await tx.settleSuccess();
+ if (writes.length === 0) {
+ tx.discard();
+ return result;
+ }
+ let seq;
+ try {
+ seq = await this.#storage.commit(writes, withoutAbortSignal(context));
+ } catch (error) {
+ tx.discard();
+ if (!(error instanceof StorageRejected))
+ this.#poison = { error };
+ throw error;
+ }
+ let documents;
+ try {
+ documents = tx.adopt(seq);
+ } catch (error) {
+ this.#poison = { error };
+ throw error;
+ }
+ this.#publish(seq, writes, documents, context);
+ return result;
+ }
+ #publish(seq, writes, documents, context) {
+ if (this.#commitListeners.size === 0)
+ return;
+ const changes = [];
+ for (const write of writes) {
+ switch (write.type) {
+ case "conversation":
+ case "entry":
+ case "task":
+ case "submission":
+ changes.push(write);
+ }
+ }
+ for (const document of documents)
+ changes.push(document);
+ const publication = { seq, changes };
+ for (const listener of [...this.#commitListeners])
+ listener(publication, context);
+ }
+ /**
+ * Attach an observer to one committed incarnation: check the definition, then forward this incarnation's committed
+ * changes and close. `detach` removes both subscriptions.
+ */
+ #attachDocument(definition, loaded, create) {
+ checkRecordScope(definition, loaded.record);
+ checkRecordVersion(definition, loaded.record, loaded.storedVersion);
+ let unsubscribeCommit = () => {
+ };
+ let unsubscribeClose = () => {
+ };
+ const detach = () => {
+ unsubscribeCommit();
+ unsubscribeClose();
+ };
+ const observer = create(loaded.tracker.value, detach);
+ const observed = { version: loaded.valueVersion };
+ unsubscribeCommit = this.subscribeCommits((publication, context) => {
+ for (const change of publication.changes) {
+ if (change.type !== "document" || change.record.id !== loaded.record.id)
+ continue;
+ const frameContext = observer instanceof CommittedStateSource ? withoutAbortSignal(context) : context;
+ const ops = observedOperations(observed, change);
+ if (ops.length === 0)
+ continue;
+ observer.advance(change.value, ops, frameContext);
+ }
+ });
+ unsubscribeClose = this.subscribeClose(() => observer.closeSession());
+ return { observer, detach };
+ }
+ async #loadDocument(definition, addressId2, address, context) {
+ const cached = this.#documents.get(addressId2);
+ if (cached?.valueVersion === definition.version)
+ return cached;
+ if (cached !== void 0)
+ this.#documents.delete(addressId2);
+ const record = await this.#storage.findDocument(address, "current", context);
+ if (record === void 0)
+ return void 0;
+ const stored = await this.#storage.document(record.id, "current", context);
+ if (stored === void 0)
+ throw new Error(`Current document ${record.id} (${record.kind}) cannot be read`);
+ const value = materializeDocument(definition, stored);
+ const loaded = {
+ addressId: addressId2,
+ record: stored.record,
+ storedVersion: stored.version,
+ valueVersion: definition.version,
+ deltasSinceBase: stored.deltasSinceBase,
+ tracker: track(value)
+ };
+ this.#documents.set(addressId2, loaded);
+ return loaded;
+ }
+ #enqueue(job) {
+ const run2 = this.#tail.then(job);
+ this.#tail = run2.then(() => void 0, () => void 0);
+ return run2;
+ }
+ #assertUsable() {
+ if (this.#closing !== void 0)
+ throw new Error("Session is closed");
+ this.#assertHealthy();
+ }
+ #assertHealthy() {
+ if (this.#poison !== void 0) {
+ throw new Error("Session is poisoned by a failed commit after storage admission; reopen it", {
+ cause: this.#poison.error
+ });
+ }
+ }
+};
+function observedOperations(observed, change) {
+ if (change.value === null)
+ return RETIREMENT_OPERATIONS;
+ if (change.version === observed.version)
+ return change.ops;
+ observed.version = change.version;
+ return [["r", change.value]];
+}
+function cancellationError(signal) {
+ return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/registry.js
+var SECTION_KEY = /^[a-z][a-z0-9_-]*$/;
+var BUILTIN_TASKS = [GenerationTask, ToolTask, CompactionTask];
+var RegistryState = class {
+ #extensions;
+ #byName;
+ #tasks;
+ constructor(extensions) {
+ this.#extensions = extensions;
+ this.#byName = new Map(extensions.map((extension) => [extension.name, extension]));
+ const tasks = /* @__PURE__ */ new Map();
+ for (const task of BUILTIN_TASKS)
+ tasks.set(task.definition.name, task);
+ for (const extension of extensions) {
+ for (const task of extension.tasks ?? []) {
+ const name = task.definition.name;
+ if (tasks.has(name))
+ throw new Error(`Task ${name} of extension ${extension.name} is already installed`);
+ tasks.set(name, task);
+ }
+ }
+ this.#tasks = tasks;
+ }
+ installed() {
+ return this.#extensions;
+ }
+ extension(name) {
+ return this.#byName.get(name);
+ }
+ tools() {
+ return this.#extensions.flatMap((extension) => (extension.tools ?? []).map((tool) => ({ extension, tool })));
+ }
+ sections() {
+ return this.#extensions.flatMap((extension) => (extension.sections ?? []).map((section2) => ({ extension, section: section2 })));
+ }
+ tasks() {
+ return [...this.#tasks.values()];
+ }
+ task(name) {
+ return this.#tasks.get(name);
+ }
+};
+var RegistryImpl = class {
+ #current = new RegistryState([]);
+ #listeners = /* @__PURE__ */ new Set();
+ snapshot() {
+ return this.#current;
+ }
+ subscribe(listener) {
+ this.#listeners.add(listener);
+ return () => this.#listeners.delete(listener);
+ }
+ install(extension) {
+ validateExtension(extension);
+ const current = this.#current.installed();
+ const index3 = current.findIndex((installed) => installed.name === extension.name);
+ const next = index3 < 0 ? [...current, extension] : current.map((installed, at) => at === index3 ? extension : installed);
+ this.#publish(next);
+ }
+ uninstall(extension) {
+ const current = this.#current.installed();
+ if (!current.some((installed) => installed.name === extension.name))
+ return;
+ this.#publish(current.filter((installed) => installed.name !== extension.name));
+ }
+ /** Build and validate the next state, which throws on a task name collision, then publish it synchronously. */
+ #publish(extensions) {
+ this.#current = new RegistryState(extensions);
+ for (const listener of [...this.#listeners])
+ listener();
+ }
+};
+function validateExtension(extension) {
+ const tools = /* @__PURE__ */ new Set();
+ for (const tool of extension.tools ?? []) {
+ if (tools.has(tool.name))
+ throw new Error(`Extension ${extension.name} has two tools named ${tool.name}`);
+ tools.add(tool.name);
+ }
+ const sections = /* @__PURE__ */ new Set();
+ for (const { key } of extension.sections ?? []) {
+ if (!SECTION_KEY.test(key))
+ throw new TypeError(`Section key ${JSON.stringify(key)} must match ${SECTION_KEY}`);
+ if (key === INSTRUCTIONS_KEY)
+ throw new Error(`Section key ${key} is reserved for the agent's instructions`);
+ if (sections.has(key))
+ throw new Error(`Extension ${extension.name} has two sections with key ${key}`);
+ sections.add(key);
+ }
+}
+function createRegistry() {
+ return new RegistryImpl();
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/scheduler.js
+var SCAN_PAGE_SIZE3 = 256;
+var MAX_TIMER_DELAY = 2147483647;
+var LIVE_STATUSES = ["pending", "running", "waiting", "completing"];
+var TaskScheduler = class {
+ #session;
+ #storage;
+ #registry;
+ #models;
+ #agent;
+ #settings;
+ #env;
+ #now;
+ #report;
+ #settleOutcome;
+ #withdrawInputs;
+ #conversation;
+ #context;
+ #live = /* @__PURE__ */ new Map();
+ #invocations = /* @__PURE__ */ new Map();
+ #taskWaiters = new Waiters();
+ /** Idle waiters by conversation; `undefined` waits for the whole Harness. */
+ #idleWaiters = new Waiters();
+ /** Definition whose migration failed per task; retried only once the registry resolves another definition. */
+ #failedMigrations = /* @__PURE__ */ new Map();
+ /** Owner task of each loaded conversation, `null` when ownerless. */
+ #edges = /* @__PURE__ */ new Map();
+ /** Tasks that own a loaded conversation; their nodes stay in `#settled` once terminal. */
+ #conversationOwners = /* @__PURE__ */ new Set();
+ /** Ownership fields of terminal tasks that walks pass through. */
+ #settled = /* @__PURE__ */ new Map();
+ /**
+ * `failFast` waiters the next reconcile checks for a failed task in `on`: at open, when they start waiting, and when
+ * one of their tasks fails.
+ */
+ #failFastChecks = /* @__PURE__ */ new Set();
+ #reconcileScheduled = false;
+ #cascadePending = false;
+ #unsubscribeRegistry = () => {
+ };
+ #enabled = false;
+ #closing = false;
+ #dirty = false;
+ #draining = false;
+ constructor(options) {
+ this.#session = options.session;
+ this.#storage = options.storage;
+ this.#registry = options.registry;
+ this.#models = options.models;
+ this.#agent = options.agent;
+ this.#settings = options.settings;
+ this.#env = options.env;
+ this.#now = options.now;
+ this.#report = options.report;
+ this.#settleOutcome = options.settleOutcome;
+ this.#withdrawInputs = options.withdrawInputs;
+ this.#conversation = options.conversation;
+ this.#context = options.context;
+ }
+ /** Load live tasks and change surviving `running` tasks back to `pending`. Dispatches nothing. */
+ async open(context) {
+ this.#session.subscribeCommits((publication) => this.#observe(publication));
+ this.#session.subscribeClose(() => this.#seal());
+ this.#unsubscribeRegistry = this.#registry.subscribe(() => this.#kick());
+ await this.#session.commitWith(async (tx) => {
+ const scans = [];
+ for (const status of LIVE_STATUSES) {
+ scans.push(await scanAll((cursor) => tx.scanTasks({ status }, SCAN_PAGE_SIZE3, cursor)));
+ }
+ for (const records of scans) {
+ for (const record of records) {
+ this.#live.set(record.id, record);
+ if (record.state.status === "running") {
+ tx.setTask(withState(record, { status: "pending", checkpoint: record.state.checkpoint }));
+ }
+ if (record.state.status === "waiting" && record.state.policy === "failFast") {
+ this.#failFastChecks.add(record.id);
+ }
+ }
+ }
+ }, context);
+ this.#cascadePending = true;
+ this.#scheduleReconcile();
+ }
+ /** Enable scheduling. Idempotent; the kick does nothing once closing. */
+ resume() {
+ this.#enabled = true;
+ this.#kick();
+ }
+ /** Wait for every invocation signalled by `#seal()`. Writes nothing. */
+ async join() {
+ await Promise.allSettled([...this.#invocations.values()].map((invocation) => invocation.done));
+ }
+ /**
+ * Commit the abort mark, or settle a task that no registered definition can take as `orphaned` when nothing it owns
+ * is live, then join the run invocation seen on the line; the commit listener signalled it. The abort invocation
+ * starts once the task's ordinary owned work is gone. A `completing` task is only marked.
+ */
+ async abort(id, context) {
+ const marked = await this.#session.commitWith(async (tx) => {
+ const current = await tx.task(id);
+ if (current === void 0)
+ throw new Error(`Task ${id} does not exist`);
+ if (current.state.status === "terminal")
+ return { result: "terminal" };
+ const invocation = this.#invocations.get(id);
+ if (invocation === void 0 && current.state.status !== "completing") {
+ await this.#loadScopes(false);
+ if (!this.#ownedLive().has(id)) {
+ const resolution = this.#resolve(current, this.#registry.snapshot());
+ if (resolution.kind === "blocked") {
+ await this.#terminate(tx, current, { status: "orphaned", reason: resolution.reason });
+ return { result: "marked" };
+ }
+ }
+ }
+ if (!current.abortRequested)
+ tx.setTask({ ...current, abortRequested: true });
+ return { result: "marked", run: invocation?.mode === "run" ? invocation : void 0 };
+ }, context);
+ if (marked.run !== void 0)
+ await awaitWithContext(marked.run.done, context);
+ return marked.result;
+ }
+ async waitForTask(id, context) {
+ const found = await this.#session.readOnLine(async () => {
+ if (this.#closing)
+ throw closedError();
+ if (this.#live.has(id))
+ return { promise: this.#taskWaiters.add(id, context) };
+ const record = await this.#storage.task(id, context);
+ if (record === void 0)
+ throw new Error(`Task ${id} does not exist`);
+ return { promise: Promise.resolve(record) };
+ });
+ return found.promise;
+ }
+ /**
+ * Resolve when ordinary traversal from the conversation, or from every ownerless conversation, reaches no live
+ * non-background task.
+ */
+ waitForIdle(conversationId, context) {
+ if (this.#closing)
+ return Promise.reject(closedError());
+ if (this.#idle(conversationId))
+ return Promise.resolve();
+ this.#scheduleReconcile();
+ return this.#idleWaiters.add(conversationId, context);
+ }
+ /**
+ * `Conversation.abort()`: in one commit, withdraw the queued inputs and mark every live non-background task that
+ * ordinary traversal from the conversation reaches; resolves once the scope is idle. With `background`, traversal
+ * crosses background boundaries, and the wait also covers every task it reached.
+ */
+ async abortConversation(conversationId, background, context) {
+ const reached = await this.#session.commitWith(async (tx) => {
+ const queued2 = await this.#loadScopes(true);
+ const scope = { conversation: conversationId };
+ const reached2 = [];
+ for (const record of this.#live.values()) {
+ if (record.background && !background)
+ continue;
+ if (this.#inScope(parentOf(record), scope, background) !== true)
+ continue;
+ reached2.push(record.id);
+ if (!record.abortRequested)
+ tx.setTask({ ...record, abortRequested: true });
+ }
+ for (const id of queued2) {
+ if (this.#inScope({ conversation: id }, scope, background) === true)
+ await this.#withdrawInputs(tx, id);
+ }
+ return reached2;
+ }, context);
+ if (background)
+ for (const id of reached)
+ await this.waitForTask(id, context);
+ await this.waitForIdle(conversationId, context);
+ }
+ // ─── Scheduling ────────────────────────────────────────────────────────
+ #observe(publication) {
+ const updated = [];
+ const failed = [];
+ let changed = false;
+ for (const change of publication.changes) {
+ if (change.type !== "task")
+ continue;
+ changed = true;
+ const record = change.value;
+ const previous = this.#live.get(record.id);
+ if (failedOutcome(record) && (previous === void 0 || !failedOutcome(previous)))
+ failed.push(record.id);
+ if (record.state.status === "terminal") {
+ this.#live.delete(record.id);
+ this.#failedMigrations.delete(record.id);
+ this.#failFastChecks.delete(record.id);
+ if (this.#conversationOwners.has(record.id))
+ this.#settled.set(record.id, nodeOf(record));
+ this.#taskWaiters.resolve(record.id, record);
+ this.#scheduleReconcile();
+ continue;
+ }
+ if (record.abortRequested && previous?.abortRequested !== true) {
+ this.#cascadePending = true;
+ const invocation = this.#invocations.get(record.id);
+ if (invocation?.mode === "run")
+ invocation.controller.abort();
+ }
+ const status = record.state.status;
+ if (status === "completing" && previous?.state.status !== "completing") {
+ if (cancellationIntent(record))
+ this.#cascadePending = true;
+ this.#scheduleReconcile();
+ }
+ if (status === "waiting" && record.state.policy === "failFast" && previous?.state.status !== "waiting") {
+ this.#failFastChecks.add(record.id);
+ this.#scheduleReconcile();
+ }
+ this.#live.set(record.id, record);
+ updated.push(record);
+ }
+ for (const id of failed) {
+ for (const record of this.#live.values()) {
+ const state3 = record.state;
+ if (state3.status === "waiting" && state3.policy === "failFast" && state3.on.includes(id)) {
+ this.#failFastChecks.add(record.id);
+ this.#scheduleReconcile();
+ }
+ }
+ }
+ for (const change of publication.changes) {
+ if (change.type === "conversation" && !this.#edges.has(change.value.id)) {
+ this.#setEdge(change.value.id, change.value.owner?.taskId ?? null);
+ }
+ }
+ for (const change of publication.changes) {
+ if (change.type !== "submission" || change.value.status !== "queued" || change.value.type !== "input")
+ continue;
+ const up = { conversation: change.value.conversationId };
+ if (!this.#chainKnown(up) || this.#belowCancelled(up))
+ this.#cascadePending = true;
+ }
+ for (const record of updated) {
+ if (!this.#chainKnown(parentOf(record)))
+ this.#scheduleReconcile();
+ else if (!record.background && !record.abortRequested && this.#belowCancelled(parentOf(record))) {
+ this.#cascadePending = true;
+ }
+ }
+ if (this.#cascadePending)
+ this.#scheduleReconcile();
+ if (!changed)
+ return;
+ this.#resolveIdleWaiters();
+ this.#kick();
+ }
+ #resolveIdleWaiters() {
+ for (const conversationId of this.#idleWaiters.keys()) {
+ if (this.#idle(conversationId))
+ this.#idleWaiters.resolve(conversationId);
+ }
+ }
+ // ─── Ownership ───────────────────────────────────────────────────────────
+ #scheduleReconcile() {
+ if (this.#reconcileScheduled || this.#closing)
+ return;
+ this.#reconcileScheduled = true;
+ queueMicrotask(() => void this.#reconcile());
+ }
+ /**
+ * One commit that applies what committed records imply: abort marks below live owners with cancellation intent
+ * (spec §5.4), `failFast` marks (spec §5.5), withdrawn queued inputs below cancelled owners, and the final terminal
+ * record of every `completing` task whose ordinary owned work is gone. The durable records are the intent, so this
+ * also repairs whatever a crash left unapplied. Resolves idle waiters that the loaded edges decide.
+ */
+ async #reconcile() {
+ this.#reconcileScheduled = false;
+ const cascade = this.#cascadePending;
+ this.#cascadePending = false;
+ const checks = [...this.#failFastChecks];
+ this.#failFastChecks.clear();
+ try {
+ await this.#session.commitWith(async (tx) => {
+ if (this.#closing)
+ return;
+ const queued2 = await this.#loadScopes(cascade);
+ const marked = /* @__PURE__ */ new Set();
+ const mark = (record) => {
+ if (record.abortRequested || marked.has(record.id))
+ return;
+ marked.add(record.id);
+ tx.setTask({ ...record, abortRequested: true });
+ };
+ for (const record of this.#live.values()) {
+ if (!record.background && this.#belowCancelled(parentOf(record)))
+ mark(record);
+ }
+ for (const id of checks) {
+ const waiter = this.#live.get(id);
+ if (waiter?.state.status !== "waiting" || !await this.#anyFailed(waiter.state.on))
+ continue;
+ for (const member of waiter.state.on) {
+ const record = this.#live.get(member);
+ if (record !== void 0 && !failedOutcome(record))
+ mark(record);
+ }
+ }
+ for (const id of queued2)
+ if (this.#belowCancelled({ conversation: id }))
+ await this.#withdrawInputs(tx, id);
+ await this.#finalize(tx);
+ }, this.#context);
+ } catch (error) {
+ this.#cascadePending = true;
+ for (const id of checks)
+ this.#failFastChecks.add(id);
+ if (!this.#closing)
+ this.#report(error);
+ }
+ this.#resolveIdleWaiters();
+ }
+ /** Whether any of `ids` holds or ended with an outcome other than `completed`. */
+ async #anyFailed(ids) {
+ for (const id of ids) {
+ const record = this.#live.get(id) ?? await this.#storage.task(id, this.#context);
+ if (record !== void 0 && failedOutcome(record))
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Write the terminal record of every `completing` task without live ordinary owned work. Finalizing one can free its
+ * owner, so this repeats over the commit's candidates until nothing changes. A held scheduler outcome gets its
+ * Harness cleanup here.
+ */
+ async #finalize(tx) {
+ for (; ; ) {
+ const overlay = overlayOf(tx);
+ const owned = this.#ownedLive(overlay);
+ const done = [...this.#liveRecords(overlay)].filter((record) => record.state.status === "completing" && !owned.has(record.id));
+ if (done.length === 0)
+ return;
+ for (const record of done) {
+ const outcome = record.state.outcome;
+ tx.setTask(withState(record, { status: "terminal", outcome }));
+ if (outcome.status === "faulted" || outcome.status === "orphaned") {
+ await this.#settleOutcome(tx, record, outcome);
+ }
+ }
+ }
+ }
+ /**
+ * Load the owner chains of every live task and, with `queued`, of every conversation with queued submissions, on the
+ * Session line; returns the latter. Reads committed Storage directly, so it may run inside a commit callback.
+ */
+ async #loadScopes(queued2) {
+ for (const record of [...this.#live.values()]) {
+ if (!this.#chainKnown(parentOf(record)))
+ await this.#loadChain(parentOf(record));
+ }
+ if (!queued2)
+ return [];
+ const submissions = await scanAll((cursor) => this.#storage.scanSubmissions({ status: "queued" }, SCAN_PAGE_SIZE3, cursor, this.#context));
+ const conversations = [...new Set(submissions.map((submission) => submission.conversationId))];
+ for (const id of conversations)
+ await this.#loadChain({ conversation: id });
+ return conversations;
+ }
+ /** Load the owner edges and task nodes from `start` up to its ownerless root. */
+ async #loadChain(start, overlay) {
+ let at = start;
+ while (at !== void 0) {
+ if ("task" in at) {
+ let node = this.#node(at.task, overlay);
+ if (node === void 0) {
+ const record = await this.#storage.task(at.task, this.#context);
+ if (record === void 0)
+ return;
+ node = nodeOf(record);
+ if (record.state.status === "terminal")
+ this.#settled.set(record.id, node);
+ }
+ at = parentOf(node);
+ } else {
+ let edge = this.#edge(at.conversation, overlay);
+ if (edge === void 0) {
+ const record = await this.#storage.conversation(at.conversation, this.#context);
+ edge = record?.owner?.taskId ?? null;
+ this.#setEdge(at.conversation, edge);
+ }
+ at = edge === null ? void 0 : { task: edge };
+ }
+ }
+ }
+ #setEdge(conversationId, owner) {
+ this.#edges.set(conversationId, owner);
+ if (owner !== null)
+ this.#conversationOwners.add(owner);
+ }
+ /** Owner task of a conversation, `null` when ownerless, `undefined` while not loaded. */
+ #edge(id, overlay) {
+ return overlay?.edges.has(id) === true ? overlay.edges.get(id) : this.#edges.get(id);
+ }
+ #node(id, overlay) {
+ return overlay?.tasks.get(id) ?? this.#live.get(id) ?? this.#settled.get(id);
+ }
+ /** Walk up from `start`: owner tasks and conversations, ending at an ownerless root or an edge not loaded yet. */
+ *#above(start, overlay) {
+ let at = start;
+ while (at !== void 0) {
+ if ("task" in at) {
+ const node = this.#node(at.task, overlay);
+ if (node === void 0) {
+ yield { unknown: true };
+ return;
+ }
+ yield { task: at.task, node };
+ at = parentOf(node);
+ } else {
+ yield { conversation: at.conversation };
+ const edge = this.#edge(at.conversation, overlay);
+ if (edge === void 0) {
+ yield { unknown: true };
+ return;
+ }
+ at = edge === null ? void 0 : { task: edge };
+ }
+ }
+ }
+ /** Whether every owner above `start` is loaded. */
+ #chainKnown(start, overlay) {
+ for (const step of this.#above(start, overlay))
+ if ("unknown" in step)
+ return false;
+ return true;
+ }
+ /** Live records, with the overlay's candidates replacing committed ones; terminal candidates are gone. */
+ *#liveRecords(overlay) {
+ for (const record of this.#live.values()) {
+ const candidate = overlay?.tasks.get(record.id) ?? record;
+ if (candidate.state.status !== "terminal")
+ yield candidate;
+ }
+ if (overlay === void 0)
+ return;
+ for (const record of overlay.tasks.values()) {
+ if (!this.#live.has(record.id) && record.state.status !== "terminal")
+ yield record;
+ }
+ }
+ /**
+ * Every task with live ordinary owned work (spec §5.5), mapped to that work: each live non-background task counts for
+ * every owner task above it up to and including the first background one. Owner chains must be loaded.
+ */
+ #ownedLive(overlay) {
+ const owned = /* @__PURE__ */ new Map();
+ for (const record of this.#liveRecords(overlay)) {
+ if (record.background)
+ continue;
+ for (const step of this.#above(parentOf(record), overlay)) {
+ if ("unknown" in step)
+ break;
+ if (!("task" in step))
+ continue;
+ const below = owned.get(step.task);
+ if (below === void 0)
+ owned.set(step.task, [record.id]);
+ else
+ below.push(record.id);
+ if (step.node.background)
+ break;
+ }
+ }
+ return owned;
+ }
+ /**
+ * Whether ordinary traversal from `scope` reaches `start`: walking up reaches the scope's conversation, or an
+ * ownerless one for `roots`, without crossing a background owner, unless `crossBackground`. `undefined` while an
+ * edge is not loaded.
+ */
+ #inScope(start, scope, crossBackground = false) {
+ for (const step of this.#above(start)) {
+ if ("unknown" in step)
+ return void 0;
+ if ("conversation" in step) {
+ if ("conversation" in scope && step.conversation === scope.conversation)
+ return true;
+ } else if (step.node.background && !crossBackground) {
+ return false;
+ }
+ }
+ return "roots" in scope;
+ }
+ /**
+ * Whether a live owner's cancellation intent reaches `start`: walking up finds an owner with intent before a
+ * background owner without it. Terminal owners never cascade (spec §5.4).
+ */
+ #belowCancelled(start) {
+ for (const step of this.#above(start)) {
+ if ("unknown" in step)
+ return false;
+ if (!("task" in step))
+ continue;
+ const live = this.#live.get(step.task);
+ if (live !== void 0 && cancellationIntent(live))
+ return true;
+ if (step.node.background)
+ return false;
+ }
+ return false;
+ }
+ /** Close listener: runs synchronously once admission is sealed, before `join()`. */
+ #seal() {
+ this.#closing = true;
+ this.#unsubscribeRegistry();
+ const error = closedError();
+ this.#taskWaiters.rejectAll(error);
+ this.#idleWaiters.rejectAll(error);
+ for (const invocation of this.#invocations.values())
+ invocation.controller.abort();
+ }
+ #kick() {
+ this.#dirty = true;
+ if (this.#draining || !this.#enabled || this.#closing)
+ return;
+ this.#draining = true;
+ queueMicrotask(() => void this.#drain());
+ }
+ async #drain() {
+ try {
+ while (this.#dirty && this.#enabled && !this.#closing) {
+ this.#dirty = false;
+ for (const reservation of await this.#reserve())
+ this.#start(reservation);
+ }
+ } catch (error) {
+ if (!this.#closing)
+ this.#report(error);
+ } finally {
+ this.#draining = false;
+ if (this.#dirty)
+ this.#kick();
+ }
+ }
+ /** Reserve every eligible task in one commit; orphan abort-marked tasks no definition can take. */
+ async #reserve() {
+ const reservations = [];
+ try {
+ await this.#session.commitWith(async (tx) => {
+ if (!this.#enabled || this.#closing)
+ return;
+ await this.#loadScopes(false);
+ const owned = this.#ownedLive();
+ let snapshot;
+ for (const record of [...this.#live.values()]) {
+ if (this.#invocations.has(record.id) || this.#waitingOn(record, owned).length > 0)
+ continue;
+ if (record.state.status === "completing")
+ continue;
+ const runnable = record;
+ const mode = record.abortRequested ? "abort" : "run";
+ snapshot ??= this.#registry.snapshot();
+ const resolution = this.#resolve(runnable, snapshot);
+ if (resolution.kind === "blocked") {
+ if (mode === "abort") {
+ await this.#terminate(tx, record, { status: "orphaned", reason: resolution.reason });
+ }
+ continue;
+ }
+ if (resolution.record !== runnable || record.state.status !== "running") {
+ tx.setTask(withState(resolution.record, {
+ status: "running",
+ checkpoint: resolution.record.state.checkpoint
+ }));
+ }
+ const invocation = this.#createInvocation(record, mode);
+ reservations.push({ invocation, task: resolution.task, snapshot });
+ }
+ }, this.#context);
+ } catch (error) {
+ for (const { invocation } of reservations) {
+ this.#invocations.delete(invocation.taskId);
+ invocation.finish();
+ }
+ throw error;
+ }
+ return reservations;
+ }
+ /**
+ * Live tasks a task waits for before its next invocation: its live ordinary owned work when abort-marked, since
+ * abort runs bottom-up, otherwise the live part of the `on` of a wait.
+ */
+ #waitingOn(record, owned) {
+ if (record.abortRequested)
+ return owned.get(record.id) ?? [];
+ if (record.state.status !== "waiting")
+ return [];
+ return record.state.on.filter((id) => this.#live.has(id));
+ }
+ /** Resolve the record's definition by kind, migrating an older stored version. */
+ #resolve(record, snapshot) {
+ const fit = this.#fit(record, snapshot.task(record.kind));
+ if ("reason" in fit)
+ return { kind: "blocked", reason: fit.reason };
+ if (!fit.migrates)
+ return { kind: "ready", task: fit.task, record };
+ const definition = erased(fit.task);
+ try {
+ if (definition.migrate === void 0)
+ throw missingMigration(record, definition);
+ const migrated = definition.migrate(record.input, record.state.checkpoint, record.version);
+ const state3 = { ...record.state, checkpoint: copyJson(migrated.checkpoint) };
+ const migratedRecord = { ...record, version: definition.version, input: copyJson(migrated.input), state: state3 };
+ return { kind: "ready", task: fit.task, record: migratedRecord };
+ } catch (error) {
+ this.#failedMigrations.set(record.id, { task: fit.task, error });
+ this.#report(error);
+ return { kind: "blocked", reason: "migration_failed" };
+ }
+ }
+ #fit(record, task) {
+ if (task === void 0)
+ return { reason: "missing_task" };
+ const version = task.definition.version;
+ if (version === record.version)
+ return { task, migrates: false };
+ if (version < record.version)
+ return { reason: "task_too_old" };
+ const failed = this.#failedMigrations.get(record.id);
+ if (failed?.task === task)
+ return { reason: "migration_failed", error: failed.error };
+ return { task, migrates: true };
+ }
+ /**
+ * Scheduling state and every live task with its derived state, read on the Session line. Runs no task code: a
+ * pending migration shows as `ready` with `migrates`, and only a migration the scheduler already tried, or one that
+ * cannot exist, shows as failed.
+ */
+ async inspect(snapshot) {
+ await this.#loadScopes(false);
+ const owned = this.#ownedLive();
+ const tasks = [];
+ for (const record of this.#live.values()) {
+ tasks.push({ record, state: this.#inspectTask(record, snapshot, owned) });
+ }
+ const scheduling = this.#closing ? "closing" : this.#enabled ? "running" : "paused";
+ return { scheduling, tasks };
+ }
+ #inspectTask(record, snapshot, owned) {
+ if (this.#invocations.has(record.id))
+ return { kind: "running" };
+ if (record.state.status === "completing")
+ return { kind: "completing" };
+ const on = this.#waitingOn(record, owned);
+ if (on.length > 0)
+ return { kind: "waiting", on };
+ const fit = this.#fit(record, snapshot.task(record.kind));
+ if ("reason" in fit)
+ return { kind: "blocked", ...fit };
+ if (fit.migrates && fit.task.definition.migrate === void 0) {
+ return { kind: "blocked", reason: "migration_failed", error: missingMigration(record, erased(fit.task)) };
+ }
+ return { kind: "ready", migrates: fit.migrates };
+ }
+ #createInvocation(record, mode) {
+ const controller = new AbortController();
+ const { promise: done, resolve: finish } = Promise.withResolvers();
+ const invocation = {
+ taskId: record.id,
+ conversationId: record.conversationId,
+ mode,
+ controller,
+ context: withAbortSignal(controller.signal, this.#context),
+ watches: /* @__PURE__ */ new Set(),
+ ended: false,
+ done,
+ finish: () => finish()
+ };
+ this.#invocations.set(record.id, invocation);
+ return invocation;
+ }
+ #start(reservation) {
+ const invocation = reservation.invocation;
+ void (async () => {
+ try {
+ if (invocation.mode === "run")
+ await this.#run(reservation);
+ else
+ await this.#runAbort(reservation);
+ } catch (error) {
+ this.#report(error);
+ } finally {
+ this.#end(invocation);
+ invocation.finish();
+ this.#kick();
+ }
+ })();
+ }
+ /** Run phase handlers, each preceded by a step that decides on the line whether the invocation continues. */
+ async #run(reservation) {
+ const invocation = reservation.invocation;
+ const state3 = { task: reservation.task, snapshot: reservation.snapshot, reported: void 0 };
+ const phase = { snapshot: () => state3.snapshot, task: () => state3.task, agent: void 0 };
+ const runtime = this.#runtime(invocation, phase);
+ let previous;
+ for (; ; ) {
+ const current = await this.#step(invocation, (tx, current2) => this.#decide(tx, current2, previous, state3));
+ if (current === void 0 || this.#closing)
+ return;
+ const checkpoint = current.state.checkpoint;
+ phase.agent = void 0;
+ try {
+ await erased(state3.task).phases[checkpoint.phase](current, runtime, invocation.context);
+ previous = { checkpoint };
+ } catch (error) {
+ previous = { checkpoint, failure: { error } };
+ }
+ }
+ }
+ /**
+ * Precedence rules for a run invocation, on the line. Rules 1 (terminal, `completing`, or `waiting`) and 2 (closing)
+ * are applied by `#step`. Returns whether the invocation continues with the next phase.
+ */
+ #decide(tx, current, previous, state3) {
+ if (current.abortRequested)
+ return false;
+ if (previous === void 0)
+ return true;
+ if (previous.failure !== void 0)
+ return { fault: previous.failure.error };
+ if (jsonEqual(current.state.checkpoint, previous.checkpoint)) {
+ const message = `Task ${current.kind} phase ${previous.checkpoint.phase} returned without durable progress`;
+ return { fault: new Error(message) };
+ }
+ state3.snapshot = this.#registry.snapshot();
+ const next = state3.snapshot.task(current.kind);
+ if (next !== state3.task) {
+ if (next !== void 0 && canReserve(next, current)) {
+ tx.setTask(withState(current, { status: "pending", checkpoint: current.state.checkpoint }));
+ return false;
+ }
+ if (state3.reported === void 0 || state3.reported.task !== next) {
+ state3.reported = { task: next };
+ const cause = next === void 0 ? "missing_task" : "incompatible_task";
+ this.#report(new Error(`Task ${current.id} keeps running under its old ${current.kind} definition`, { cause }));
+ }
+ }
+ return true;
+ }
+ /** Run the abort handler once; rules 1, 2, and 4 apply, and returning without an outcome faults. */
+ async #runAbort(reservation) {
+ const invocation = reservation.invocation;
+ const current = this.#live.get(invocation.taskId);
+ if (current === void 0 || this.#closing)
+ return;
+ let failure;
+ try {
+ const phase = { snapshot: () => reservation.snapshot, task: () => reservation.task, agent: void 0 };
+ const runtime = this.#runtime(invocation, phase);
+ await erased(reservation.task).abort(current, runtime, invocation.context);
+ } catch (error) {
+ failure = { error };
+ }
+ const message = `Abort handler of task ${invocation.taskId} returned without a terminal outcome`;
+ await this.#step(invocation, () => ({ fault: failure?.error ?? new Error(message) }));
+ }
+ /**
+ * One synchronous decision on the Session line. A task that is no longer running (rule 1: terminal, `completing`, or
+ * `waiting`) or a closing Harness (rule 2) ends the invocation without a write; otherwise `decide` may stage a write
+ * and returns whether the invocation continues. Ending happens inside the callback, before a fault's Harness
+ * cleanup. A rejected step, such as admission after close, also ends the invocation.
+ */
+ async #step(invocation, decide) {
+ try {
+ return await this.#session.commitWith(async (tx) => {
+ const found = this.#live.get(invocation.taskId);
+ const current = found?.state.status === "running" ? found : void 0;
+ const decision = current !== void 0 && !this.#closing ? decide(tx, current) : false;
+ if (decision === true)
+ return current;
+ this.#end(invocation);
+ if (decision !== false) {
+ const message = decision.fault instanceof Error ? decision.fault.message : String(decision.fault);
+ await this.#terminate(tx, current, { status: "faulted", error: { message } });
+ }
+ return void 0;
+ }, this.#context);
+ } catch (error) {
+ this.#end(invocation);
+ if (!this.#closing)
+ this.#report(error);
+ return void 0;
+ }
+ }
+ /**
+ * Write an outcome the scheduler decided. While the task's ordinary owned work is live it holds as `completing` and
+ * its Harness cleanup waits for the final commit (spec §5.5, rule 4); otherwise it is terminal with its cleanup.
+ */
+ async #terminate(tx, record, outcome) {
+ await this.#loadScopes(false);
+ if (this.#ownedLive(overlayOf(tx)).has(record.id)) {
+ tx.setTask(withState(record, { status: "completing", outcome }));
+ return;
+ }
+ tx.setTask(withState(record, { status: "terminal", outcome }));
+ await this.#settleOutcome(tx, record, outcome);
+ }
+ /**
+ * Replace a running task's state with what it committed. A terminal state holds as `completing` while ordinary owned
+ * work is live, judged on the commit's candidates, so work the same commit creates below the task counts. A wait is
+ * validated first.
+ */
+ async #commitState(tx, invocation, current, next) {
+ if (next.status === "waiting")
+ await this.#validateWait(tx, invocation, current, next.on, next.policy);
+ if (next.status === "terminal") {
+ const overlay = overlayOf(tx);
+ await this.#loadScopes(false);
+ for (const record of overlay.tasks.values())
+ await this.#loadChain(parentOf(record), overlay);
+ if (this.#ownedLive(overlay).has(current.id)) {
+ tx.setTask(withState(current, { status: "completing", outcome: next.outcome }));
+ return;
+ }
+ }
+ tx.setTask(withState(current, next));
+ }
+ /**
+ * A wait names existing tasks other than the waiter and its owners, which could never finish first; `failFast` only
+ * tasks the waiter owns. An abort handler cannot wait.
+ */
+ async #validateWait(tx, invocation, current, on, policy) {
+ if (invocation.mode === "abort")
+ throw new Error(`Abort handler of task ${current.id} cannot wait`);
+ const overlay = overlayOf(tx);
+ await this.#loadChain(parentOf(current));
+ const owners = /* @__PURE__ */ new Set();
+ for (const step of this.#above(parentOf(current)))
+ if ("task" in step)
+ owners.add(step.task);
+ for (const id of on) {
+ if (id === current.id || owners.has(id)) {
+ throw new Error(`Task ${current.id} cannot wait on itself or its owner ${id}`);
+ }
+ const member = overlay.tasks.get(id) ?? this.#live.get(id) ?? await this.#storage.task(id, this.#context);
+ if (member === void 0)
+ throw new Error(`Task ${id} does not exist`);
+ if (policy === "failFast" && member.owner !== current.id) {
+ throw new Error(`Task ${current.id} can wait failFast only on tasks it owns; ${id} is not one`);
+ }
+ }
+ }
+ /** End an invocation: its runtime operations reject from now on, its signal aborts, its watches stop, and its task is free. */
+ #end(invocation) {
+ if (invocation.ended)
+ return;
+ invocation.ended = true;
+ if (this.#invocations.get(invocation.taskId) === invocation)
+ this.#invocations.delete(invocation.taskId);
+ for (const watch of invocation.watches)
+ void watch.stop();
+ invocation.controller.abort(endedError(invocation));
+ }
+ /** No live non-background task in the scope; a task whose owner edges are not loaded yet counts as inside. */
+ #idle(conversationId) {
+ const scope = conversationId === void 0 ? { roots: true } : { conversation: conversationId };
+ for (const record of this.#live.values()) {
+ if (!record.background && this.#inScope(parentOf(record), scope) !== false)
+ return false;
+ }
+ return true;
+ }
+ // ─── Invocation runtime ──────────────────────────────────────────────────
+ #runtime(invocation, phase) {
+ const agent = () => {
+ if (invocation.ended)
+ return Promise.reject(endedError(invocation));
+ if (phase.agent === void 0) {
+ phase.agent = this.#agent(invocation.conversationId, phase.snapshot(), invocation.context);
+ phase.agent.catch(() => {
+ });
+ }
+ return phase.agent;
+ };
+ const hooks = {
+ each: async (name, invoke) => {
+ for (const handlers of agentHooks(await agent(), phase.task().definition.name)) {
+ const handler = handlers[name];
+ if (typeof handler !== "function")
+ continue;
+ try {
+ await invoke(handler.bind(handlers));
+ } catch (error) {
+ if (invocation.controller.signal.aborted)
+ throw error;
+ this.#report(error);
+ }
+ }
+ }
+ };
+ const settings2 = this.#settings;
+ return {
+ taskId: invocation.taskId,
+ conversationId: invocation.conversationId,
+ signal: invocation.controller.signal,
+ models: this.#models,
+ agent: (context) => invocation.ended ? Promise.reject(endedError(invocation)) : awaitWithContext(agent(), context),
+ get settings() {
+ return settings2();
+ },
+ env: (context) => this.#read(invocation, () => this.#env(invocation.conversationId, context)),
+ hooks,
+ get registry() {
+ return phase.snapshot();
+ },
+ commit: (change, context) => this.#gated(invocation, async (tx, current) => {
+ const next = await change(tx, current);
+ if (next !== void 0)
+ await this.#commitState(tx, invocation, current, next);
+ }, context),
+ memo: ((name, ...rest) => {
+ if (rest.length === 1) {
+ return this.#read(invocation, async () => memoOf(this.#live.get(invocation.taskId), name));
+ }
+ const candidate = rest[0];
+ return this.#gated(invocation, (tx, current) => {
+ const winner = memoOf(current, name);
+ if (winner !== void 0)
+ return winner;
+ tx.setTask({ ...current, memos: { ...current.memos, [name]: candidate } });
+ return candidate;
+ }, rest[1]);
+ }),
+ sleep: (until, context) => this.#sleep(invocation, until, context),
+ watchDoc: ((...args) => this.#watchDoc(invocation, args)),
+ snapshot: ((...args) => this.#read(invocation, () => sessionMethod(this.#session, "snapshot")(...args))),
+ snapshotAsOf: ((...args) => this.#read(invocation, () => sessionMethod(this.#session, "snapshotAsOf")(...args))),
+ getTask: ((id, context) => this.#read(invocation, () => this.#session.readOnLine(() => this.#storage.task(id, context)))),
+ waitForTask: ((id, context) => this.#read(invocation, () => this.waitForTask(id, withAbortSignal(invocation.controller.signal, context)))),
+ outcomes: ((ids, context) => this.#read(invocation, () => this.#session.readOnLine(async () => {
+ const outcomes = [];
+ for (const id of ids) {
+ const state3 = (await this.#storage.task(id, context))?.state;
+ if (state3?.status !== "terminal")
+ throw new Error(`Task ${id} is not terminal`);
+ outcomes.push(state3.outcome);
+ }
+ return outcomes;
+ }))),
+ conversation: (id, context) => this.#read(invocation, () => this.#conversation(id, {
+ signal: invocation.controller.signal,
+ check: () => {
+ if (invocation.ended)
+ throw endedError(invocation);
+ }
+ }, context)),
+ entry: ((...args) => {
+ const [token, id, context] = args.length === 2 ? [void 0, args[0], args[1]] : [args[0], args[1], args[2]];
+ return this.#read(invocation, async () => {
+ const found = await this.#session.readOnLine(() => this.#storage.entry(invocation.conversationId, id, context));
+ const entry = found?.entry;
+ return token === void 0 || entry?.kind === token.kind ? entry : void 0;
+ });
+ }),
+ context: (conversationId, context, at) => this.#read(invocation, () => readContext(this.#session, this.#storage, conversationId, context, at)),
+ now: () => {
+ if (invocation.ended)
+ throw endedError(invocation);
+ return this.#now();
+ },
+ report: (error) => {
+ if (invocation.ended)
+ throw endedError(invocation);
+ this.#report(error);
+ }
+ };
+ }
+ /** Run a committed-state read unless the invocation has ended. */
+ async #read(invocation, read2) {
+ if (invocation.ended)
+ throw endedError(invocation);
+ return read2();
+ }
+ /** Commit after rereading the task on the line and gating the invocation. */
+ #gated(invocation, change, context) {
+ if (invocation.ended)
+ return Promise.reject(endedError(invocation));
+ return this.#session.commitWith(async (tx) => {
+ if (invocation.ended)
+ throw endedError(invocation);
+ if (this.#closing)
+ throw closedError();
+ const found = this.#live.get(invocation.taskId);
+ if (found === void 0)
+ throw new Error(`Task ${invocation.taskId} is terminal`);
+ if (found.state.status !== "running")
+ throw new Error(`Task ${invocation.taskId} is ${found.state.status}`);
+ const current = found;
+ if (invocation.mode === "run" && current.abortRequested) {
+ throw new Error(`Task ${invocation.taskId} has a durable abort mark`);
+ }
+ return change(tx, current);
+ }, context, { conversationId: invocation.conversationId, taskId: invocation.taskId });
+ }
+ /** Wait until the Harness clock reaches `until`, rechecking it after every timer. */
+ async #sleep(invocation, until, context) {
+ if (invocation.ended)
+ throw endedError(invocation);
+ const signals = [invocation.controller.signal];
+ if (context.abortSignal !== void 0)
+ signals.push(context.abortSignal);
+ const signal = AbortSignal.any(signals);
+ for (; ; ) {
+ signal.throwIfAborted();
+ const remaining = until - this.#now();
+ if (remaining <= 0)
+ return;
+ await delay(Math.min(remaining, MAX_TIMER_DELAY), signal);
+ }
+ }
+ async #watchDoc(invocation, args) {
+ if (invocation.ended)
+ throw endedError(invocation);
+ const watch = await sessionMethod(this.#session, "watchDoc")(...args);
+ if (watch === void 0)
+ return void 0;
+ if (invocation.ended) {
+ void watch.stop();
+ throw endedError(invocation);
+ }
+ invocation.watches.add(watch);
+ void watch.closed.then(() => invocation.watches.delete(watch));
+ return watch;
+ }
+};
+function cancellationIntent(record) {
+ return record.state.status !== "terminal" && (record.abortRequested || failedOutcome(record));
+}
+function failedOutcome(record) {
+ const state3 = record.state;
+ return (state3.status === "completing" || state3.status === "terminal") && state3.outcome.status !== "completed";
+}
+function parentOf(node) {
+ return node.owner !== void 0 ? { task: node.owner } : { conversation: node.conversationId };
+}
+function nodeOf(record) {
+ return {
+ conversationId: record.conversationId,
+ ...record.owner === void 0 ? {} : { owner: record.owner },
+ background: record.background
+ };
+}
+function overlayOf(tx) {
+ const tasks = new Map(tx.stagedTasks().map((record) => [record.id, record]));
+ const edges = new Map(tx.stagedConversations().map((record) => [record.id, record.owner?.taskId ?? null]));
+ return { tasks, edges };
+}
+function memoOf(record, name) {
+ const memos = record?.memos;
+ return memos !== void 0 && Object.hasOwn(memos, name) ? memos[name] : void 0;
+}
+function sessionMethod(session, name) {
+ return session[name].bind(session);
+}
+function missingMigration(record, definition) {
+ return new Error(`Task ${record.kind} version ${definition.version} has no migration from ${record.version}`);
+}
+function erased(task) {
+ return task.definition;
+}
+function endedError(invocation) {
+ return new Error(`Task ${invocation.taskId} invocation has ended`);
+}
+function withState(record, state3) {
+ if (state3.status !== "terminal" && state3.status !== "completing")
+ return { ...record, state: state3 };
+ const { memos: _memos, ...rest } = record;
+ return { ...rest, state: state3 };
+}
+function canReserve(task, record) {
+ const definition = task.definition;
+ return definition.version === record.version || definition.version > record.version && definition.migrate !== void 0;
+}
+function delay(ms, signal) {
+ return new Promise((resolve3, reject) => {
+ const onAbort = () => {
+ clearTimeout(timer);
+ reject(signal.reason);
+ };
+ const timer = setTimeout(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve3();
+ }, ms);
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+}
+function jsonEqual(left, right) {
+ if (left === right)
+ return true;
+ if (typeof left !== "object" || typeof right !== "object" || left === null || right === null)
+ return false;
+ if (Array.isArray(left) || Array.isArray(right)) {
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length)
+ return false;
+ return left.every((value, index3) => jsonEqual(value, right[index3]));
+ }
+ const keys = Object.keys(left);
+ if (keys.length !== Object.keys(right).length)
+ return false;
+ return keys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key]));
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/task-graph.js
+var LIVE_STATUSES2 = ["pending", "running", "waiting", "completing"];
+var SCAN_PAGE_SIZE4 = 256;
+var TaskGraphView = class {
+ #session;
+ #storage;
+ #mount;
+ #closed = false;
+ constructor(session, storage) {
+ this.#session = session;
+ this.#storage = storage;
+ session.subscribeCommits((publication, context) => {
+ if (this.#mount !== void 0)
+ advance2(this.#mount, publication, context);
+ });
+ session.subscribeClose(() => {
+ this.#closed = true;
+ for (const observer of [...this.#mount?.observers ?? []])
+ observer.closeSession();
+ this.#mount = void 0;
+ });
+ }
+ /** A disposable read-only Chord state of the graph. */
+ async state(context) {
+ const { observer, detach } = await this.#attach((value, release) => new CommittedStateSource(value, release), context);
+ try {
+ return replicatedState(observer);
+ } catch (error) {
+ detach();
+ throw error;
+ }
+ }
+ /** A serialized exact-frame watch of the graph; cancelling `context` stops it. */
+ async watch(context) {
+ const { observer } = await this.#attach((value, release) => new CommittedWatch(value, release), context);
+ const signal = context.abortSignal;
+ if (signal?.aborted) {
+ observer.cancel();
+ throw signal.reason;
+ }
+ if (signal !== void 0)
+ observer.observeCancellation(signal);
+ return observer;
+ }
+ /** Register an observer created from the current revision, atomically on the Session line. */
+ #attach(create, context) {
+ return this.#session.readOnLine(async () => {
+ const mount = this.#mount ?? { value: await this.#build(context), observers: /* @__PURE__ */ new Set() };
+ const detach = () => {
+ mount.observers.delete(observer);
+ if (mount.observers.size === 0 && this.#mount === mount)
+ this.#mount = void 0;
+ };
+ const observer = create(mount.value, detach);
+ if (this.#closed)
+ throw closedError();
+ context.abortSignal?.throwIfAborted();
+ this.#mount = mount;
+ mount.observers.add(observer);
+ return { observer, detach };
+ });
+ }
+ async #build(context) {
+ const tasks = {};
+ const records = [];
+ for (const status of LIVE_STATUSES2) {
+ records.push(...await scanAll((cursor) => this.#storage.scanTasks({ status }, SCAN_PAGE_SIZE4, cursor, context)));
+ }
+ records.sort((a, b) => a.id - b.id);
+ for (const record of records) {
+ const owned = await scanAll((cursor) => this.#storage.scanConversations({ ownerTaskId: record.id }, SCAN_PAGE_SIZE4, cursor, context));
+ const conversations = owned.map((conversation) => conversation.id).sort((a, b) => a - b);
+ tasks[String(record.id)] = nodeOf2(record, conversations);
+ }
+ return { tasks };
+ }
+};
+function advance2(mount, publication, context) {
+ const ops = [];
+ const changed = /* @__PURE__ */ new Map();
+ const node = (key) => changed.has(key) ? changed.get(key) : mount.value.tasks[key];
+ for (const change of publication.changes) {
+ if (change.type !== "task")
+ continue;
+ const record = change.value;
+ const key = String(record.id);
+ const previous = node(key);
+ if (record.state.status === "terminal") {
+ if (previous === void 0)
+ continue;
+ ops.push(["d", ["tasks", key]]);
+ changed.set(key, void 0);
+ continue;
+ }
+ const next = nodeOf2(record, previous?.conversations ?? []);
+ if (previous !== void 0 && JSON.stringify(next) === JSON.stringify(previous))
+ continue;
+ ops.push(["s", ["tasks", key], next]);
+ changed.set(key, next);
+ }
+ const created = /* @__PURE__ */ new Map();
+ for (const change of publication.changes) {
+ if (change.type !== "conversation" || change.value.owner === void 0)
+ continue;
+ const key = String(change.value.owner.taskId);
+ if (node(key) !== void 0)
+ created.set(key, [...created.get(key) ?? [], change.value.id]);
+ }
+ for (const [key, ids] of created) {
+ const conversations = [...node(key).conversations, ...ids].sort((a, b) => a - b);
+ ops.push(["s", ["tasks", key, "conversations"], conversations]);
+ }
+ if (ops.length === 0)
+ return;
+ mount.value = applyImmutable(mount.value, ops);
+ const frameContext = withoutAbortSignal(context);
+ for (const observer of [...mount.observers])
+ observer.advance(mount.value, ops, frameContext);
+}
+function nodeOf2(record, conversations) {
+ return {
+ id: record.id,
+ kind: record.kind,
+ conversationId: record.conversationId,
+ ...record.owner === void 0 ? {} : { owner: record.owner },
+ background: record.background,
+ abortRequested: record.abortRequested,
+ state: stateOf(record),
+ conversations
+ };
+}
+function stateOf(record) {
+ const state3 = record.state;
+ switch (state3.status) {
+ case "pending":
+ case "running":
+ return { status: state3.status, phase: phaseOf(state3.checkpoint) };
+ case "waiting":
+ return { status: "waiting", phase: phaseOf(state3.checkpoint), on: [...state3.on], policy: state3.policy };
+ // Terminal records never reach here: they leave the graph.
+ case "completing":
+ case "terminal":
+ return { status: "completing", outcome: state3.outcome.status };
+ }
+}
+function phaseOf(checkpoint) {
+ return checkpoint.phase;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/harness/harness.js
+var SCAN_PAGE_SIZE5 = 256;
+var ConversationImpl = class {
+ id;
+ #host;
+ constructor(id, host) {
+ this.id = id;
+ this.#host = host;
+ }
+ agent(context) {
+ return this.#host.harness.resolveAgent(this.id, void 0, context);
+ }
+ configure(change, context) {
+ return this.#host.harness.commitWith((tx) => configure(tx, this.id, change), context);
+ }
+ submit(submission, context) {
+ return this.#host.submissions.submit(this.id, submission, context);
+ }
+ compact(instructions2, context) {
+ this.#host.tasks.resume();
+ const input = { reason: "manual", ...instructions2 === void 0 ? {} : { instructions: instructions2 } };
+ return this.#host.harness.commitWith((tx) => createCompaction(tx, this.id, input), context);
+ }
+ async reset(handoff, context) {
+ const model = handoff === void 0 ? {} : { model: [{ role: "user", content: handoff, timestamp: this.#host.now() }] };
+ const entry = { kind: ResetEntry.kind, head: "self", ...model };
+ await this.#host.submissions.submit(this.id, { type: "write", entry }, context);
+ }
+ commit(change, context) {
+ return this.#host.harness.commitWith(change, context, { conversationId: this.id });
+ }
+ context(context) {
+ return readContext(this.#host.harness, this.#host.storage, this.id, context);
+ }
+ entries(query, limit2, cursor, context) {
+ const bounded = {
+ conversationId: this.id,
+ ...query.minEntryId === void 0 ? {} : { minEntryId: query.minEntryId },
+ ...query.maxEntryId === void 0 ? {} : { maxEntryId: query.maxEntryId }
+ };
+ return this.#host.harness.readOnLine(() => this.#host.storage.scanEntries(bounded, limit2, cursor, context));
+ }
+ fork(at, options, context) {
+ return this.#host.create({ kind: "fork", parentId: this.id, at, ownership: options.ownership }, options, context);
+ }
+ abort(context, options) {
+ this.#host.tasks.resume();
+ return this.#host.tasks.abortConversation(this.id, options?.background === true, context);
+ }
+ waitForIdle(context) {
+ this.#host.tasks.resume();
+ return this.#host.tasks.waitForIdle(this.id, context);
+ }
+ viewState(context) {
+ return this.#host.views.state(this.id, context);
+ }
+ watch(context) {
+ return this.#host.views.watch(this.id, context);
+ }
+};
+var HarnessImpl = class extends SessionImpl {
+ #storage;
+ #options;
+ #report;
+ #host;
+ #tasks;
+ #submissions;
+ #taskGraph;
+ #closed = false;
+ constructor(storage, options, context) {
+ super(storage);
+ this.#storage = storage;
+ this.#options = options;
+ this.#report = options.onReport ?? (() => {
+ });
+ const now = options.now ?? Date.now;
+ const settings2 = () => resolveSettings(options.settings);
+ this.#tasks = new TaskScheduler({
+ session: this,
+ storage,
+ registry: options.registry,
+ models: options.models,
+ agent: (id, snapshot, callContext) => this.resolveAgent(id, snapshot, callContext),
+ settings: settings2,
+ env: (id, callContext) => this.buildEnv(id, callContext),
+ now,
+ report: this.#report,
+ settleOutcome: settleSchedulerOutcome,
+ withdrawInputs: withdrawQueuedInputs,
+ conversation: async (id, binding, callContext) => {
+ const record = await this.readOnLine(() => storage.conversation(id, callContext));
+ return record === void 0 ? void 0 : boundConversation(id, binding, this.#submissions, this.#tasks);
+ },
+ context: withoutAbortSignal(context)
+ });
+ this.#submissions = new Submissions(this, storage, now, settings2, () => this.#tasks.resume());
+ this.#taskGraph = new TaskGraphView(this, storage);
+ this.#host = {
+ harness: this,
+ storage,
+ tasks: this.#tasks,
+ submissions: this.#submissions,
+ views: new ConversationViews(this, storage),
+ now,
+ create: (target, createOptions, context2) => this.#create(target, createOptions, context2)
+ };
+ }
+ /** Resolve a conversation's committed `pi.agent` against `snapshot`, or the current one, and the current settings. */
+ async resolveAgent(id, snapshot, context) {
+ const registry = snapshot ?? this.#options.registry.snapshot();
+ const state3 = await this.snapshot(AgentDoc, id, context);
+ return resolveAgent(state3, registry, resolveSettings(this.#options.settings), this.#report);
+ }
+ /** Build a conversation's environment from its current `cwd`; `undefined` without an `env` option. */
+ async buildEnv(id, context) {
+ const build = this.#options.env;
+ if (build === void 0)
+ return void 0;
+ const cwd = (await this.snapshot(AgentDoc, id, context))?.cwd;
+ return build({ conversationId: id, ...cwd === void 0 ? {} : { cwd }, read: this }, context);
+ }
+ /** Reconcile surviving `running` tasks to `pending`; part of open. */
+ openTasks(context) {
+ return this.#tasks.open(context);
+ }
+ resume() {
+ this.#assertOpen();
+ this.#tasks.resume();
+ }
+ getTask(id, context) {
+ return this.readOnLine(() => this.#storage.task(id, context));
+ }
+ inspect(context) {
+ return this.readOnLine(async () => {
+ const { scheduling, tasks } = await this.#tasks.inspect(this.#options.registry.snapshot());
+ const scan = (status) => scanAll((cursor) => this.#storage.scanSubmissions({ status }, SCAN_PAGE_SIZE5, cursor, context));
+ const submissions = [...await scan("queued"), ...await scan("placed")].sort((a, b) => a.id - b.id);
+ return { scheduling, tasks, submissions };
+ });
+ }
+ submission(id, context) {
+ return this.#submissions.get(id, context);
+ }
+ abortSubmission(id, context, conversationId) {
+ return this.#submissions.abort(id, context, conversationId);
+ }
+ abortTask(id, context) {
+ return this.#tasks.abort(id, context);
+ }
+ waitForTask(id, context) {
+ this.#tasks.resume();
+ return this.#tasks.waitForTask(id, context);
+ }
+ waitForIdle(context) {
+ this.#tasks.resume();
+ return this.#tasks.waitForIdle(void 0, context);
+ }
+ /** Sum every conversation's committed `pi.usage`. Each document is read at its own point; totals only grow. */
+ async usage(context) {
+ const conversations = await this.readOnLine(() => scanAll((cursor) => this.#storage.scanConversations({}, SCAN_PAGE_SIZE5, cursor, context)));
+ const total = UsageDoc.definition.initial();
+ for (const { id } of conversations) {
+ const state3 = await this.snapshot(UsageDoc, id, context);
+ if (state3 !== void 0)
+ addUsageState(total, state3);
+ }
+ return total;
+ }
+ taskGraph(context) {
+ return this.#taskGraph.state(context);
+ }
+ watchTaskGraph(context) {
+ return this.#taskGraph.watch(context);
+ }
+ root(context, options) {
+ return this.#create({ kind: "root" }, options ?? {}, context);
+ }
+ async conversation(id, context) {
+ this.#assertOpen();
+ const record = await this.readOnLine(() => this.#storage.conversation(id, context));
+ return record === void 0 ? void 0 : new ConversationImpl(record.id, this.#host);
+ }
+ createConversation(options, context) {
+ return this.#create({ kind: "independent", ownership: options.ownership }, options, context);
+ }
+ close(context) {
+ this.#closed = true;
+ return super.close(context);
+ }
+ /** Join task invocations after admission is sealed and before Storage closes; writes no task outcome. */
+ beforeClose() {
+ return this.#tasks.join();
+ }
+ async #create(target, options, context) {
+ this.#assertOpen();
+ const id = await this.commitWith(async (tx) => {
+ if (target.kind === "root" && await tx.conversation(ROOT_CONVERSATION_ID) !== void 0) {
+ return ROOT_CONVERSATION_ID;
+ }
+ const record = target.kind === "root" ? await tx.createRootConversation() : target.kind === "fork" ? await tx.forkConversation(target.parentId, target.at, { ownership: target.ownership }) : await tx.createConversation({ ownership: target.ownership });
+ if (options.agent !== void 0)
+ await configure(tx, record.id, options.agent);
+ if (options.init !== void 0)
+ await options.init(tx, record.id);
+ return record.id;
+ }, context);
+ return new ConversationImpl(id, this.#host);
+ }
+ /**
+ * The built-in creation hook, in every commit that creates or forks a conversation: empty `pi.live`, `pi.inbox`, and
+ * `pi.usage`, a fresh `pi.provider`, the conversation's `pi.agent` (see `createAgent()`), then
+ * `HarnessOptions.conversationCreated`.
+ */
+ async conversationCreated(tx, record) {
+ await tx.doc(LiveDoc, record.id);
+ await tx.doc(InboxDoc, record.id);
+ await tx.doc(UsageDoc, record.id);
+ await tx.doc(ProviderDoc, record.id);
+ await createAgent(tx, record);
+ await this.#options.conversationCreated?.(tx, record);
+ }
+ #assertOpen() {
+ if (this.#closed)
+ throw new Error("Harness is closed");
+ }
+};
+function boundConversation(id, binding, submissions, tasks) {
+ const bind = (context) => withAbortSignal(binding.signal, context);
+ const bound = (operation) => {
+ return async (context) => {
+ binding.check();
+ return operation(bind(context));
+ };
+ };
+ return {
+ id,
+ submit: async (draft, context) => {
+ binding.check();
+ const submission = await submissions.submit(id, draft, bind(context));
+ return {
+ id: submission.id,
+ status: bound((callContext) => submission.status(callContext)),
+ wait: bound((callContext) => submission.wait(callContext)),
+ abort: bound((callContext) => submission.abort(callContext))
+ };
+ },
+ abort: async (context, options) => {
+ binding.check();
+ return tasks.abortConversation(id, options?.background === true, bind(context));
+ },
+ waitForIdle: bound((callContext) => tasks.waitForIdle(id, callContext))
+ };
+}
+var Harness = {
+ /** Open a Harness over storage. The registry may keep changing while the Harness runs. */
+ async open(storage, options, context) {
+ context.abortSignal?.throwIfAborted();
+ const snapshot = options.registry.snapshot();
+ const missing = BUILTIN_TASKS.filter((task) => snapshot.task(task.definition.name) === void 0);
+ if (missing.length > 0) {
+ const names3 = missing.map((task) => task.definition.name).join(", ");
+ throw new Error(`Registry lacks built-in tasks ${names3}; create it with createRegistry()`);
+ }
+ const harness = new HarnessImpl(storage, options, context);
+ try {
+ await harness.openTasks(context);
+ } catch (error) {
+ await harness.close(withoutAbortSignal(context)).catch((closeError) => options.onReport?.(closeError));
+ throw error;
+ }
+ return harness;
+ }
+};
+
+// node_modules/@earendil-works/pi-durable/dist/storage/memory.js
+function* documentDeltaBatches(id, version, revisions, start) {
+ for (let index3 = start; index3 < revisions.length; index3++) {
+ const revision = revisions[index3];
+ if (revision.kind !== "delta" || revision.version !== version) {
+ throw new Error(`Document ${id} crosses a stored version boundary without a base`);
+ }
+ yield revision.ops;
+ }
+}
+var clone = (value) => {
+ if (value === null || typeof value !== "object")
+ return value;
+ if (Array.isArray(value))
+ return value.map((item) => clone(item));
+ const source = value;
+ const nullPrototype = Object.getPrototypeOf(value) === null;
+ const result = nullPrototype ? /* @__PURE__ */ Object.create(null) : {};
+ for (const key of Object.keys(source)) {
+ const copied = clone(source[key]);
+ if (!nullPrototype && key in result) {
+ Object.defineProperty(result, key, {
+ value: copied,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+ } else {
+ result[key] = copied;
+ }
+ }
+ return result;
+};
+var freeze = (value) => {
+ if (value === null || typeof value !== "object" || Object.isFrozen(value))
+ return value;
+ for (const child of Object.values(value))
+ freeze(child);
+ return Object.freeze(value);
+};
+var cursorId = (cursor) => {
+ const after = cursor?.after;
+ if (after === void 0)
+ return void 0;
+ if (typeof after !== "number" || !Number.isSafeInteger(after))
+ throw new TypeError("Invalid storage cursor");
+ return idFromNumber(after);
+};
+var lowerBound = (ids, target) => {
+ let low = 0;
+ let high = ids.length;
+ while (low < high) {
+ const middle = low + high >>> 1;
+ if (ids[middle] < target)
+ low = middle + 1;
+ else
+ high = middle;
+ }
+ return low;
+};
+var upperBound = (ids, target) => {
+ let low = 0;
+ let high = ids.length;
+ while (low < high) {
+ const middle = low + high >>> 1;
+ if (ids[middle] <= target)
+ low = middle + 1;
+ else
+ high = middle;
+ }
+ return low;
+};
+var insertSorted = (ids, id) => {
+ if (ids.length === 0 || ids[ids.length - 1] < id)
+ ids.push(id);
+ else
+ ids.splice(lowerBound(ids, id), 0, id);
+};
+var removeSorted = (ids, id) => {
+ const index3 = lowerBound(ids, id);
+ if (ids[index3] === id)
+ ids.splice(index3, 1);
+};
+var insertMapId = (index3, key, id) => {
+ let ids = index3.get(key);
+ if (ids === void 0) {
+ ids = [];
+ index3.set(key, ids);
+ }
+ insertSorted(ids, id);
+};
+var scopeKey = (scope) => {
+ switch (scope.kind) {
+ case "session":
+ return JSON.stringify(["session"]);
+ case "conversation":
+ return JSON.stringify(["conversation", scope.conversationId]);
+ case "task":
+ return JSON.stringify(["task", scope.taskId]);
+ }
+};
+var addressKey = (address) => JSON.stringify([
+ address.kind,
+ scopeKey(address.scope),
+ address.key === void 0 ? ["singleton"] : ["family", address.key]
+]);
+var recordAddressKey = (record) => addressKey({ kind: record.kind, scope: record.scope, key: record.key });
+var isAliveAt = (record, at) => {
+ if (at === "current")
+ return record.retiredAt === void 0;
+ return record.createdAt <= at && (record.retiredAt === void 0 || at < record.retiredAt);
+};
+var isCurrentOnly = (record) => record.scope.kind !== "conversation" || record.history === "latest";
+var tableContaining = (state3, id) => state3.recordTypes.get(id);
+var page = (values, limit2) => {
+ const items = values.slice(0, limit2);
+ if (values.length <= limit2)
+ return { items: clone(items) };
+ return { items: clone(items), next: { after: items.at(-1).id } };
+};
+var MemoryStorage = class {
+ state = {
+ recordTypes: /* @__PURE__ */ new Map(),
+ conversations: /* @__PURE__ */ new Map(),
+ conversationIds: [],
+ conversationIdsByOwnerConversation: /* @__PURE__ */ new Map(),
+ conversationIdsByOwnerTask: /* @__PURE__ */ new Map(),
+ entries: /* @__PURE__ */ new Map(),
+ entryIds: /* @__PURE__ */ new Map(),
+ headEntryIds: /* @__PURE__ */ new Map(),
+ entryCommitSeqs: /* @__PURE__ */ new Map(),
+ tasks: /* @__PURE__ */ new Map(),
+ taskIds: [],
+ taskIdsByStatus: { pending: [], running: [], waiting: [], completing: [], terminal: [] },
+ submissions: /* @__PURE__ */ new Map(),
+ submissionIds: [],
+ submissionIdsByStatus: { queued: [], placed: [], done: [], unanswered: [] },
+ submissionIdsByRequest: /* @__PURE__ */ new Map(),
+ documents: /* @__PURE__ */ new Map(),
+ documentAddresses: /* @__PURE__ */ new Map(),
+ documentIdsByScope: /* @__PURE__ */ new Map()
+ };
+ nextId = 2;
+ nextSeq = 1;
+ closed = false;
+ async commit(writes, _context) {
+ return this.prepareCommit(writes).apply();
+ }
+ /** Validate and detach one commit without changing observable state. */
+ prepareCommit(writes, seq = seqFromNumber(this.nextSeq)) {
+ this.assertOpen();
+ if (!Number.isSafeInteger(seq) || seq < this.nextSeq) {
+ throw new Error(`Commit sequence ${seq} does not strictly increase`);
+ }
+ const detachedWrites = freeze(this.resolveDocumentCopies(writes.map((write) => clone(write))));
+ this.checkGlobalIds(detachedWrites);
+ const documentActions = this.prepareDocumentActions(detachedWrites);
+ this.checkDocumentActions(documentActions);
+ let applied = false;
+ return {
+ seq,
+ writes: detachedWrites,
+ apply: () => {
+ if (!applied) {
+ applied = true;
+ this.applyPreparedCommit(detachedWrites, documentActions, seq);
+ }
+ return seq;
+ }
+ };
+ }
+ resolveDocumentCopies(writes) {
+ if (!writes.some((write) => write.type === "document.copy"))
+ return writes;
+ const changedDocumentIds = /* @__PURE__ */ new Set();
+ for (const write of writes) {
+ if (write.type === "document.create" || write.type === "document.copy") {
+ changedDocumentIds.add(write.record.id);
+ } else if (write.type === "document.change" || write.type === "document.retire") {
+ changedDocumentIds.add(write.id);
+ }
+ }
+ return writes.map((write) => {
+ if (write.type !== "document.copy")
+ return write;
+ try {
+ if (changedDocumentIds.has(write.source.id)) {
+ throw new Error(`Fork source document ${write.source.id} is changed in the copy batch`);
+ }
+ const stored = this.materializeDocument(write.source.id, write.source.at);
+ if (stored === void 0)
+ throw new Error(`Fork source document ${write.source.id} cannot be read`);
+ if (stored.record.scope.kind !== "conversation" || write.record.scope.kind !== "conversation" || stored.record.kind !== write.record.kind || stored.record.key !== write.record.key || stored.record.history !== write.record.history || stored.record.fork !== write.record.fork) {
+ throw new Error(`Fork source document ${write.source.id} does not match the copied record`);
+ }
+ return {
+ type: "document.create",
+ record: write.record,
+ content: { kind: "base", version: stored.version, value: stored.value }
+ };
+ } catch (error) {
+ if (error instanceof StorageRejected)
+ throw error;
+ throw new StorageRejected(`Document copy ${write.record.id} was rejected`, { cause: error });
+ }
+ });
+ }
+ applyPreparedCommit(prepared, documentActions, seq) {
+ for (const write of prepared) {
+ switch (write.type) {
+ case "conversation": {
+ this.state.recordTypes.set(write.value.id, "conversation");
+ this.state.conversations.set(write.value.id, write.value);
+ insertSorted(this.state.conversationIds, write.value.id);
+ const owner = write.value.owner;
+ if (owner !== void 0) {
+ insertMapId(this.state.conversationIdsByOwnerConversation, owner.conversationId, write.value.id);
+ insertMapId(this.state.conversationIdsByOwnerTask, owner.taskId, write.value.id);
+ }
+ this.nextId = Math.max(this.nextId, write.value.id + 1);
+ break;
+ }
+ case "entry": {
+ this.state.recordTypes.set(write.value.id, "entry");
+ this.state.entries.set(write.value.id, write.value);
+ this.state.entryCommitSeqs.set(write.value.id, seq);
+ let ids = this.state.entryIds.get(write.value.conversationId);
+ if (ids === void 0) {
+ ids = [];
+ this.state.entryIds.set(write.value.conversationId, ids);
+ }
+ insertSorted(ids, write.value.id);
+ if (write.value.head !== void 0) {
+ let headIds = this.state.headEntryIds.get(write.value.conversationId);
+ if (headIds === void 0) {
+ headIds = [];
+ this.state.headEntryIds.set(write.value.conversationId, headIds);
+ }
+ insertSorted(headIds, write.value.id);
+ }
+ this.nextId = Math.max(this.nextId, write.value.id + 1);
+ break;
+ }
+ case "task": {
+ this.state.recordTypes.set(write.value.id, "task");
+ const previous = this.state.tasks.get(write.value.id);
+ if (previous === void 0) {
+ insertSorted(this.state.taskIds, write.value.id);
+ insertSorted(this.state.taskIdsByStatus[write.value.state.status], write.value.id);
+ } else if (previous.state.status !== write.value.state.status) {
+ removeSorted(this.state.taskIdsByStatus[previous.state.status], write.value.id);
+ insertSorted(this.state.taskIdsByStatus[write.value.state.status], write.value.id);
+ }
+ this.state.tasks.set(write.value.id, write.value);
+ this.nextId = Math.max(this.nextId, write.value.id + 1);
+ break;
+ }
+ case "submission": {
+ this.state.recordTypes.set(write.value.id, "submission");
+ const previous = this.state.submissions.get(write.value.id);
+ if (previous === void 0) {
+ insertSorted(this.state.submissionIds, write.value.id);
+ insertSorted(this.state.submissionIdsByStatus[write.value.status], write.value.id);
+ } else if (previous.status !== write.value.status) {
+ removeSorted(this.state.submissionIdsByStatus[previous.status], write.value.id);
+ insertSorted(this.state.submissionIdsByStatus[write.value.status], write.value.id);
+ }
+ if (previous?.requestId !== void 0) {
+ const previousRequests = this.state.submissionIdsByRequest.get(previous.conversationId);
+ if (previousRequests?.get(previous.requestId) === write.value.id) {
+ previousRequests.delete(previous.requestId);
+ if (previousRequests.size === 0)
+ this.state.submissionIdsByRequest.delete(previous.conversationId);
+ }
+ }
+ this.state.submissions.set(write.value.id, write.value);
+ if (write.value.requestId !== void 0) {
+ let requests = this.state.submissionIdsByRequest.get(write.value.conversationId);
+ if (requests === void 0) {
+ requests = /* @__PURE__ */ new Map();
+ this.state.submissionIdsByRequest.set(write.value.conversationId, requests);
+ }
+ requests.set(write.value.requestId, write.value.id);
+ }
+ this.nextId = Math.max(this.nextId, write.value.id + 1);
+ break;
+ }
+ case "document.copy":
+ throw new Error("Prepared document copy was not resolved");
+ case "document.create":
+ case "document.change":
+ case "document.retire":
+ break;
+ }
+ }
+ this.applyDocumentActions(documentActions, seq);
+ this.nextSeq = seq + 1;
+ return seq;
+ }
+ async mintId() {
+ this.assertOpen();
+ if (!Number.isSafeInteger(this.nextId))
+ throw new Error("ID space is exhausted");
+ return idFromNumber(this.nextId++);
+ }
+ async conversation(id, _context) {
+ this.assertOpen();
+ const value = this.state.conversations.get(id);
+ return value === void 0 ? void 0 : clone(value);
+ }
+ async scanConversations(query, limit2, cursor, _context) {
+ this.assertOpen();
+ const ids = query.ownerTaskId !== void 0 ? this.state.conversationIdsByOwnerTask.get(query.ownerTaskId) ?? [] : query.ownerConversationId !== void 0 ? this.state.conversationIdsByOwnerConversation.get(query.ownerConversationId) ?? [] : this.state.conversationIds;
+ const after = cursorId(cursor);
+ const start = after === void 0 ? 0 : upperBound(ids, after);
+ const values = [];
+ for (let index3 = start; index3 < ids.length && values.length <= limit2; index3++) {
+ const value = this.state.conversations.get(ids[index3]);
+ if (query.ownerConversationId !== void 0 && value.owner?.conversationId !== query.ownerConversationId) {
+ continue;
+ }
+ values.push(value);
+ }
+ return page(values, limit2);
+ }
+ async entry(idOrConversationId, idOrContext, context) {
+ this.assertOpen();
+ if (context === void 0) {
+ const id2 = idFromNumber(idOrConversationId);
+ const entry2 = this.state.entries.get(id2);
+ if (entry2 === void 0)
+ return void 0;
+ return { entry: clone(entry2), commitSeq: this.state.entryCommitSeqs.get(id2) };
+ }
+ if (typeof idOrContext !== "number")
+ throw new TypeError("Storage.entry() requires an entry ID");
+ const conversationId = idFromNumber(idOrConversationId);
+ const id = idFromNumber(idOrContext);
+ const entry = this.visibleEntries(conversationId, id, id).next().value;
+ if (entry === void 0)
+ return void 0;
+ return { entry: clone(entry), commitSeq: this.state.entryCommitSeqs.get(id) };
+ }
+ async findLatestHeadMarker(conversationId, atOrBeforeEntryId, _context) {
+ this.assertOpen();
+ if (!this.state.conversations.has(conversationId)) {
+ throw new Error(`Unknown conversation: ${conversationId}`);
+ }
+ let currentId = conversationId;
+ let upperEntryId = atOrBeforeEntryId ?? Number.POSITIVE_INFINITY;
+ while (true) {
+ const ids = this.state.headEntryIds.get(currentId) ?? [];
+ const index3 = upperBound(ids, upperEntryId) - 1;
+ if (index3 >= 0) {
+ const entry = this.state.entries.get(ids[index3]);
+ return clone({ ...entry, head: entry.head });
+ }
+ const conversation = this.state.conversations.get(currentId);
+ if (conversation.parent === void 0)
+ return void 0;
+ upperEntryId = Math.min(upperEntryId, conversation.parent.at);
+ currentId = conversation.parent.conversationId;
+ }
+ }
+ async scanEntries(query, limit2, cursor, _context) {
+ this.assertOpen();
+ const after = cursorId(cursor);
+ const maxEntryId = after === void 0 ? query.maxEntryId : Math.min(query.maxEntryId ?? Number.POSITIVE_INFINITY, after - 1);
+ const visible = [];
+ for (const entry of this.visibleEntries(query.conversationId, query.minEntryId, maxEntryId)) {
+ visible.push(entry);
+ if (visible.length > limit2)
+ break;
+ }
+ return page(visible, limit2);
+ }
+ async task(id, _context) {
+ this.assertOpen();
+ const value = this.state.tasks.get(id);
+ return value === void 0 ? void 0 : clone(value);
+ }
+ async scanTasks(query, limit2, cursor, _context) {
+ this.assertOpen();
+ const after = cursorId(cursor);
+ const ids = query.status === void 0 ? this.state.taskIds : this.state.taskIdsByStatus[query.status];
+ const start = after === void 0 ? 0 : upperBound(ids, after);
+ const values = [];
+ for (let index3 = start; index3 < ids.length && values.length <= limit2; index3++) {
+ const value = this.state.tasks.get(ids[index3]);
+ if (query.conversationId !== void 0 && value.conversationId !== query.conversationId)
+ continue;
+ if (query.kind !== void 0 && value.kind !== query.kind)
+ continue;
+ if (query.abortRequested !== void 0 && value.abortRequested !== query.abortRequested)
+ continue;
+ if (query.background !== void 0 && value.background !== query.background)
+ continue;
+ values.push(value);
+ }
+ return page(values, limit2);
+ }
+ async submission(id, _context) {
+ this.assertOpen();
+ const value = this.state.submissions.get(id);
+ return value === void 0 ? void 0 : clone(value);
+ }
+ async scanSubmissions(query, limit2, cursor, _context) {
+ this.assertOpen();
+ const after = cursorId(cursor);
+ const ids = query.status === void 0 ? this.state.submissionIds : this.state.submissionIdsByStatus[query.status];
+ const start = after === void 0 ? 0 : upperBound(ids, after);
+ const values = [];
+ for (let index3 = start; index3 < ids.length && values.length <= limit2; index3++) {
+ const value = this.state.submissions.get(ids[index3]);
+ if (query.conversationId !== void 0 && value.conversationId !== query.conversationId)
+ continue;
+ values.push(value);
+ }
+ return page(values, limit2);
+ }
+ async submissionByRequest(conversationId, requestId, _context) {
+ this.assertOpen();
+ const id = this.state.submissionIdsByRequest.get(conversationId)?.get(requestId);
+ if (id === void 0)
+ return void 0;
+ return clone(this.state.submissions.get(id));
+ }
+ async findDocument(address, at, _context) {
+ this.assertOpen();
+ const index3 = this.state.documentAddresses.get(addressKey(address));
+ if (at === "current") {
+ return index3?.currentId === void 0 ? void 0 : clone(this.state.documents.get(index3.currentId).record);
+ }
+ for (const id of index3?.ids ?? []) {
+ const record = this.state.documents.get(id).record;
+ if (isAliveAt(record, at))
+ return clone(record);
+ }
+ return void 0;
+ }
+ async document(id, at, _context) {
+ this.assertOpen();
+ const stored = this.materializeDocument(id, at);
+ return stored === void 0 ? void 0 : {
+ record: clone(stored.record),
+ version: stored.version,
+ value: clone(stored.value),
+ deltasSinceBase: stored.deltasSinceBase
+ };
+ }
+ async scanDocuments(query, limit2, cursor, _context) {
+ this.assertOpen();
+ const ids = this.state.documentIdsByScope.get(scopeKey(query.scope)) ?? [];
+ const after = cursorId(cursor);
+ const start = after === void 0 ? 0 : upperBound(ids, after);
+ const values = [];
+ for (let index3 = start; index3 < ids.length && values.length <= limit2; index3++) {
+ const record = this.state.documents.get(ids[index3]).record;
+ if (query.kind !== void 0 && record.kind !== query.kind)
+ continue;
+ if (isAliveAt(record, query.at))
+ values.push(record);
+ }
+ return page(values, limit2);
+ }
+ async close(_context) {
+ this.closed = true;
+ }
+ materializeDocument(id, at) {
+ const stored = this.state.documents.get(id);
+ if (stored === void 0)
+ return void 0;
+ if (at !== "current" && isCurrentOnly(stored.record)) {
+ throw new Error(`Document ${id} does not retain historical content`);
+ }
+ if (!isAliveAt(stored.record, at))
+ return void 0;
+ const revisions = at === "current" ? stored.revisions : stored.revisions.filter((revision) => revision.seq <= at);
+ let baseIndex = revisions.length - 1;
+ while (baseIndex >= 0 && revisions[baseIndex].kind !== "base")
+ baseIndex--;
+ const base = revisions[baseIndex];
+ if (base?.kind !== "base")
+ throw new Error(`Document ${id} is missing a required base`);
+ const value = applyImmutableBatches(base.value, documentDeltaBatches(id, base.version, revisions, baseIndex + 1));
+ return { record: stored.record, version: base.version, value, deltasSinceBase: revisions.length - baseIndex - 1 };
+ }
+ *visibleEntries(conversationId, minEntryId = Number.NEGATIVE_INFINITY, maxEntryId = Number.POSITIVE_INFINITY) {
+ if (!this.state.conversations.has(conversationId)) {
+ throw new Error(`Unknown conversation: ${conversationId}`);
+ }
+ let currentId = conversationId;
+ let upperEntryId = maxEntryId;
+ while (true) {
+ const ids = this.state.entryIds.get(currentId) ?? [];
+ for (let index3 = upperBound(ids, upperEntryId) - 1; index3 >= 0; index3--) {
+ const id = ids[index3];
+ if (id < minEntryId)
+ break;
+ yield this.state.entries.get(id);
+ }
+ const conversation = this.state.conversations.get(currentId);
+ if (conversation.parent === void 0)
+ break;
+ upperEntryId = Math.min(upperEntryId, conversation.parent.at);
+ if (upperEntryId < minEntryId)
+ break;
+ currentId = conversation.parent.conversationId;
+ }
+ }
+ checkGlobalIds(writes) {
+ const claimed = /* @__PURE__ */ new Map();
+ for (const write of writes) {
+ if (write.type === "document.change" || write.type === "document.retire")
+ continue;
+ const document = write.type === "document.create" || write.type === "document.copy";
+ const table = document ? "document" : write.type;
+ const id = document ? write.record.id : write.value.id;
+ const existing = tableContaining(this.state, id);
+ const earlier = claimed.get(id);
+ if (table === "conversation" || table === "entry" || table === "document") {
+ if (existing !== void 0)
+ throw new Error(`ID ${id} already belongs to ${existing}`);
+ if (earlier !== void 0)
+ throw new Error(`ID ${id} is written more than once`);
+ } else {
+ if (existing !== void 0 && existing !== table) {
+ throw new Error(`ID ${id} already belongs to ${existing}`);
+ }
+ if (earlier !== void 0 && earlier !== table)
+ throw new Error(`ID ${id} is written as two record types`);
+ }
+ claimed.set(id, table);
+ }
+ }
+ prepareDocumentActions(writes) {
+ const actions = /* @__PURE__ */ new Map();
+ for (const write of writes) {
+ if (write.type !== "document.create" && write.type !== "document.change" && write.type !== "document.retire") {
+ continue;
+ }
+ const id = write.type === "document.create" ? write.record.id : write.id;
+ let action = actions.get(id);
+ if (action === void 0) {
+ action = { retire: false };
+ actions.set(id, action);
+ }
+ switch (write.type) {
+ case "document.create":
+ if (action.create !== void 0 || action.content !== void 0) {
+ throw new Error(`Document ${id} has more than one content command`);
+ }
+ action.create = write.record;
+ action.content = write.content;
+ break;
+ case "document.change":
+ if (action.content !== void 0)
+ throw new Error(`Document ${id} has more than one content command`);
+ action.content = write.content;
+ break;
+ case "document.retire":
+ if (action.retire)
+ throw new Error(`Document ${id} is retired more than once`);
+ action.retire = true;
+ break;
+ }
+ }
+ return actions;
+ }
+ checkDocumentActions(actions) {
+ const liveCounts = /* @__PURE__ */ new Map();
+ for (const [id, action] of actions) {
+ const existing = this.state.documents.get(id);
+ if (action.create === void 0 && existing === void 0)
+ throw new Error(`Unknown document: ${id}`);
+ if (action.create !== void 0 && existing !== void 0)
+ throw new Error(`Document ${id} already exists`);
+ if (existing?.record.retiredAt !== void 0)
+ throw new Error(`Document ${id} is retired`);
+ const previous = existing?.revisions.at(-1);
+ if (action.content?.kind === "delta") {
+ if (previous === void 0)
+ throw new Error(`Document ${id} delta has no base`);
+ if (previous.version !== action.content.version) {
+ throw new Error(`Document ${id} version transition requires a base`);
+ }
+ }
+ const key = action.create === void 0 ? recordAddressKey(existing.record) : recordAddressKey(action.create);
+ const currentId = this.state.documentAddresses.get(key)?.currentId;
+ let live = liveCounts.get(key);
+ if (live === void 0)
+ live = currentId === void 0 ? 0 : 1;
+ if (action.retire && currentId === id)
+ live--;
+ if (action.create !== void 0 && !action.retire)
+ live++;
+ liveCounts.set(key, live);
+ }
+ for (const live of liveCounts.values()) {
+ if (live > 1)
+ throw new Error(`Document address already has a current incarnation`);
+ }
+ }
+ applyDocumentActions(actions, seq) {
+ for (const [id, action] of actions) {
+ let stored = this.state.documents.get(id);
+ if (action.create !== void 0) {
+ const record = {
+ ...action.create,
+ createdAt: seq,
+ ...action.retire ? { retiredAt: seq } : {}
+ };
+ stored = { record, revisions: [{ ...action.content, seq }] };
+ this.state.recordTypes.set(id, "document");
+ this.state.documents.set(id, stored);
+ const key = recordAddressKey(record);
+ let address = this.state.documentAddresses.get(key);
+ if (address === void 0) {
+ address = { ids: [] };
+ this.state.documentAddresses.set(key, address);
+ }
+ insertSorted(address.ids, id);
+ let scopeIds = this.state.documentIdsByScope.get(scopeKey(record.scope));
+ if (scopeIds === void 0) {
+ scopeIds = [];
+ this.state.documentIdsByScope.set(scopeKey(record.scope), scopeIds);
+ }
+ insertSorted(scopeIds, id);
+ this.nextId = Math.max(this.nextId, id + 1);
+ } else if (action.content !== void 0) {
+ const revision = { ...action.content, seq };
+ if (revision.kind === "base" && isCurrentOnly(stored.record))
+ stored.revisions = [revision];
+ else
+ stored.revisions.push(revision);
+ }
+ if (action.retire && action.create === void 0)
+ stored.record = { ...stored.record, retiredAt: seq };
+ if (action.retire && isCurrentOnly(stored.record))
+ stored.revisions = [];
+ if (action.create !== void 0 || action.retire) {
+ const address = this.state.documentAddresses.get(recordAddressKey(stored.record));
+ if (action.retire && address.currentId === id)
+ delete address.currentId;
+ if (action.create !== void 0 && !action.retire)
+ address.currentId = id;
+ }
+ }
+ }
+ assertOpen() {
+ if (this.closed)
+ throw new Error("MemoryStorage is closed");
+ }
+};
+
+// node_modules/@earendil-works/pi-durable/dist/env/node.js
+import { spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { constants, createWriteStream } from "node:fs";
+import { access, appendFile, lstat as lstat2, mkdir, mkdtemp, opendir, open as openFile, readdir as readdir2, readFile as readFile2, realpath, rename, rm, writeFile } from "node:fs/promises";
+import { homedir, constants as osConstants, tmpdir } from "node:os";
+import { basename as basename2, isAbsolute, join, resolve as resolve2 } from "node:path";
+import { fileURLToPath } from "node:url";
+
+// node_modules/@earendil-works/pi-durable/dist/env/decode.js
+function rangeDecoder() {
+ return new TextDecoder("utf-8", { ignoreBOM: true });
+}
+function startsWithBom(firstBytes) {
+ return firstBytes[0] === 239 && firstBytes[1] === 187 && firstBytes[2] === 191;
+}
+var StreamDecoder = class {
+ #decoder = rangeDecoder();
+ #started = false;
+ /** Text for `bytes`, holding back an incomplete character; without `bytes`, the end of the stream. */
+ decode(bytes) {
+ const text = bytes === void 0 ? this.#decoder.decode() : this.#decoder.decode(bytes, { stream: true });
+ if (this.#started || text === "")
+ return text;
+ this.#started = true;
+ return text.startsWith("\uFEFF") ? text.slice(1) : text;
+ }
+};
+
+// node_modules/@earendil-works/pi-durable/dist/env/line-scan.js
+var NEWLINE2 = 10;
+var encoder3 = new TextEncoder();
+function decodedBytes(text) {
+ return text === "" ? 0 : encoder3.encode(text).length;
+}
+var LineScanner = class {
+ #startLine;
+ #endLine;
+ #position = 0;
+ #newlines = 0;
+ #lineStart = 0;
+ #start;
+ #end;
+ #firstLineEnd;
+ #lastLineStart;
+ #selectedBytes = 0;
+ #firstLineBytes = 0;
+ #selection;
+ #firstLine;
+ /** The first bytes, held until it is known whether they are a byte-order mark. */
+ #head = [];
+ #bom = false;
+ /** `startLine` and `endLine` must be non-negative integers with `endLine > startLine`; `endLine` absent: to the end. */
+ constructor(startLine, endLine = Number.POSITIVE_INFINITY) {
+ if (!Number.isSafeInteger(startLine) || startLine < 0 || !(endLine > startLine)) {
+ throw new RangeError("Invalid line range");
+ }
+ if (endLine !== Number.POSITIVE_INFINITY && !Number.isSafeInteger(endLine))
+ throw new RangeError("Invalid line range");
+ this.#startLine = startLine;
+ this.#endLine = endLine;
+ if (startLine === 0)
+ this.#begin(0);
+ }
+ push(chunk) {
+ if (this.#head !== void 0) {
+ const take = Math.min(3 - this.#head.length, chunk.length);
+ this.#head.push(...chunk.subarray(0, take));
+ if (this.#head.length < 3)
+ return;
+ this.#releaseHead();
+ chunk = chunk.subarray(take);
+ }
+ this.#process(chunk);
+ }
+ #releaseHead() {
+ const head = Uint8Array.from(this.#head ?? []);
+ this.#head = void 0;
+ this.#bom = startsWithBom(head);
+ this.#process(head);
+ }
+ #process(chunk) {
+ const base = this.#position;
+ let from = 0;
+ for (let index3 = chunk.indexOf(NEWLINE2); index3 !== -1; index3 = chunk.indexOf(NEWLINE2, index3 + 1)) {
+ this.#feed(chunk, base, from, index3);
+ const line = this.#newlines;
+ const position = base + index3;
+ if (line === this.#startLine)
+ this.#endFirstLine(position);
+ if (line === this.#endLine - 1)
+ this.#endSelection(position);
+ this.#feed(chunk, base, index3, index3 + 1);
+ from = index3 + 1;
+ this.#newlines++;
+ this.#lineStart = position + 1;
+ if (this.#newlines === this.#startLine)
+ this.#begin(this.#lineStart);
+ if (this.#newlines === this.#endLine - 1)
+ this.#lastLineStart = this.#lineStart;
+ }
+ this.#feed(chunk, base, from, chunk.length);
+ this.#position += chunk.length;
+ }
+ finish() {
+ if (this.#head !== void 0)
+ this.#releaseHead();
+ const size = this.#position;
+ if (this.#start === void 0) {
+ return {
+ newlines: this.#newlines,
+ start: size,
+ end: size,
+ firstLineEnd: size,
+ lastLineStart: size,
+ selectedBytes: 0,
+ firstLineBytes: 0
+ };
+ }
+ if (this.#firstLineEnd === void 0)
+ this.#endFirstLine(size);
+ if (this.#end === void 0)
+ this.#endSelection(size);
+ return {
+ newlines: this.#newlines,
+ start: this.#start,
+ end: this.#end ?? size,
+ firstLineEnd: this.#firstLineEnd ?? size,
+ // A selection that reaches past the last line ends with the last line.
+ lastLineStart: this.#lastLineStart ?? this.#lineStart,
+ selectedBytes: this.#selectedBytes,
+ firstLineBytes: this.#firstLineBytes
+ };
+ }
+ #begin(start) {
+ this.#start = start;
+ if (this.#startLine === this.#endLine - 1)
+ this.#lastLineStart = start;
+ this.#selection = rangeDecoder();
+ this.#firstLine = rangeDecoder();
+ }
+ #endFirstLine(position) {
+ this.#firstLineEnd = position;
+ if (this.#firstLine !== void 0)
+ this.#firstLineBytes += decodedBytes(this.#firstLine.decode());
+ this.#firstLine = void 0;
+ }
+ #endSelection(position) {
+ this.#end = position;
+ if (this.#selection !== void 0)
+ this.#selectedBytes += decodedBytes(this.#selection.decode());
+ this.#selection = void 0;
+ }
+ /** Feed `chunk[from, to)`, which starts at file offset `base`, to the decoders of the ranges still open. */
+ #feed(chunk, base, from, to) {
+ if (this.#bom && base + from < 3)
+ from = Math.min(to, 3 - base);
+ if (to <= from)
+ return;
+ const bytes = chunk.subarray(from, to);
+ if (this.#selection !== void 0) {
+ this.#selectedBytes += decodedBytes(this.#selection.decode(bytes, { stream: true }));
+ }
+ if (this.#firstLine !== void 0) {
+ this.#firstLineBytes += decodedBytes(this.#firstLine.decode(bytes, { stream: true }));
+ }
+ }
+};
+
+// node_modules/@earendil-works/pi-durable/dist/env/index.js
+function ok(value) {
+ return { ok: true, value };
+}
+function err(error) {
+ return { ok: false, error };
+}
+function getOrThrow(result) {
+ if (!result.ok)
+ throw result.error;
+ return result.value;
+}
+function toError3(error) {
+ if (error instanceof Error)
+ return error;
+ if (typeof error === "string")
+ return new Error(error);
+ try {
+ return new Error(JSON.stringify(error));
+ } catch {
+ return new Error(String(error));
+ }
+}
+var FileError = class extends Error {
+ code;
+ path;
+ constructor(code, message, path5, cause) {
+ super(message, cause === void 0 ? void 0 : { cause });
+ this.name = "FileError";
+ this.code = code;
+ this.path = path5;
+ }
+};
+var ExecutionError = class extends Error {
+ code;
+ /** Spill file of a command that timed out or was aborted after its output crossed the spill thresholds. */
+ spillPath;
+ constructor(code, message, cause) {
+ super(message, cause === void 0 ? void 0 : { cause });
+ this.name = "ExecutionError";
+ this.code = code;
+ }
+};
+
+// node_modules/@earendil-works/pi-durable/dist/env/node-watch.js
+import { createHash } from "node:crypto";
+import { watch as fsWatch } from "node:fs";
+import { lstat, readdir, readFile, stat, statfs } from "node:fs/promises";
+import { dirname, relative, sep } from "node:path";
+var DEBOUNCE_MS = 50;
+var FSEVENTS_SETTLE_MS = 500;
+var DEFAULT_POLL_MS = 2e3;
+var DEFAULT_MAX_DIRECTORIES = 1e4;
+var HASH_MAX_BYTES = 256 * 1024;
+var HASH_RECENT_MS = 5e3;
+var UNRELIABLE_FILE_SYSTEMS = /* @__PURE__ */ new Set([
+ 26985,
+ // NFS
+ 20859,
+ // SMB
+ 4283649346,
+ // CIFS
+ 4266872130,
+ // SMB2
+ 1702057286,
+ // FUSE (sshfs, Android shared storage)
+ 16914839,
+ // 9P (WSL2 Windows drives)
+ 198183888,
+ // Lustre
+ 1196443219,
+ // GPFS
+ 12805120,
+ // Ceph
+ 1397113167,
+ // OpenAFS
+ 1799439955,
+ // kAFS
+ 1573531125
+ // sdcardfs
+]);
+var BudgetExceeded = class extends Error {
+};
+function isNodeError(error) {
+ return error instanceof Error && "code" in error;
+}
+function entryOf(stats, hash) {
+ const kind = stats.isFile() ? "file" : stats.isDirectory() ? "directory" : stats.isSymbolicLink() ? "symlink" : "other";
+ return {
+ kind,
+ dev: stats.dev,
+ ino: stats.ino,
+ size: kind === "directory" ? 0 : stats.size,
+ mtimeMs: kind === "directory" ? 0 : stats.mtimeMs,
+ ...hash === void 0 ? {} : { hash }
+ };
+}
+function sameEntry(a, b) {
+ return a.kind === b.kind && a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.hash === b.hash;
+}
+function ancestorsOf(path5) {
+ const result = [];
+ for (let current = dirname(path5); ; current = dirname(current)) {
+ result.push(current);
+ if (dirname(current) === current)
+ return result;
+ }
+}
+function isWithin(path5, ancestor) {
+ return path5 === ancestor || path5.startsWith(ancestor.endsWith(sep) ? ancestor : ancestor + sep);
+}
+function excluded(target, name) {
+ return target.hidden && name.startsWith(".") || target.names.has(name);
+}
+var NodeFileWatcher = class _NodeFileWatcher {
+ #targets;
+ #onChange;
+ #pollIntervalMs;
+ #maxDirectories;
+ #watchers = /* @__PURE__ */ new Map();
+ #events = /* @__PURE__ */ new Set();
+ #mode;
+ #snapshot = /* @__PURE__ */ new Map();
+ #timer;
+ #settleTimer;
+ #running;
+ #dirty = false;
+ #closed = false;
+ constructor(targets, onChange, mode, options) {
+ this.#targets = targets;
+ this.#onChange = onChange;
+ this.#mode = mode;
+ this.#pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_MS;
+ this.#maxDirectories = options.maxDirectories ?? DEFAULT_MAX_DIRECTORIES;
+ }
+ /** Establish coverage: watchers first, then the snapshot later changes are compared with. */
+ static async open(targets, resolvePath3, onChange, options) {
+ const resolved = targets.map((target) => ({
+ path: resolvePath3(target.path),
+ recursive: target.recursive === true,
+ hidden: target.exclude?.hidden === true,
+ names: new Set(target.exclude?.names ?? [])
+ }));
+ const mode = options.mode ?? (process.platform === "win32" || await anyUnreliable(resolved.map((target) => target.path)) ? "polling" : "native");
+ const watcher = new _NodeFileWatcher(resolved, onChange, mode, options);
+ try {
+ await watcher.#sync(false);
+ } catch (error) {
+ watcher.#stop();
+ if (error instanceof BudgetExceeded)
+ throw new FileError("invalid", error.message);
+ throw error;
+ }
+ watcher.#schedulePoll();
+ return watcher;
+ }
+ get mode() {
+ return this.#mode;
+ }
+ async close(_context) {
+ if (this.#closed)
+ return;
+ this.#stop();
+ await this.#running;
+ }
+ #stop() {
+ this.#closed = true;
+ clearTimeout(this.#timer);
+ this.#timer = void 0;
+ clearTimeout(this.#settleTimer);
+ this.#settleTimer = void 0;
+ for (const watcher of this.#watchers.values())
+ watcher.close();
+ this.#watchers.clear();
+ }
+ #deliver(change) {
+ if (this.#closed)
+ return;
+ try {
+ this.#onChange(change);
+ } catch {
+ }
+ }
+ #schedulePoll() {
+ if (this.#closed || this.#mode !== "polling")
+ return;
+ this.#timer = setTimeout(() => {
+ this.#timer = void 0;
+ void this.#flush().finally(() => this.#schedulePoll());
+ }, this.#pollIntervalMs);
+ }
+ #scheduleFlush() {
+ if (this.#closed || this.#timer !== void 0)
+ return;
+ this.#timer = setTimeout(() => {
+ this.#timer = void 0;
+ void this.#flush();
+ }, DEBOUNCE_MS);
+ }
+ #scheduleSettle() {
+ if (this.#closed)
+ return;
+ clearTimeout(this.#settleTimer);
+ this.#settleTimer = setTimeout(() => {
+ this.#settleTimer = void 0;
+ void this.#flush();
+ }, FSEVENTS_SETTLE_MS);
+ }
+ #flush() {
+ if (this.#running !== void 0) {
+ this.#dirty = true;
+ return this.#running;
+ }
+ this.#running = (async () => {
+ try {
+ do {
+ this.#dirty = false;
+ const events = [...this.#events];
+ this.#events.clear();
+ const changed = await this.#sync(true);
+ for (const path5 of events)
+ changed.add(path5);
+ if (changed.size > 0)
+ this.#deliver({ paths: [...changed].sort() });
+ } while (this.#dirty && !this.#closed);
+ } catch (error) {
+ const fileError = error instanceof FileError ? error : new FileError("invalid", error instanceof Error ? error.message : String(error));
+ this.#deliver({ error: fileError });
+ this.#stop();
+ } finally {
+ this.#running = void 0;
+ }
+ })();
+ return this.#running;
+ }
+ /** Rescan, report differences, and install watchers for new directories, rescanning until none are new. */
+ async #sync(report) {
+ const changed = /* @__PURE__ */ new Set();
+ for (let round = 0; round < 10 && !this.#closed; round++) {
+ const next = await this.#scan();
+ if (report)
+ for (const path5 of this.#diff(this.#snapshot, next))
+ changed.add(path5);
+ this.#snapshot = next;
+ if (this.#mode === "polling" || !this.#reconcileWatchers(next))
+ break;
+ if (process.platform === "darwin")
+ this.#scheduleSettle();
+ report = true;
+ }
+ return changed;
+ }
+ #diff(previous, next) {
+ const changed = [];
+ for (const [path5, entry] of next) {
+ const before = previous.get(path5);
+ if (before === void 0 || !sameEntry(before, entry))
+ changed.push(this.#reported(path5));
+ }
+ for (const path5 of previous.keys())
+ if (!next.has(path5))
+ changed.push(this.#reported(path5));
+ return changed;
+ }
+ /** An ancestor that changed identity moved every target below it; report those targets. */
+ #reported(path5) {
+ if (this.#targets.some((target) => isWithin(path5, target.path)))
+ return path5;
+ return this.#targets.find((target) => isWithin(target.path, path5))?.path ?? path5;
+ }
+ async #scan() {
+ const snapshot = /* @__PURE__ */ new Map();
+ let directories = 0;
+ const countDirectory = () => {
+ if (++directories > this.#maxDirectories) {
+ throw new BudgetExceeded(`Watched paths exceed ${this.#maxDirectories} directories`);
+ }
+ };
+ const record = async (path5, stats) => {
+ let hash;
+ if (this.#mode === "polling" && stats.isFile() && stats.size <= HASH_MAX_BYTES && Date.now() - stats.mtimeMs < HASH_RECENT_MS) {
+ hash = await readFile(path5).then((content) => createHash("sha256").update(content).digest("hex"), () => void 0);
+ }
+ snapshot.set(path5, entryOf(stats, hash));
+ };
+ const scanDirectory = async (target, directory) => {
+ let names3;
+ try {
+ names3 = await readdir(directory);
+ } catch (error) {
+ if (isNodeError(error) && ["ENOENT", "EACCES", "EPERM", "ENOTDIR"].includes(error.code ?? ""))
+ return;
+ throw error;
+ }
+ for (const name of names3) {
+ if (excluded(target, name))
+ continue;
+ const path5 = `${directory.endsWith(sep) ? directory : directory + sep}${name}`;
+ if (snapshot.has(path5))
+ continue;
+ const stats = await lstat(path5).catch(() => void 0);
+ if (stats === void 0)
+ continue;
+ await record(path5, stats);
+ if (target.recursive && stats.isDirectory()) {
+ countDirectory();
+ await scanDirectory(target, path5);
+ }
+ }
+ };
+ for (const target of this.#targets) {
+ for (const ancestor of ancestorsOf(target.path)) {
+ if (snapshot.has(ancestor))
+ continue;
+ const stats2 = await lstat(ancestor).catch(() => void 0);
+ if (stats2 !== void 0)
+ snapshot.set(ancestor, { ...entryOf(stats2), size: 0, mtimeMs: 0 });
+ }
+ const stats = await stat(target.path).catch(() => void 0);
+ if (stats === void 0)
+ continue;
+ await record(target.path, stats);
+ if (stats.isDirectory()) {
+ countDirectory();
+ await scanDirectory(target, target.path);
+ }
+ }
+ return snapshot;
+ }
+ /**
+ * Watch every existing ancestor of each target, each target directory, and on Linux each directory below a recursive
+ * target (elsewhere one recursive watcher per target). Returns whether a watcher was added.
+ */
+ #reconcileWatchers(snapshot) {
+ const wanted = /* @__PURE__ */ new Map();
+ const perDirectory = process.platform === "linux" || process.platform === "android";
+ for (const target of this.#targets) {
+ for (const ancestor of ancestorsOf(target.path)) {
+ if (snapshot.get(ancestor)?.kind === "directory" && !wanted.has(ancestor))
+ wanted.set(ancestor, false);
+ }
+ if (snapshot.get(target.path)?.kind !== "directory")
+ continue;
+ const recursiveRoot = target.recursive && !perDirectory;
+ wanted.set(target.path, recursiveRoot);
+ if (target.recursive && perDirectory) {
+ for (const [path5, entry] of snapshot) {
+ if (entry.kind === "directory" && path5 !== target.path && isWithin(path5, target.path)) {
+ wanted.set(path5, false);
+ }
+ }
+ }
+ }
+ for (const [path5, watcher] of this.#watchers) {
+ if (!wanted.has(path5)) {
+ watcher.close();
+ this.#watchers.delete(path5);
+ }
+ }
+ let added = false;
+ for (const [path5, recursive] of wanted) {
+ if (this.#watchers.has(path5))
+ continue;
+ try {
+ const watcher = fsWatch(path5, { recursive, persistent: false }, (_event, filename) => this.#onEvent(path5, filename === null ? void 0 : String(filename)));
+ watcher.on("error", () => {
+ watcher.close();
+ if (this.#watchers.get(path5) === watcher)
+ this.#watchers.delete(path5);
+ this.#scheduleFlush();
+ });
+ this.#watchers.set(path5, watcher);
+ added = true;
+ } catch (error) {
+ if (isNodeError(error) && error.code !== "ENOENT" && error.code !== "EACCES" && error.code !== "EPERM") {
+ this.#switchToPolling();
+ return false;
+ }
+ }
+ }
+ return added;
+ }
+ #switchToPolling() {
+ if (this.#mode === "polling")
+ return;
+ this.#mode = "polling";
+ for (const watcher of this.#watchers.values())
+ watcher.close();
+ this.#watchers.clear();
+ this.#deliver({ overflow: true });
+ clearTimeout(this.#timer);
+ this.#timer = void 0;
+ this.#schedulePoll();
+ }
+ #onEvent(directory, filename) {
+ if (this.#closed)
+ return;
+ const path5 = filename === void 0 ? directory : `${directory.endsWith(sep) ? directory : directory + sep}${filename}`;
+ const relevant = this.#inScope(path5);
+ if (relevant)
+ this.#events.add(this.#reported(path5));
+ if (relevant || filename === void 0)
+ this.#scheduleFlush();
+ }
+ #inScope(path5) {
+ for (const target of this.#targets) {
+ if (isWithin(target.path, path5))
+ return true;
+ if (!isWithin(path5, target.path) || path5 === target.path)
+ continue;
+ const components = relative(target.path, path5).split(sep);
+ if (!target.recursive && components.length > 1)
+ continue;
+ if (components.some((name) => excluded(target, name)))
+ continue;
+ return true;
+ }
+ return false;
+ }
+};
+async function anyUnreliable(paths) {
+ if (process.platform !== "linux" && process.platform !== "android")
+ return false;
+ for (const path5 of paths) {
+ for (const candidate of [path5, ...ancestorsOf(path5)]) {
+ const info = await statfs(candidate).catch(() => void 0);
+ if (info === void 0)
+ continue;
+ if (UNRELIABLE_FILE_SYSTEMS.has(info.type))
+ return true;
+ break;
+ }
+ }
+ return false;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/env/node.js
+var MAX_TIMEOUT_MS = 2147483647;
+var MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1e3;
+var EXIT_STDIO_GRACE_MS = 100;
+var SPILL_HIGH_WATER_MARK = 1024 * 1024;
+var BINARY_READ_CHUNK = 1024 * 1024;
+function resolveTimeoutMs(timeout) {
+ if (timeout === void 0)
+ return ok(void 0);
+ if (!Number.isFinite(timeout) || timeout <= 0) {
+ return err(new ExecutionError("timeout", "Invalid timeout: must be a finite number of seconds"));
+ }
+ const timeoutMs = timeout * 1e3;
+ if (timeoutMs > MAX_TIMEOUT_MS) {
+ return err(new ExecutionError("timeout", `Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`));
+ }
+ return ok(timeoutMs);
+}
+function resolvePath2(cwd, path5) {
+ let normalized = path5;
+ if (normalized === "~") {
+ normalized = homedir();
+ } else if (normalized.startsWith("~/") || process.platform === "win32" && normalized.startsWith("~\\")) {
+ normalized = join(homedir(), normalized.slice(2));
+ } else if (normalized.startsWith("file://")) {
+ try {
+ normalized = fileURLToPath(normalized);
+ } catch {
+ }
+ }
+ return isAbsolute(normalized) ? resolve2(normalized) : resolve2(cwd, normalized);
+}
+function fileKindFromStats(stats) {
+ if (stats.isFile())
+ return "file";
+ if (stats.isDirectory())
+ return "directory";
+ if (stats.isSymbolicLink())
+ return "symlink";
+ return void 0;
+}
+function fileInfoFromStats(path5, stats) {
+ const kind = fileKindFromStats(stats);
+ if (!kind)
+ return err(new FileError("invalid", "Unsupported file type", path5));
+ return ok({
+ name: basename2(path5),
+ path: path5,
+ kind,
+ size: stats.size,
+ mtimeMs: stats.mtimeMs
+ });
+}
+function isNodeError2(error) {
+ return error instanceof Error && "code" in error;
+}
+function toFileError(error, fallbackPath) {
+ if (error instanceof FileError)
+ return error;
+ const cause = toError3(error);
+ const nodeError = isNodeError2(error) ? error : void 0;
+ const path5 = typeof nodeError?.path === "string" ? nodeError.path : fallbackPath;
+ if (nodeError) {
+ const message = nodeError.message;
+ switch (nodeError.code) {
+ case "ABORT_ERR":
+ return new FileError("aborted", message, path5, cause);
+ case "ENOENT":
+ return new FileError("not_found", message, path5, cause);
+ case "EACCES":
+ case "EPERM":
+ return new FileError("permission_denied", message, path5, cause);
+ case "ENOTDIR":
+ return new FileError("not_directory", message, path5, cause);
+ case "EISDIR":
+ return new FileError("is_directory", message, path5, cause);
+ case "EINVAL":
+ return new FileError("invalid", message, path5, cause);
+ }
+ }
+ return new FileError("unknown", cause.message, path5, cause);
+}
+function abortResult(signal, path5) {
+ return signal?.aborted ? err(new FileError("aborted", "aborted", path5)) : void 0;
+}
+async function pathExists(path5) {
+ try {
+ await access(path5, constants.F_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+async function runCommand(command, args, timeoutMs) {
+ return await new Promise((resolve3) => {
+ let stdout = "";
+ let child;
+ try {
+ child = spawn(command, args, {
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true
+ });
+ } catch {
+ resolve3({ stdout: "", status: null });
+ return;
+ }
+ const timeout = setTimeout(() => {
+ if (child.pid)
+ killProcessTree(child.pid);
+ }, timeoutMs);
+ child.stdout?.setEncoding("utf8");
+ child.stdout?.on("data", (chunk) => {
+ stdout += chunk;
+ });
+ child.on("error", () => {
+ clearTimeout(timeout);
+ resolve3({ stdout: "", status: null });
+ });
+ child.on("close", (status) => {
+ clearTimeout(timeout);
+ resolve3({ stdout, status });
+ });
+ });
+}
+async function findBashOnPath() {
+ const result = process.platform === "win32" ? await runCommand("where", ["bash.exe"], 5e3) : await runCommand("which", ["bash"], 5e3);
+ if (result.status !== 0 || !result.stdout)
+ return null;
+ const firstMatch = result.stdout.trim().split(/\r?\n/)[0];
+ return firstMatch && await pathExists(firstMatch) ? firstMatch : null;
+}
+function isLegacyWslBashPath(path5) {
+ const normalized = path5.replace(/\//g, "\\").toLowerCase();
+ return /^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized);
+}
+function getBashShellConfig(shell) {
+ return isLegacyWslBashPath(shell) ? { shell, args: ["-s"], commandTransport: "stdin" } : { shell, args: ["-c"] };
+}
+async function getShellConfig(customShellPath) {
+ if (customShellPath) {
+ if (await pathExists(customShellPath)) {
+ return ok(getBashShellConfig(customShellPath));
+ }
+ return err(new ExecutionError("shell_unavailable", `Custom shell path not found: ${customShellPath}`));
+ }
+ if (process.platform === "win32") {
+ const candidates = [];
+ const programFiles = process.env.ProgramFiles;
+ if (programFiles)
+ candidates.push(`${programFiles}\\Git\\bin\\bash.exe`);
+ const programFilesX86 = process.env["ProgramFiles(x86)"];
+ if (programFilesX86)
+ candidates.push(`${programFilesX86}\\Git\\bin\\bash.exe`);
+ for (const candidate of candidates) {
+ if (await pathExists(candidate)) {
+ return ok(getBashShellConfig(candidate));
+ }
+ }
+ const bashOnPath2 = await findBashOnPath();
+ if (bashOnPath2) {
+ return ok(getBashShellConfig(bashOnPath2));
+ }
+ return err(new ExecutionError("shell_unavailable", `No bash shell found. Options:
+ 1. Install Git for Windows: https://git-scm.com/download/win
+ 2. Add your bash to PATH (Cygwin, MSYS2, etc.)
+ 3. Configure an explicit shellPath
+
+Searched Git Bash in:
+${candidates.map((path5) => ` ${path5}`).join("\n")}`));
+ }
+ if (await pathExists("/bin/bash")) {
+ return ok(getBashShellConfig("/bin/bash"));
+ }
+ const bashOnPath = await findBashOnPath();
+ if (bashOnPath) {
+ return ok(getBashShellConfig(bashOnPath));
+ }
+ return ok({ shell: "sh", args: ["-c"] });
+}
+function getShellEnv(baseEnv, extraEnv, inheritEnv = true) {
+ if (!inheritEnv)
+ return { ...extraEnv };
+ return {
+ ...process.env,
+ ...baseEnv,
+ ...extraEnv
+ };
+}
+function killProcessTree(pid) {
+ if (process.platform === "win32") {
+ try {
+ const child = spawn(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe"), ["/F", "/T", "/PID", String(pid)], {
+ stdio: "ignore",
+ detached: true,
+ windowsHide: true
+ });
+ child.once("error", () => {
+ });
+ } catch {
+ }
+ return;
+ }
+ try {
+ process.kill(-pid, "SIGKILL");
+ } catch {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ }
+ }
+}
+function waitForChildProcess(child, spillIsDraining) {
+ return new Promise((resolvePromise, reject) => {
+ let settled = false;
+ let exited = false;
+ let exitCode = null;
+ let exitSignal = null;
+ let postExitTimer;
+ let stdoutEnded = child.stdout === null;
+ let stderrEnded = child.stderr === null;
+ const cleanup = () => {
+ if (postExitTimer)
+ clearTimeout(postExitTimer);
+ child.removeListener("error", onError);
+ child.removeListener("exit", onExit);
+ child.removeListener("close", onClose);
+ child.stdout?.removeListener("end", onStdoutEnd);
+ child.stderr?.removeListener("end", onStderrEnd);
+ child.stdout?.removeListener("data", onData);
+ child.stderr?.removeListener("data", onData);
+ };
+ const finalize = () => {
+ if (settled)
+ return;
+ settled = true;
+ cleanup();
+ child.stdout?.destroy();
+ child.stderr?.destroy();
+ resolvePromise({ code: exitCode, signal: exitSignal });
+ };
+ const maybeFinalizeAfterExit = () => {
+ if (exited && stdoutEnded && stderrEnded)
+ finalize();
+ };
+ const armIdleTimer = () => {
+ if (postExitTimer)
+ clearTimeout(postExitTimer);
+ postExitTimer = setTimeout(() => {
+ if (spillIsDraining())
+ armIdleTimer();
+ else
+ finalize();
+ }, EXIT_STDIO_GRACE_MS);
+ };
+ const onData = () => {
+ if (exited && !settled)
+ armIdleTimer();
+ };
+ const onStdoutEnd = () => {
+ stdoutEnded = true;
+ maybeFinalizeAfterExit();
+ };
+ const onStderrEnd = () => {
+ stderrEnded = true;
+ maybeFinalizeAfterExit();
+ };
+ const onError = (error) => {
+ if (settled)
+ return;
+ settled = true;
+ cleanup();
+ reject(error);
+ };
+ const onExit = (code, signal) => {
+ exited = true;
+ exitCode = code;
+ exitSignal = signal;
+ maybeFinalizeAfterExit();
+ if (!settled)
+ armIdleTimer();
+ };
+ const onClose = (code, signal) => {
+ exitCode = code;
+ exitSignal = signal;
+ finalize();
+ };
+ child.stdout?.once("end", onStdoutEnd);
+ child.stderr?.once("end", onStderrEnd);
+ child.stdout?.on("data", onData);
+ child.stderr?.on("data", onData);
+ child.once("error", onError);
+ child.once("exit", onExit);
+ child.once("close", onClose);
+ });
+}
+var NodeTextLineReader = class {
+ file;
+ path;
+ decoder = new StreamDecoder();
+ chunk = new Uint8Array(64 * 1024);
+ byteOffset = 0;
+ buffered = "";
+ ended = false;
+ closed = false;
+ constructor(file, path5) {
+ this.file = file;
+ this.path = path5;
+ }
+ async readLine(context) {
+ const aborted = abortResult(context.abortSignal, this.path);
+ if (aborted)
+ return aborted;
+ if (this.closed)
+ return err(new FileError("invalid", "Text line reader is closed", this.path));
+ try {
+ while (true) {
+ const newline = this.buffered.indexOf("\n");
+ if (newline !== -1) {
+ const text = this.buffered.slice(0, newline);
+ this.buffered = this.buffered.slice(newline + 1);
+ return ok({ text, terminated: true });
+ }
+ if (this.ended) {
+ if (this.buffered.length === 0)
+ return ok(void 0);
+ const text = this.buffered;
+ this.buffered = "";
+ return ok({ text, terminated: false });
+ }
+ const { bytesRead } = await this.file.read(this.chunk, 0, this.chunk.length, this.byteOffset);
+ const afterReadAbort = abortResult(context.abortSignal, this.path);
+ if (afterReadAbort)
+ return afterReadAbort;
+ this.byteOffset += bytesRead;
+ if (bytesRead === 0) {
+ this.buffered += this.decoder.decode();
+ this.ended = true;
+ } else {
+ this.buffered += this.decoder.decode(this.chunk.subarray(0, bytesRead));
+ }
+ }
+ } catch (error) {
+ return err(toFileError(error, this.path));
+ }
+ }
+ async close(_context) {
+ if (this.closed)
+ return;
+ this.closed = true;
+ this.buffered = "";
+ try {
+ await this.file.close();
+ } catch {
+ }
+ }
+};
+function closedResult(what, path5) {
+ return err(new FileError("invalid", `${what} is closed`, path5));
+}
+var NodeBinaryReader = class {
+ file;
+ path;
+ closed = false;
+ constructor(file, path5) {
+ this.file = file;
+ this.path = path5;
+ }
+ async info(context) {
+ const aborted = abortResult(context.abortSignal, this.path);
+ if (aborted)
+ return aborted;
+ if (this.closed)
+ return closedResult("Binary reader", this.path);
+ try {
+ return fileInfoFromStats(this.path, await this.file.stat());
+ } catch (error) {
+ return err(toFileError(error, this.path));
+ }
+ }
+ async read(offset, length, context) {
+ const aborted = abortResult(context.abortSignal, this.path);
+ if (aborted)
+ return aborted;
+ if (this.closed)
+ return closedResult("Binary reader", this.path);
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0) {
+ return err(new FileError("invalid", "Offset and length must be non-negative safe integers", this.path));
+ }
+ const chunks = [];
+ let total = 0;
+ try {
+ while (total < length) {
+ const chunk = new Uint8Array(Math.min(length - total, BINARY_READ_CHUNK));
+ const { bytesRead } = await this.file.read(chunk, 0, chunk.length, offset + total);
+ const afterReadAbort = abortResult(context.abortSignal, this.path);
+ if (afterReadAbort)
+ return afterReadAbort;
+ if (bytesRead === 0)
+ break;
+ chunks.push(bytesRead === chunk.length ? chunk : chunk.subarray(0, bytesRead));
+ total += bytesRead;
+ }
+ } catch (error) {
+ return err(toFileError(error, this.path));
+ }
+ if (chunks.length === 1)
+ return ok(chunks[0]);
+ const bytes = new Uint8Array(total);
+ let position = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, position);
+ position += chunk.length;
+ }
+ return ok(bytes);
+ }
+ async scanLines(options, context) {
+ const aborted = abortResult(context.abortSignal, this.path);
+ if (aborted)
+ return aborted;
+ if (this.closed)
+ return closedResult("Binary reader", this.path);
+ let scanner;
+ try {
+ scanner = new LineScanner(options.startLine, options.endLine);
+ } catch {
+ return err(new FileError("invalid", "Invalid line range", this.path));
+ }
+ const chunk = new Uint8Array(64 * 1024);
+ try {
+ for (let position = 0; ; ) {
+ const { bytesRead } = await this.file.read(chunk, 0, chunk.length, position);
+ const afterReadAbort = abortResult(context.abortSignal, this.path);
+ if (afterReadAbort)
+ return afterReadAbort;
+ if (bytesRead === 0)
+ return ok(scanner.finish());
+ scanner.push(chunk.subarray(0, bytesRead));
+ position += bytesRead;
+ }
+ } catch (error) {
+ return err(toFileError(error, this.path));
+ }
+ }
+ async close(_context) {
+ if (this.closed)
+ return;
+ this.closed = true;
+ await this.file.close().catch(() => void 0);
+ }
+};
+var NodeDirReader = class {
+ dir;
+ path;
+ done = false;
+ closed = false;
+ constructor(dir, path5) {
+ this.dir = dir;
+ this.path = path5;
+ }
+ async next(maxEntries, context) {
+ const aborted = abortResult(context.abortSignal, this.path);
+ if (aborted)
+ return aborted;
+ if (this.closed)
+ return closedResult("Directory reader", this.path);
+ if (!Number.isSafeInteger(maxEntries) || maxEntries <= 0) {
+ return err(new FileError("invalid", "maxEntries must be a positive safe integer", this.path));
+ }
+ const entries = [];
+ try {
+ while (!this.done && entries.length < maxEntries) {
+ const entry = await this.dir.read();
+ if (entry === null) {
+ this.done = true;
+ break;
+ }
+ const loopAbort = abortResult(context.abortSignal, this.path);
+ if (loopAbort)
+ return loopAbort;
+ const entryPath = resolve2(this.path, entry.name);
+ let stats;
+ try {
+ stats = await lstat2(entryPath);
+ } catch (error) {
+ if (isNodeError2(error) && error.code === "ENOENT")
+ continue;
+ return err(toFileError(error, entryPath));
+ }
+ const info = fileInfoFromStats(entryPath, stats);
+ if (info.ok)
+ entries.push(info.value);
+ }
+ return ok({ entries, done: this.done });
+ } catch (error) {
+ return err(toFileError(error, this.path));
+ }
+ }
+ async close(_context) {
+ if (this.closed)
+ return;
+ this.closed = true;
+ await this.dir.close().catch(() => void 0);
+ }
+};
+function symlinkRefused(path5, cause) {
+ return new FileError("invalid", "Refusing to follow a symbolic link", path5, cause);
+}
+var NodeExecutionEnv = class {
+ /** Every local environment sees the same files. */
+ id = "node:local";
+ cwd;
+ shellPath;
+ shellEnv;
+ watchOptions;
+ activeChildPids = /* @__PURE__ */ new Set();
+ constructor(options) {
+ this.cwd = options.cwd;
+ this.shellPath = options.shellPath;
+ this.shellEnv = options.shellEnv;
+ this.watchOptions = options.watch ?? {};
+ }
+ async watch(targets, onChange, context) {
+ const aborted = abortResult(context.abortSignal);
+ if (aborted)
+ return aborted;
+ try {
+ const watcher = await NodeFileWatcher.open(targets, (path5) => resolvePath2(this.cwd, path5), onChange, this.watchOptions);
+ const afterOpenAbort = abortResult(context.abortSignal);
+ if (afterOpenAbort) {
+ await watcher.close(context);
+ return afterOpenAbort;
+ }
+ return ok(watcher);
+ } catch (error) {
+ return err(toFileError(error));
+ }
+ }
+ async absolutePath(path5, _context) {
+ return ok(resolvePath2(this.cwd, path5));
+ }
+ async joinPath(parts2, _context) {
+ return ok(join(...parts2));
+ }
+ async exec(command, options, context) {
+ const signal = context.abortSignal;
+ if (signal?.aborted)
+ return err(new ExecutionError("aborted", "aborted"));
+ const timeoutMsResult = resolveTimeoutMs(options?.timeout);
+ if (!timeoutMsResult.ok)
+ return err(timeoutMsResult.error);
+ const timeoutMs = timeoutMsResult.value;
+ const cwd = options?.cwd ? resolvePath2(this.cwd, options.cwd) : this.cwd;
+ let program;
+ let args;
+ let stdinCommand;
+ if (typeof command === "string") {
+ const shellConfig = await getShellConfig(this.shellPath);
+ if (!shellConfig.ok)
+ return shellConfig;
+ const commandFromStdin = shellConfig.value.commandTransport === "stdin";
+ program = shellConfig.value.shell;
+ args = commandFromStdin ? shellConfig.value.args : [...shellConfig.value.args, command];
+ stdinCommand = commandFromStdin ? command : void 0;
+ } else {
+ const [first, ...rest] = command;
+ if (first === void 0)
+ return err(new ExecutionError("spawn_error", "Empty argv: no program to run"));
+ program = first;
+ args = rest;
+ }
+ try {
+ await access(cwd, constants.F_OK);
+ } catch (error) {
+ const cause = toError3(error);
+ return err(new ExecutionError("spawn_error", `Working directory does not exist: ${cwd}
+Cannot execute bash commands.`, cause));
+ }
+ return await new Promise((resolvePromise) => {
+ let settled = false;
+ let timedOut = false;
+ let callbackError;
+ let spillError;
+ let child;
+ let timeoutId;
+ const spillPrefix = [];
+ let spillPath;
+ const spillQueue = [];
+ let spillStart;
+ let spillStream;
+ let spillBackpressured = false;
+ const onAbort = () => {
+ if (child?.pid)
+ killProcessTree(child.pid);
+ };
+ const failCallback = (error) => {
+ if (callbackError !== void 0)
+ return;
+ const cause = toError3(error);
+ callbackError = new ExecutionError("callback_error", cause.message, cause);
+ onAbort();
+ };
+ const stdoutDecoder = new StreamDecoder();
+ const stderrDecoder = new StreamDecoder();
+ const emit = (text, stream3) => {
+ if (settled || text === "" || options?.onOutput === void 0 || callbackError !== void 0)
+ return;
+ try {
+ options.onOutput(text, context, { stream: stream3 });
+ } catch (error) {
+ failCallback(error);
+ }
+ };
+ let seenBytes = 0;
+ let seenNewlines = 0;
+ const settle2 = (result) => {
+ if (settled)
+ return;
+ settled = true;
+ if (timeoutId)
+ clearTimeout(timeoutId);
+ if (signal)
+ signal.removeEventListener("abort", onAbort);
+ if (child?.pid)
+ this.activeChildPids.delete(child.pid);
+ resolvePromise(result);
+ };
+ const pauseOutput = () => {
+ child?.stdout?.pause();
+ child?.stderr?.pause();
+ };
+ const resumeOutput = () => {
+ if (callbackError || spillError || timedOut || signal?.aborted || spillBackpressured)
+ return;
+ child?.stdout?.resume();
+ child?.stderr?.resume();
+ };
+ const failSpill = (error) => {
+ if (spillError !== void 0)
+ return;
+ const cause = toError3(error);
+ spillError = new ExecutionError("unknown", `Failed to preserve complete shell output: ${cause.message}`, cause);
+ spillBackpressured = false;
+ onAbort();
+ };
+ const writeSpill = (chunk) => {
+ if (spillStream === void 0 || chunk.length === 0)
+ return;
+ if (spillStream.write(chunk) || spillBackpressured)
+ return;
+ spillBackpressured = true;
+ pauseOutput();
+ spillStream.once("drain", () => {
+ spillBackpressured = false;
+ resumeOutput();
+ });
+ };
+ const startSpill = (chunk) => {
+ if (spillStream !== void 0) {
+ writeSpill(chunk);
+ return;
+ }
+ spillQueue.push(chunk);
+ if (spillStart !== void 0)
+ return;
+ pauseOutput();
+ spillStart = (async () => {
+ const created = await this.createTempFile({ prefix: "pi-output-", suffix: ".log" }, context);
+ if (!created.ok)
+ throw created.error;
+ spillPath = created.value;
+ spillStream = createWriteStream(spillPath, { flags: "a", highWaterMark: SPILL_HIGH_WATER_MARK });
+ spillStream.on("error", failSpill);
+ for (const queued2 of spillQueue)
+ writeSpill(queued2);
+ spillQueue.length = 0;
+ })().catch(failSpill).finally(resumeOutput);
+ };
+ const finishSpill = async () => {
+ await spillStart;
+ const stream3 = spillStream;
+ if (stream3 === void 0 || spillError !== void 0 || stream3.destroyed)
+ return;
+ await new Promise((resolveFinish) => {
+ stream3.once("error", () => resolveFinish());
+ stream3.once("finish", resolveFinish);
+ stream3.end();
+ });
+ };
+ try {
+ child = spawn(program, args, {
+ cwd,
+ detached: process.platform !== "win32",
+ env: getShellEnv(this.shellEnv, options?.env, options?.inheritEnv),
+ stdio: [stdinCommand === void 0 ? "ignore" : "pipe", "pipe", "pipe"],
+ windowsHide: true
+ });
+ if (child.pid)
+ this.activeChildPids.add(child.pid);
+ if (stdinCommand !== void 0) {
+ child.stdin?.on("error", () => {
+ });
+ child.stdin?.end(stdinCommand);
+ }
+ } catch (error) {
+ const cause = toError3(error);
+ settle2(err(new ExecutionError("spawn_error", cause.message, cause)));
+ return;
+ }
+ timeoutId = timeoutMs === void 0 ? void 0 : setTimeout(() => {
+ timedOut = true;
+ onAbort();
+ }, timeoutMs);
+ if (signal) {
+ if (signal.aborted)
+ onAbort();
+ else
+ signal.addEventListener("abort", onAbort, { once: true });
+ }
+ const feed = (source, decoder2) => (chunk) => {
+ emit(decoder2.decode(chunk), source);
+ const spill = options?.spill;
+ if (spill === void 0 || chunk.length === 0)
+ return;
+ if (spillStart !== void 0) {
+ startSpill(chunk);
+ return;
+ }
+ seenBytes += chunk.length;
+ for (let index3 = chunk.indexOf(10); index3 !== -1; index3 = chunk.indexOf(10, index3 + 1))
+ seenNewlines++;
+ const lines2 = seenNewlines + (chunk[chunk.length - 1] === 10 ? 0 : 1);
+ if (seenBytes <= spill.afterBytes && lines2 <= spill.afterLines) {
+ spillPrefix.push(chunk);
+ return;
+ }
+ for (const prefix of spillPrefix)
+ startSpill(prefix);
+ spillPrefix.length = 0;
+ startSpill(chunk);
+ };
+ child.stdout?.on("data", feed("stdout", stdoutDecoder));
+ child.stderr?.on("data", feed("stderr", stderrDecoder));
+ void waitForChildProcess(child, () => spillError === void 0 && spillStart !== void 0 && (spillStream === void 0 || spillBackpressured)).then(async ({ code, signal: exitSignal }) => {
+ await finishSpill();
+ emit(stdoutDecoder.decode(), "stdout");
+ emit(stderrDecoder.decode(), "stderr");
+ if (callbackError) {
+ settle2(err(callbackError));
+ return;
+ }
+ const interrupted = timedOut ? new ExecutionError("timeout", `timeout:${options?.timeout}`) : signal?.aborted ? new ExecutionError("aborted", "aborted") : void 0;
+ if (interrupted !== void 0) {
+ if (spillPath !== void 0)
+ interrupted.spillPath = spillPath;
+ settle2(err(interrupted));
+ return;
+ }
+ if (spillError) {
+ settle2(err(spillError));
+ return;
+ }
+ const exitCode = code ?? (exitSignal ? 128 + (osConstants.signals[exitSignal] ?? 0) : 1);
+ settle2(ok({ exitCode, ...spillPath === void 0 ? {} : { spillPath } }));
+ }, (error) => settle2(err(new ExecutionError("spawn_error", error.message, error))));
+ });
+ }
+ async openTextLineReader(path5, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const aborted = abortResult(context.abortSignal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ const file = await openFile(resolved, "r");
+ const afterOpenAbort = abortResult(context.abortSignal, resolved);
+ if (afterOpenAbort) {
+ await file.close().catch(() => void 0);
+ return afterOpenAbort;
+ }
+ return ok(new NodeTextLineReader(file, resolved));
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async readTextFile(path5, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const signal = context.abortSignal;
+ const aborted = abortResult(signal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ return ok(await readFile2(resolved, { encoding: "utf8", signal }));
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async readTextLines(path5, options, context) {
+ if (options?.maxLines !== void 0 && options.maxLines <= 0)
+ return ok([]);
+ const opened = await this.openTextLineReader(path5, context);
+ if (!opened.ok)
+ return opened;
+ const lines2 = [];
+ try {
+ while (options?.maxLines === void 0 || lines2.length < options.maxLines) {
+ const line = await opened.value.readLine(context);
+ if (!line.ok)
+ return line;
+ if (line.value === void 0)
+ break;
+ lines2.push(line.value.text);
+ }
+ return ok(lines2);
+ } finally {
+ await opened.value.close(context);
+ }
+ }
+ async readBinaryFile(path5, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const signal = context.abortSignal;
+ const aborted = abortResult(signal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ return ok(await readFile2(resolved, { signal }));
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async openBinaryReader(path5, options, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const aborted = abortResult(context.abortSignal, resolved);
+ if (aborted)
+ return aborted;
+ const noFollow = options?.noFollow === true;
+ let file;
+ try {
+ let flags = constants.O_RDONLY;
+ if (process.platform === "win32") {
+ if (noFollow && (await lstat2(resolved)).isSymbolicLink())
+ return err(symlinkRefused(resolved));
+ } else {
+ flags |= constants.O_NONBLOCK;
+ if (noFollow)
+ flags |= constants.O_NOFOLLOW;
+ }
+ file = await openFile(resolved, flags);
+ const stats = await file.stat();
+ if (!stats.isFile()) {
+ await file.close().catch(() => void 0);
+ return err(stats.isDirectory() ? new FileError("is_directory", "EISDIR: illegal operation on a directory, read", resolved) : new FileError("invalid", "Not a regular file", resolved));
+ }
+ const afterOpenAbort = abortResult(context.abortSignal, resolved);
+ if (afterOpenAbort) {
+ await file.close().catch(() => void 0);
+ return afterOpenAbort;
+ }
+ return ok(new NodeBinaryReader(file, resolved));
+ } catch (error) {
+ await file?.close().catch(() => void 0);
+ if (noFollow && isNodeError2(error) && (error.code === "ELOOP" || error.code === "EMLINK")) {
+ return err(symlinkRefused(resolved, toError3(error)));
+ }
+ return err(toFileError(error, resolved));
+ }
+ }
+ async writeFile(path5, content, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const signal = context.abortSignal;
+ const aborted = abortResult(signal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ await mkdir(resolve2(resolved, ".."), { recursive: true });
+ const afterMkdirAbort = abortResult(signal, resolved);
+ if (afterMkdirAbort)
+ return afterMkdirAbort;
+ await writeFile(resolved, content, { signal });
+ return ok(void 0);
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async appendFile(path5, content, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const signal = context.abortSignal;
+ const aborted = abortResult(signal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ await mkdir(resolve2(resolved, ".."), { recursive: true });
+ const afterMkdirAbort = abortResult(signal, resolved);
+ if (afterMkdirAbort)
+ return afterMkdirAbort;
+ await appendFile(resolved, content);
+ const afterAppendAbort = abortResult(signal, resolved);
+ return afterAppendAbort ?? ok(void 0);
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async truncateFile(path5, size, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const signal = context.abortSignal;
+ const aborted = abortResult(signal, resolved);
+ if (aborted)
+ return aborted;
+ if (!Number.isSafeInteger(size) || size < 0) {
+ return err(new FileError("invalid", "File size must be a non-negative safe integer", resolved));
+ }
+ let file;
+ try {
+ file = await openFile(resolved, "r+");
+ await file.truncate(size);
+ const afterTruncateAbort = abortResult(signal, resolved);
+ return afterTruncateAbort ?? ok(void 0);
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ } finally {
+ await file?.close().catch(() => void 0);
+ }
+ }
+ async flushFile(path5, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const signal = context.abortSignal;
+ const aborted = abortResult(signal, resolved);
+ if (aborted)
+ return aborted;
+ let file;
+ try {
+ file = await openFile(resolved, "r+");
+ if ((await file.stat()).isDirectory())
+ return err(new FileError("is_directory", "Is a directory", resolved));
+ await file.sync();
+ const afterSyncAbort = abortResult(signal, resolved);
+ return afterSyncAbort ?? ok(void 0);
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ } finally {
+ await file?.close().catch(() => void 0);
+ }
+ }
+ async renameFile(sourcePath, destinationPath, context) {
+ const source = resolvePath2(this.cwd, sourcePath);
+ const destination = resolvePath2(this.cwd, destinationPath);
+ const aborted = abortResult(context.abortSignal, destination);
+ if (aborted)
+ return aborted;
+ try {
+ await rename(source, destination);
+ return ok(void 0);
+ } catch (error) {
+ return err(toFileError(error, source));
+ }
+ }
+ async fileInfo(path5, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const aborted = abortResult(context.abortSignal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ return fileInfoFromStats(resolved, await lstat2(resolved));
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async listDir(path5, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const signal = context.abortSignal;
+ const aborted = abortResult(signal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ const entries = await readdir2(resolved, { withFileTypes: true });
+ const infos = [];
+ for (const entry of entries) {
+ const loopAbort = abortResult(signal, resolved);
+ if (loopAbort)
+ return loopAbort;
+ const entryPath = resolve2(resolved, entry.name);
+ try {
+ const info = fileInfoFromStats(entryPath, await lstat2(entryPath));
+ if (info.ok)
+ infos.push(info.value);
+ } catch (error) {
+ return err(toFileError(error, entryPath));
+ }
+ }
+ return ok(infos);
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async openDirReader(path5, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const aborted = abortResult(context.abortSignal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ const dir = await opendir(resolved);
+ const afterOpenAbort = abortResult(context.abortSignal, resolved);
+ if (afterOpenAbort) {
+ await dir.close().catch(() => void 0);
+ return afterOpenAbort;
+ }
+ return ok(new NodeDirReader(dir, resolved));
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async canonicalPath(path5, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const aborted = abortResult(context.abortSignal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ return ok(await realpath(resolved));
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async exists(path5, context) {
+ const result = await this.fileInfo(path5, context);
+ if (result.ok)
+ return ok(true);
+ if (result.error.code === "not_found")
+ return ok(false);
+ return err(result.error);
+ }
+ async createDir(path5, options, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const aborted = abortResult(context.abortSignal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ await mkdir(resolved, { recursive: options?.recursive ?? true });
+ return ok(void 0);
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async remove(path5, options, context) {
+ const resolved = resolvePath2(this.cwd, path5);
+ const aborted = abortResult(context.abortSignal, resolved);
+ if (aborted)
+ return aborted;
+ try {
+ await rm(resolved, { recursive: options?.recursive ?? false, force: options?.force ?? false });
+ return ok(void 0);
+ } catch (error) {
+ return err(toFileError(error, resolved));
+ }
+ }
+ async createTempDir(prefix, context) {
+ const aborted = abortResult(context.abortSignal);
+ if (aborted)
+ return aborted;
+ try {
+ prefix ??= "tmp-";
+ return ok(await mkdtemp(join(tmpdir(), prefix)));
+ } catch (error) {
+ return err(toFileError(error));
+ }
+ }
+ async createTempFile(options, context) {
+ const dir = await this.createTempDir("tmp-", context);
+ if (!dir.ok)
+ return dir;
+ const filePath = join(dir.value, `${options?.prefix ?? ""}${randomUUID()}${options?.suffix ?? ""}`);
+ try {
+ await writeFile(filePath, "");
+ return ok(filePath);
+ } catch (error) {
+ return err(toFileError(error, filePath));
+ }
+ }
+ async cleanup(_context) {
+ for (const pid of this.activeChildPids)
+ killProcessTree(pid);
+ this.activeChildPids.clear();
+ }
+};
+
+// node_modules/typebox/build/typebox.mjs
+var typebox_exports = {};
+__export(typebox_exports, {
+ Any: () => Any,
+ Array: () => _Array_,
+ BigInt: () => BigInt2,
+ Boolean: () => Boolean2,
+ Call: () => Call2,
+ Capitalize: () => Capitalize,
+ Codec: () => Codec,
+ Conditional: () => Conditional,
+ Constructor: () => Constructor,
+ ConstructorParameters: () => ConstructorParameters,
+ Cyclic: () => Cyclic,
+ Decode: () => Decode2,
+ DecodeBuilder: () => DecodeBuilder,
+ Dependent: () => Dependent,
+ Encode: () => Encode2,
+ EncodeBuilder: () => EncodeBuilder,
+ Enum: () => Enum,
+ Evaluate: () => Evaluate2,
+ Exclude: () => Exclude,
+ Extends: () => Extends,
+ ExtendsResult: () => result_exports,
+ Extract: () => Extract,
+ Function: () => _Function_,
+ Generic: () => Generic,
+ Identifier: () => Identifier,
+ Immutable: () => Immutable,
+ Index: () => Index,
+ Infer: () => Infer,
+ InstanceType: () => InstanceType,
+ Instantiate: () => Instantiate,
+ Integer: () => Integer,
+ Interface: () => Interface,
+ Intersect: () => Intersect,
+ IsAny: () => IsAny,
+ IsArray: () => IsArray3,
+ IsBigInt: () => IsBigInt3,
+ IsBoolean: () => IsBoolean4,
+ IsCall: () => IsCall,
+ IsCodec: () => IsCodec,
+ IsConstructor: () => IsConstructor3,
+ IsCyclic: () => IsCyclic,
+ IsDependent: () => IsDependent,
+ IsEnum: () => IsEnum2,
+ IsEnumValue: () => IsEnumValue,
+ IsFunction: () => IsFunction3,
+ IsGeneric: () => IsGeneric,
+ IsIdentifier: () => IsIdentifier2,
+ IsImmutable: () => IsImmutable,
+ IsInfer: () => IsInfer,
+ IsInteger: () => IsInteger3,
+ IsIntersect: () => IsIntersect,
+ IsKind: () => IsKind,
+ IsLiteral: () => IsLiteral,
+ IsNever: () => IsNever,
+ IsNull: () => IsNull3,
+ IsNumber: () => IsNumber4,
+ IsObject: () => IsObject3,
+ IsOptional: () => IsOptional,
+ IsParameter: () => IsParameter,
+ IsReadonly: () => IsReadonly,
+ IsRecord: () => IsRecord,
+ IsRef: () => IsRef2,
+ IsRefine: () => IsRefine2,
+ IsRest: () => IsRest,
+ IsSchema: () => IsSchema2,
+ IsString: () => IsString4,
+ IsSymbol: () => IsSymbol3,
+ IsTemplateLiteral: () => IsTemplateLiteral,
+ IsThis: () => IsThis,
+ IsTuple: () => IsTuple,
+ IsUndefined: () => IsUndefined3,
+ IsUnion: () => IsUnion,
+ IsUnknown: () => IsUnknown,
+ IsUnsafe: () => IsUnsafe,
+ IsVoid: () => IsVoid,
+ KeyOf: () => KeyOf2,
+ Literal: () => Literal,
+ Lowercase: () => Lowercase,
+ Mapped: () => Mapped,
+ Module: () => Module2,
+ Never: () => Never,
+ NonNullable: () => NonNullable,
+ Null: () => Null,
+ Number: () => Number2,
+ Object: () => _Object_,
+ Omit: () => Omit,
+ Optional: () => Optional,
+ Parameter: () => Parameter,
+ Parameters: () => Parameters,
+ Partial: () => Partial,
+ Pick: () => Pick,
+ Readonly: () => Readonly,
+ ReadonlyObject: () => ReadonlyObject,
+ ReadonlyType: () => ReadonlyType,
+ Record: () => Record,
+ RecordKey: () => RecordKey,
+ RecordPattern: () => RecordPattern,
+ RecordValue: () => RecordValue,
+ Ref: () => Ref2,
+ Refine: () => Refine,
+ Required: () => Required,
+ Rest: () => Rest,
+ ReturnType: () => ReturnType,
+ Script: () => Script2,
+ String: () => String2,
+ Symbol: () => Symbol2,
+ TemplateLiteral: () => TemplateLiteral2,
+ This: () => This,
+ Tuple: () => Tuple,
+ Uncapitalize: () => Uncapitalize,
+ Undefined: () => Undefined,
+ Union: () => Union,
+ Unknown: () => Unknown,
+ Unsafe: () => Unsafe,
+ Uppercase: () => Uppercase,
+ Void: () => Void,
+ With: () => With2
+});
+
+// node_modules/@earendil-works/pi-durable/dist/tools/env.js
+function requireEnv(api) {
+ if (api.env === void 0)
+ throw new Error("No execution environment is configured");
+ return api.env;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/bash.js
+var MAX_TIMEOUT_SECONDS2 = 2147483647 / 1e3;
+var bashSchema = typebox_exports.Object({
+ command: typebox_exports.String({ description: "Bash command to execute" }),
+ timeout: typebox_exports.Optional(typebox_exports.Number({ description: "Timeout in seconds (optional, no default timeout)" }))
+});
+function validateTimeout(timeout) {
+ if (timeout === void 0)
+ return;
+ if (!Number.isFinite(timeout) || timeout <= 0) {
+ throw new Error("Invalid timeout: must be a finite number of seconds");
+ }
+ if (timeout > MAX_TIMEOUT_SECONDS2) {
+ throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS2} seconds`);
+ }
+}
+function createBashTool(options) {
+ return defineTool({
+ name: "bash",
+ description: `Execute a bash command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,
+ parameters: bashSchema,
+ outputLimits: { retain: "tail" },
+ async execute(args, api, context) {
+ const { command, timeout } = args;
+ validateTimeout(timeout);
+ const env = requireEnv(api);
+ const execution = {
+ command: options?.commandPrefix ? `${options.commandPrefix}
+${command}` : command,
+ cwd: env.cwd,
+ env: {},
+ inheritEnv: true
+ };
+ await options?.prepare?.(execution, api, context);
+ const result = await env.exec(execution.command, {
+ cwd: execution.cwd,
+ env: execution.env,
+ inheritEnv: execution.inheritEnv,
+ ...timeout === void 0 ? {} : { timeout },
+ onOutput: (text, _context, info) => api.output(text, info.skipped),
+ spill: { afterBytes: DEFAULT_MAX_BYTES, afterLines: DEFAULT_MAX_LINES },
+ // An environment may then omit output outside the retained tail and report the omission.
+ ...api.outputWindow === void 0 ? {} : { window: api.outputWindow }
+ }, context);
+ const spillPath = result.ok ? result.value.spillPath : result.error.spillPath;
+ if (spillPath !== void 0) {
+ api.diagnostic({ severity: "info", code: "full_output", message: `Full output: ${spillPath}` });
+ }
+ if (!result.ok) {
+ if (result.error.code === "aborted" && context.abortSignal?.aborted)
+ throw result.error;
+ if (result.error.code === "timeout")
+ throw new Error(`Command timed out after ${timeout} seconds`);
+ if (result.error.code === "aborted")
+ throw new Error("Command aborted");
+ throw result.error;
+ }
+ if (result.value.exitCode !== 0)
+ throw new Error(`Command exited with code ${result.value.exitCode}`);
+ return {};
+ }
+ });
+}
+
+// node_modules/diff/libesm/diff/base.js
+var Diff2 = class {
+ diff(oldStr, newStr, options = {}) {
+ let callback;
+ if (typeof options === "function") {
+ callback = options;
+ options = {};
+ } else if ("callback" in options) {
+ callback = options.callback;
+ }
+ const oldString = this.castInput(oldStr, options);
+ const newString = this.castInput(newStr, options);
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
+ }
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
+ var _a5;
+ const done = (value) => {
+ value = this.postProcess(value, options);
+ if (callback) {
+ setTimeout(function() {
+ callback(value);
+ }, 0);
+ return void 0;
+ } else {
+ return value;
+ }
+ };
+ const newLen = newTokens.length, oldLen = oldTokens.length;
+ let editLength = 1;
+ let maxEditLength = newLen + oldLen;
+ if (options.maxEditLength != null) {
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
+ }
+ const maxExecutionTime = (_a5 = options.timeout) !== null && _a5 !== void 0 ? _a5 : Infinity;
+ const abortAfterTimestamp = Date.now() + maxExecutionTime;
+ const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
+ let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
+ if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
+ return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
+ }
+ let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
+ const execEditLength = () => {
+ for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
+ let basePath;
+ const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
+ if (removePath) {
+ bestPath[diagonalPath - 1] = void 0;
+ }
+ let canAdd = false;
+ if (addPath) {
+ const addPathNewPos = addPath.oldPos - diagonalPath;
+ canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
+ }
+ const canRemove = removePath && removePath.oldPos + 1 < oldLen;
+ if (!canAdd && !canRemove) {
+ bestPath[diagonalPath] = void 0;
+ continue;
+ }
+ if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
+ basePath = this.addToPath(addPath, true, false, 0, options);
+ } else {
+ basePath = this.addToPath(removePath, false, true, 1, options);
+ }
+ newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
+ if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
+ return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
+ } else {
+ bestPath[diagonalPath] = basePath;
+ if (basePath.oldPos + 1 >= oldLen) {
+ maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
+ }
+ if (newPos + 1 >= newLen) {
+ minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
+ }
+ }
+ }
+ editLength++;
+ };
+ if (callback) {
+ (function exec() {
+ setTimeout(function() {
+ if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
+ return callback(void 0);
+ }
+ if (!execEditLength()) {
+ exec();
+ }
+ }, 0);
+ })();
+ } else {
+ while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
+ const ret = execEditLength();
+ if (ret) {
+ return ret;
+ }
+ }
+ }
+ }
+ addToPath(path5, added, removed, oldPosInc, options) {
+ const last = path5.lastComponent;
+ if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
+ return {
+ oldPos: path5.oldPos + oldPosInc,
+ lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
+ };
+ } else {
+ return {
+ oldPos: path5.oldPos + oldPosInc,
+ lastComponent: { count: 1, added, removed, previousComponent: last }
+ };
+ }
+ }
+ extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
+ const newLen = newTokens.length, oldLen = oldTokens.length;
+ let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
+ newPos++;
+ oldPos++;
+ commonCount++;
+ if (options.oneChangePerToken) {
+ basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
+ }
+ }
+ if (commonCount && !options.oneChangePerToken) {
+ basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
+ }
+ basePath.oldPos = oldPos;
+ return newPos;
+ }
+ equals(left, right, options) {
+ if (options.comparator) {
+ return options.comparator(left, right);
+ } else {
+ return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
+ }
+ }
+ removeEmpty(array) {
+ const ret = [];
+ for (let i = 0; i < array.length; i++) {
+ if (array[i]) {
+ ret.push(array[i]);
+ }
+ }
+ return ret;
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ castInput(value, options) {
+ return value;
+ }
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ tokenize(value, options) {
+ return Array.from(value);
+ }
+ join(chars) {
+ return chars.join("");
+ }
+ postProcess(changeObjects, options) {
+ return changeObjects;
+ }
+ get useLongestToken() {
+ return false;
+ }
+ buildValues(lastComponent, newTokens, oldTokens) {
+ const components = [];
+ let nextComponent;
+ while (lastComponent) {
+ components.push(lastComponent);
+ nextComponent = lastComponent.previousComponent;
+ delete lastComponent.previousComponent;
+ lastComponent = nextComponent;
+ }
+ components.reverse();
+ const componentLen = components.length;
+ let componentPos = 0, newPos = 0, oldPos = 0;
+ for (; componentPos < componentLen; componentPos++) {
+ const component = components[componentPos];
+ if (!component.removed) {
+ if (!component.added && this.useLongestToken) {
+ let value = newTokens.slice(newPos, newPos + component.count);
+ value = value.map(function(value2, i) {
+ const oldValue = oldTokens[oldPos + i];
+ return oldValue.length > value2.length ? oldValue : value2;
+ });
+ component.value = this.join(value);
+ } else {
+ component.value = this.join(newTokens.slice(newPos, newPos + component.count));
+ }
+ newPos += component.count;
+ if (!component.added) {
+ oldPos += component.count;
+ }
+ } else {
+ component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
+ oldPos += component.count;
+ }
+ }
+ return components;
+ }
+};
+
+// node_modules/diff/libesm/diff/line.js
+var LineDiff = class extends Diff2 {
+ constructor() {
+ super(...arguments);
+ this.tokenize = tokenize;
+ }
+ equals(left, right, options) {
+ if (options.ignoreWhitespace) {
+ if (!options.newlineIsToken || !left.includes("\n")) {
+ left = left.trim();
+ }
+ if (!options.newlineIsToken || !right.includes("\n")) {
+ right = right.trim();
+ }
+ } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
+ if (left.endsWith("\n")) {
+ left = left.slice(0, -1);
+ }
+ if (right.endsWith("\n")) {
+ right = right.slice(0, -1);
+ }
+ }
+ return super.equals(left, right, options);
+ }
+};
+var lineDiff = new LineDiff();
+function diffLines(oldStr, newStr, options) {
+ return lineDiff.diff(oldStr, newStr, options);
+}
+function tokenize(value, options) {
+ if (options.stripTrailingCr) {
+ value = value.replace(/\r\n/g, "\n");
+ }
+ const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
+ if (!linesAndNewlines[linesAndNewlines.length - 1]) {
+ linesAndNewlines.pop();
+ }
+ for (let i = 0; i < linesAndNewlines.length; i++) {
+ const line = linesAndNewlines[i];
+ if (i % 2 && !options.newlineIsToken) {
+ retLines[retLines.length - 1] += line;
+ } else {
+ retLines.push(line);
+ }
+ }
+ return retLines;
+}
+
+// node_modules/diff/libesm/patch/create.js
+var INCLUDE_HEADERS = {
+ includeIndex: true,
+ includeUnderline: true,
+ includeFileHeaders: true
+};
+var FILE_HEADERS_ONLY = {
+ includeIndex: false,
+ includeUnderline: false,
+ includeFileHeaders: true
+};
+function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+ let optionsObj;
+ if (!options) {
+ optionsObj = {};
+ } else if (typeof options === "function") {
+ optionsObj = { callback: options };
+ } else {
+ optionsObj = options;
+ }
+ if (typeof optionsObj.context === "undefined") {
+ optionsObj.context = 4;
+ }
+ const context = optionsObj.context;
+ if (optionsObj.newlineIsToken) {
+ throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
+ }
+ if (!optionsObj.callback) {
+ return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
+ } else {
+ const { callback } = optionsObj;
+ diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {
+ const patch = diffLinesResultToPatch(diff);
+ callback(patch);
+ } }));
+ }
+ function diffLinesResultToPatch(diff) {
+ if (!diff) {
+ return;
+ }
+ diff.push({ value: "", lines: [] });
+ function contextLines(lines2) {
+ return lines2.map(function(entry) {
+ return " " + entry;
+ });
+ }
+ const hunks = [];
+ let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
+ for (let i = 0; i < diff.length; i++) {
+ const current = diff[i], lines2 = current.lines || splitLines(current.value);
+ current.lines = lines2;
+ if (current.added || current.removed) {
+ if (!oldRangeStart) {
+ const prev = diff[i - 1];
+ oldRangeStart = oldLine;
+ newRangeStart = newLine;
+ if (prev) {
+ curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];
+ oldRangeStart -= curRange.length;
+ newRangeStart -= curRange.length;
+ }
+ }
+ for (const line of lines2) {
+ curRange.push((current.added ? "+" : "-") + line);
+ }
+ if (current.added) {
+ newLine += lines2.length;
+ } else {
+ oldLine += lines2.length;
+ }
+ } else {
+ if (oldRangeStart) {
+ if (lines2.length <= context * 2 && i < diff.length - 2) {
+ for (const line of contextLines(lines2)) {
+ curRange.push(line);
+ }
+ } else {
+ const contextSize = Math.min(lines2.length, context);
+ for (const line of contextLines(lines2.slice(0, contextSize))) {
+ curRange.push(line);
+ }
+ const hunk = {
+ oldStart: oldRangeStart,
+ oldLines: oldLine - oldRangeStart + contextSize,
+ newStart: newRangeStart,
+ newLines: newLine - newRangeStart + contextSize,
+ lines: curRange
+ };
+ hunks.push(hunk);
+ oldRangeStart = 0;
+ newRangeStart = 0;
+ curRange = [];
+ }
+ }
+ oldLine += lines2.length;
+ newLine += lines2.length;
+ }
+ }
+ for (const hunk of hunks) {
+ for (let i = 0; i < hunk.lines.length; i++) {
+ if (hunk.lines[i].endsWith("\n")) {
+ hunk.lines[i] = hunk.lines[i].slice(0, -1);
+ } else {
+ hunk.lines.splice(i + 1, 0, "\\ No newline at end of file");
+ i++;
+ }
+ }
+ }
+ return {
+ oldFileName,
+ newFileName,
+ oldHeader,
+ newHeader,
+ hunks
+ };
+ }
+}
+function formatPatch(patch, headerOptions) {
+ if (!headerOptions) {
+ headerOptions = INCLUDE_HEADERS;
+ }
+ if (Array.isArray(patch)) {
+ if (patch.length > 1 && !headerOptions.includeFileHeaders) {
+ throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");
+ }
+ return patch.map((p) => formatPatch(p, headerOptions)).join("\n");
+ }
+ const ret = [];
+ if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) {
+ ret.push("Index: " + patch.oldFileName);
+ }
+ if (headerOptions.includeUnderline) {
+ ret.push("===================================================================");
+ }
+ if (headerOptions.includeFileHeaders) {
+ ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader));
+ ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader));
+ }
+ for (let i = 0; i < patch.hunks.length; i++) {
+ const hunk = patch.hunks[i];
+ if (hunk.oldLines === 0) {
+ hunk.oldStart -= 1;
+ }
+ if (hunk.newLines === 0) {
+ hunk.newStart -= 1;
+ }
+ ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
+ for (const line of hunk.lines) {
+ ret.push(line);
+ }
+ }
+ return ret.join("\n") + "\n";
+}
+function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
+ if (typeof options === "function") {
+ options = { callback: options };
+ }
+ if (!(options === null || options === void 0 ? void 0 : options.callback)) {
+ const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
+ if (!patchObj) {
+ return;
+ }
+ return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions);
+ } else {
+ const { callback } = options;
+ structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => {
+ if (!patchObj) {
+ callback(void 0);
+ } else {
+ callback(formatPatch(patchObj, options.headerOptions));
+ }
+ } }));
+ }
+}
+function splitLines(text) {
+ const hasTrailingNl = text.endsWith("\n");
+ const result = text.split("\n").map((line) => line + "\n");
+ if (hasTrailingNl) {
+ result.pop();
+ } else {
+ result.push(result.pop().slice(0, -1));
+ }
+ return result;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/edit-diff.js
+function detectLineEnding(content) {
+ const crlfIdx = content.indexOf("\r\n");
+ const lfIdx = content.indexOf("\n");
+ if (lfIdx === -1)
+ return "\n";
+ if (crlfIdx === -1)
+ return "\n";
+ return crlfIdx < lfIdx ? "\r\n" : "\n";
+}
+function normalizeToLF(text) {
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
+}
+function restoreLineEndings(text, ending) {
+ return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
+}
+function normalizeForFuzzyMatch(text) {
+ return text.normalize("NFKC").split("\n").map((line) => line.trimEnd()).join("\n").replace(/[\u2018\u2019\u201A\u201B]/g, "'").replace(/[\u201C\u201D\u201E\u201F]/g, '"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g, "-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ");
+}
+function splitLinesWithEndings(content) {
+ return content.match(/[^\n]*\n|[^\n]+/g) ?? [];
+}
+function getLineSpans(content) {
+ let offset = 0;
+ return splitLinesWithEndings(content).map((line) => {
+ const span = { start: offset, end: offset + line.length };
+ offset = span.end;
+ return span;
+ });
+}
+function getReplacementLineRange(lines2, replacement) {
+ const replacementStart = replacement.matchIndex;
+ const replacementEnd = replacement.matchIndex + replacement.matchLength;
+ let startLine = -1;
+ for (let i = 0; i < lines2.length; i++) {
+ const line = lines2[i];
+ if (replacementStart >= line.start && replacementStart < line.end) {
+ startLine = i;
+ break;
+ }
+ }
+ if (startLine === -1) {
+ throw new Error("Replacement range is outside the base content.");
+ }
+ let endLine = startLine;
+ while (endLine < lines2.length && lines2[endLine].end < replacementEnd) {
+ endLine++;
+ }
+ if (endLine >= lines2.length) {
+ throw new Error("Replacement range is outside the base content.");
+ }
+ return { startLine, endLine: endLine + 1 };
+}
+function applyReplacements(content, replacements, offset = 0) {
+ let result = content;
+ for (let i = replacements.length - 1; i >= 0; i--) {
+ const replacement = replacements[i];
+ const matchIndex = replacement.matchIndex - offset;
+ result = result.substring(0, matchIndex) + replacement.newText + result.substring(matchIndex + replacement.matchLength);
+ }
+ return result;
+}
+function applyReplacementsPreservingUnchangedLines(originalContent, baseContent, replacements) {
+ const originalLines = splitLinesWithEndings(originalContent);
+ const baseLines = getLineSpans(baseContent);
+ if (originalLines.length !== baseLines.length) {
+ throw new Error("Cannot preserve unchanged lines because the base content has a different line count.");
+ }
+ const groups = [];
+ const sortedReplacements = [...replacements].sort((a, b) => a.matchIndex - b.matchIndex);
+ for (const replacement of sortedReplacements) {
+ const range = getReplacementLineRange(baseLines, replacement);
+ const current = groups[groups.length - 1];
+ if (current && range.startLine < current.endLine) {
+ current.endLine = Math.max(current.endLine, range.endLine);
+ current.replacements.push(replacement);
+ continue;
+ }
+ groups.push({ ...range, replacements: [replacement] });
+ }
+ let originalLineIndex = 0;
+ let result = "";
+ for (const group of groups) {
+ result += originalLines.slice(originalLineIndex, group.startLine).join("");
+ const groupStartOffset = baseLines[group.startLine].start;
+ const groupEndOffset = baseLines[group.endLine - 1].end;
+ result += applyReplacements(baseContent.slice(groupStartOffset, groupEndOffset), group.replacements, groupStartOffset);
+ originalLineIndex = group.endLine;
+ }
+ result += originalLines.slice(originalLineIndex).join("");
+ return result;
+}
+function fuzzyFindText(content, oldText) {
+ const exactIndex = content.indexOf(oldText);
+ if (exactIndex !== -1) {
+ return {
+ found: true,
+ index: exactIndex,
+ matchLength: oldText.length,
+ usedFuzzyMatch: false,
+ contentForReplacement: content
+ };
+ }
+ const fuzzyContent = normalizeForFuzzyMatch(content);
+ const fuzzyOldText = normalizeForFuzzyMatch(oldText);
+ const fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);
+ if (fuzzyIndex === -1) {
+ return {
+ found: false,
+ index: -1,
+ matchLength: 0,
+ usedFuzzyMatch: false,
+ contentForReplacement: content
+ };
+ }
+ return {
+ found: true,
+ index: fuzzyIndex,
+ matchLength: fuzzyOldText.length,
+ usedFuzzyMatch: true,
+ contentForReplacement: fuzzyContent
+ };
+}
+function stripBom(content) {
+ return content.startsWith("\uFEFF") ? { bom: "\uFEFF", text: content.slice(1) } : { bom: "", text: content };
+}
+function countOccurrences(content, oldText) {
+ const fuzzyContent = normalizeForFuzzyMatch(content);
+ const fuzzyOldText = normalizeForFuzzyMatch(oldText);
+ return fuzzyContent.split(fuzzyOldText).length - 1;
+}
+function getNotFoundError(path5, editIndex, totalEdits) {
+ if (totalEdits === 1) {
+ return new Error(`Could not find the exact text in ${path5}. The old text must match exactly including all whitespace and newlines.`);
+ }
+ return new Error(`Could not find edits[${editIndex}] in ${path5}. The oldText must match exactly including all whitespace and newlines.`);
+}
+function getDuplicateError(path5, editIndex, totalEdits, occurrences) {
+ if (totalEdits === 1) {
+ return new Error(`Found ${occurrences} occurrences of the text in ${path5}. The text must be unique. Please provide more context to make it unique.`);
+ }
+ return new Error(`Found ${occurrences} occurrences of edits[${editIndex}] in ${path5}. Each oldText must be unique. Please provide more context to make it unique.`);
+}
+function getEmptyOldTextError(path5, editIndex, totalEdits) {
+ if (totalEdits === 1) {
+ return new Error(`oldText must not be empty in ${path5}.`);
+ }
+ return new Error(`edits[${editIndex}].oldText must not be empty in ${path5}.`);
+}
+function getNoChangeError(path5, totalEdits) {
+ if (totalEdits === 1) {
+ return new Error(`No changes made to ${path5}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`);
+ }
+ return new Error(`No changes made to ${path5}. The replacements produced identical content.`);
+}
+function applyEditsToNormalizedContent(normalizedContent, edits, path5) {
+ const normalizedEdits = edits.map((edit) => ({
+ oldText: normalizeToLF(edit.oldText),
+ newText: normalizeToLF(edit.newText)
+ }));
+ for (let i = 0; i < normalizedEdits.length; i++) {
+ if (normalizedEdits[i].oldText.length === 0) {
+ throw getEmptyOldTextError(path5, i, normalizedEdits.length);
+ }
+ }
+ const initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));
+ const usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch);
+ const replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent;
+ const matchedEdits = [];
+ for (let i = 0; i < normalizedEdits.length; i++) {
+ const edit = normalizedEdits[i];
+ const matchResult = fuzzyFindText(replacementBaseContent, edit.oldText);
+ if (!matchResult.found) {
+ throw getNotFoundError(path5, i, normalizedEdits.length);
+ }
+ const occurrences = countOccurrences(replacementBaseContent, edit.oldText);
+ if (occurrences > 1) {
+ throw getDuplicateError(path5, i, normalizedEdits.length, occurrences);
+ }
+ matchedEdits.push({
+ editIndex: i,
+ matchIndex: matchResult.index,
+ matchLength: matchResult.matchLength,
+ newText: edit.newText
+ });
+ }
+ matchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);
+ for (let i = 1; i < matchedEdits.length; i++) {
+ const previous = matchedEdits[i - 1];
+ const current = matchedEdits[i];
+ if (previous.matchIndex + previous.matchLength > current.matchIndex) {
+ throw new Error(`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path5}. Merge them into one edit or target disjoint regions.`);
+ }
+ }
+ const baseContent = normalizedContent;
+ const newContent = usedFuzzyMatch ? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits) : applyReplacements(replacementBaseContent, matchedEdits);
+ if (baseContent === newContent) {
+ throw getNoChangeError(path5, normalizedEdits.length);
+ }
+ return { baseContent, newContent };
+}
+function generateUnifiedPatch(path5, oldContent, newContent, contextLines = 4) {
+ return createTwoFilesPatch(path5, path5, oldContent, newContent, void 0, void 0, {
+ context: contextLines,
+ headerOptions: FILE_HEADERS_ONLY
+ });
+}
+function generateDiffString(oldContent, newContent, contextLines = 4) {
+ const parts2 = diffLines(oldContent, newContent);
+ const output = [];
+ const oldLines = oldContent.split("\n");
+ const newLines = newContent.split("\n");
+ const maxLineNum = Math.max(oldLines.length, newLines.length);
+ const lineNumWidth = String(maxLineNum).length;
+ let oldLineNum = 1;
+ let newLineNum = 1;
+ let lastWasChange = false;
+ let firstChangedLine;
+ for (let i = 0; i < parts2.length; i++) {
+ const part = parts2[i];
+ const raw = part.value.split("\n");
+ if (raw[raw.length - 1] === "") {
+ raw.pop();
+ }
+ if (part.added || part.removed) {
+ if (firstChangedLine === void 0) {
+ firstChangedLine = newLineNum;
+ }
+ for (const line of raw) {
+ if (part.added) {
+ const lineNum = String(newLineNum).padStart(lineNumWidth, " ");
+ output.push(`+${lineNum} ${line}`);
+ newLineNum++;
+ } else {
+ const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
+ output.push(`-${lineNum} ${line}`);
+ oldLineNum++;
+ }
+ }
+ lastWasChange = true;
+ } else {
+ const nextPartIsChange = i < parts2.length - 1 && (parts2[i + 1].added || parts2[i + 1].removed);
+ const hasLeadingChange = lastWasChange;
+ const hasTrailingChange = nextPartIsChange;
+ if (hasLeadingChange && hasTrailingChange) {
+ if (raw.length <= contextLines * 2) {
+ for (const line of raw) {
+ const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
+ output.push(` ${lineNum} ${line}`);
+ oldLineNum++;
+ newLineNum++;
+ }
+ } else {
+ const leadingLines = raw.slice(0, contextLines);
+ const trailingLines = raw.slice(raw.length - contextLines);
+ const skippedLines = raw.length - leadingLines.length - trailingLines.length;
+ for (const line of leadingLines) {
+ const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
+ output.push(` ${lineNum} ${line}`);
+ oldLineNum++;
+ newLineNum++;
+ }
+ output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
+ oldLineNum += skippedLines;
+ newLineNum += skippedLines;
+ for (const line of trailingLines) {
+ const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
+ output.push(` ${lineNum} ${line}`);
+ oldLineNum++;
+ newLineNum++;
+ }
+ }
+ } else if (hasLeadingChange) {
+ const shownLines = raw.slice(0, contextLines);
+ const skippedLines = raw.length - shownLines.length;
+ for (const line of shownLines) {
+ const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
+ output.push(` ${lineNum} ${line}`);
+ oldLineNum++;
+ newLineNum++;
+ }
+ if (skippedLines > 0) {
+ output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
+ oldLineNum += skippedLines;
+ newLineNum += skippedLines;
+ }
+ } else if (hasTrailingChange) {
+ const skippedLines = Math.max(0, raw.length - contextLines);
+ if (skippedLines > 0) {
+ output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
+ oldLineNum += skippedLines;
+ newLineNum += skippedLines;
+ }
+ for (const line of raw.slice(skippedLines)) {
+ const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
+ output.push(` ${lineNum} ${line}`);
+ oldLineNum++;
+ newLineNum++;
+ }
+ } else {
+ oldLineNum += raw.length;
+ newLineNum += raw.length;
+ }
+ lastWasChange = false;
+ }
+ }
+ return { diff: output.join("\n"), firstChangedLine };
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/file-mutation-queue.js
+var queues = /* @__PURE__ */ new Map();
+async function mutationKey(env, path5, context) {
+ const absolutePath = getOrThrow(await env.absolutePath(path5, context));
+ return `${env.id}\0${await canonical(env, absolutePath, context)}`;
+}
+async function canonical(env, absolutePath, context) {
+ const result = await env.canonicalPath(absolutePath, context);
+ if (result.ok)
+ return result.value;
+ if (result.error.code === "not_supported")
+ return absolutePath;
+ if (result.error.code !== "not_found")
+ throw result.error;
+ const parent = getOrThrow(await env.joinPath([absolutePath, ".."], context));
+ if (parent === absolutePath || !absolutePath.startsWith(parent))
+ return absolutePath;
+ const name = absolutePath.slice(parent.length + (/[/\\]$/.test(parent) ? 0 : 1));
+ return getOrThrow(await env.joinPath([await canonical(env, parent, context), name], context));
+}
+async function withFileMutationQueue(env, path5, fn, context) {
+ const key = await mutationKey(env, path5, context);
+ const previous = queues.get(key) ?? Promise.resolve();
+ let release = () => {
+ };
+ const done = new Promise((resolve3) => {
+ release = resolve3;
+ });
+ const tail = previous.then(() => done);
+ queues.set(key, tail);
+ await previous;
+ try {
+ return await fn();
+ } finally {
+ release();
+ if (queues.get(key) === tail)
+ queues.delete(key);
+ }
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/path-utils.js
+var UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
+var NARROW_NO_BREAK_SPACE = "\u202F";
+function normalizeToolPath(path5) {
+ const normalized = path5.replace(UNICODE_SPACES, " ");
+ return normalized.startsWith("@") ? normalized.slice(1) : normalized;
+}
+async function resolveToolPath(env, path5, context) {
+ return getOrThrow(await env.absolutePath(normalizeToolPath(path5), context));
+}
+async function resolveReadToolPath(env, path5, context) {
+ const resolved = await resolveToolPath(env, path5, context);
+ const variants = [
+ resolved,
+ resolved.replace(/ (AM|PM)\./gi, `${NARROW_NO_BREAK_SPACE}$1.`),
+ resolved.normalize("NFD"),
+ resolved.replace(/'/g, "\u2019"),
+ resolved.normalize("NFD").replace(/'/g, "\u2019")
+ ];
+ for (const variant of new Set(variants)) {
+ if (getOrThrow(await env.exists(variant, context)))
+ return variant;
+ }
+ return resolved;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/edit.js
+var replaceEditSchema = typebox_exports.Object({
+ oldText: typebox_exports.String({
+ description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."
+ }),
+ newText: typebox_exports.String({ description: "Replacement text for this targeted edit." })
+});
+var editSchema = typebox_exports.Object({
+ path: typebox_exports.String({ description: "Path to the file to edit (relative or absolute)" }),
+ edits: typebox_exports.Array(replaceEditSchema, {
+ description: "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."
+ })
+});
+function isSingleEditInput(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ return false;
+ const edit = value;
+ return typeof edit.oldText === "string" && typeof edit.newText === "string";
+}
+function prepareEditArguments(input) {
+ if (!input || typeof input !== "object" || Array.isArray(input))
+ return input;
+ const args = { ...input };
+ if (typeof args.edits === "string") {
+ try {
+ const parsed = JSON.parse(args.edits);
+ if (Array.isArray(parsed)) {
+ args.edits = parsed;
+ } else if (isSingleEditInput(parsed)) {
+ args.edits = [parsed];
+ }
+ } catch {
+ }
+ } else if (isSingleEditInput(args.edits)) {
+ args.edits = [args.edits];
+ }
+ const legacy = args;
+ if (typeof legacy.oldText !== "string" || typeof legacy.newText !== "string")
+ return legacy;
+ const edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];
+ edits.push({ oldText: legacy.oldText, newText: legacy.newText });
+ const { oldText: _oldText, newText: _newText, ...rest } = legacy;
+ return { ...rest, edits };
+}
+function validateEditInput(input) {
+ if (!Array.isArray(input.edits) || input.edits.length === 0) {
+ throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");
+ }
+ return { path: input.path, edits: input.edits };
+}
+function editAccessError(path5, error) {
+ return new Error(`Could not edit file: ${path5}. Error code: ${error.code}.`, { cause: error });
+}
+function createEditTool() {
+ return defineTool({
+ name: "edit",
+ description: "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",
+ parameters: editSchema,
+ prepareArguments: prepareEditArguments,
+ async execute(args, api, context) {
+ const { path: path5, edits } = validateEditInput(args);
+ const env = requireEnv(api);
+ const absolutePath = await resolveToolPath(env, path5, context);
+ return withFileMutationQueue(env, absolutePath, async () => {
+ if (context.abortSignal?.aborted)
+ throw new Error("Operation aborted");
+ const info = await env.fileInfo(absolutePath, context);
+ if (!info.ok)
+ throw editAccessError(path5, info.error);
+ if (info.value.kind !== "file" && info.value.kind !== "symlink") {
+ throw new Error(`Could not edit file: ${path5}. Path is not a file.`);
+ }
+ const readResult = await env.readTextFile(absolutePath, context);
+ if (!readResult.ok)
+ throw editAccessError(path5, readResult.error);
+ if (context.abortSignal?.aborted)
+ throw new Error("Operation aborted");
+ const { bom, text: content } = stripBom(readResult.value);
+ const originalEnding = detectLineEnding(content);
+ const normalizedContent = normalizeToLF(content);
+ const { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path5);
+ if (context.abortSignal?.aborted)
+ throw new Error("Operation aborted");
+ const finalContent = bom + restoreLineEndings(newContent, originalEnding);
+ const writeResult = await env.writeFile(absolutePath, finalContent, context);
+ if (!writeResult.ok)
+ throw editAccessError(path5, writeResult.error);
+ if (context.abortSignal?.aborted)
+ throw new Error("Operation aborted");
+ const diffResult = generateDiffString(baseContent, newContent);
+ const details = {
+ diff: diffResult.diff,
+ patch: generateUnifiedPatch(path5, baseContent, newContent),
+ ...diffResult.firstChangedLine === void 0 ? {} : { firstChangedLine: diffResult.firstChangedLine }
+ };
+ return {
+ content: [{ type: "text", text: `Successfully replaced ${edits.length} block(s) in ${path5}.` }],
+ details
+ };
+ }, context);
+ }
+ });
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/image.js
+var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
+var HEADER_BYTES = 32;
+var BLOCK_BYTES = 64 * 1024;
+async function detectSupportedImageMimeTypeOf(source) {
+ const header = await source.read(0, HEADER_BYTES);
+ if (!startsWith2(header, PNG_SIGNATURE))
+ return detectSupportedImageMimeType(header);
+ return isPng(header) && !await isAnimatedPngOf(source) ? "image/png" : void 0;
+}
+async function isAnimatedPngOf(source) {
+ let block = new Uint8Array(0);
+ let blockStart = 0;
+ const bytesAt = async (offset2, length) => {
+ if (offset2 < blockStart || offset2 + length > blockStart + block.length) {
+ blockStart = offset2;
+ block = await source.read(offset2, BLOCK_BYTES);
+ }
+ return block.subarray(offset2 - blockStart, offset2 - blockStart + length);
+ };
+ let offset = PNG_SIGNATURE.length;
+ while (offset + 8 <= source.size) {
+ const chunkHeader = await bytesAt(offset, 8);
+ const chunkLength = readUint32BE(chunkHeader, 0);
+ if (startsWithAscii(chunkHeader, 4, "acTL"))
+ return true;
+ if (startsWithAscii(chunkHeader, 4, "IDAT"))
+ return false;
+ const nextOffset = offset + 8 + chunkLength + 4;
+ if (nextOffset <= offset || nextOffset > source.size)
+ return false;
+ offset = nextOffset;
+ }
+ return false;
+}
+function detectSupportedImageMimeType(buffer) {
+ if (startsWith2(buffer, [255, 216, 255]))
+ return buffer[3] === 247 ? void 0 : "image/jpeg";
+ if (startsWith2(buffer, PNG_SIGNATURE))
+ return isPng(buffer) && !isAnimatedPng(buffer) ? "image/png" : void 0;
+ if (startsWithAscii(buffer, 0, "GIF87a") || startsWithAscii(buffer, 0, "GIF89a"))
+ return "image/gif";
+ if (startsWithAscii(buffer, 0, "RIFF") && startsWithAscii(buffer, 8, "WEBP"))
+ return "image/webp";
+ if (startsWithAscii(buffer, 0, "BM") && isBmp(buffer))
+ return "image/bmp";
+ return void 0;
+}
+function isPng(buffer) {
+ return buffer.length >= 16 && readUint32BE(buffer, PNG_SIGNATURE.length) === 13 && startsWithAscii(buffer, 12, "IHDR");
+}
+function isAnimatedPng(buffer) {
+ let offset = PNG_SIGNATURE.length;
+ while (offset + 8 <= buffer.length) {
+ const chunkLength = readUint32BE(buffer, offset);
+ const chunkTypeOffset = offset + 4;
+ if (startsWithAscii(buffer, chunkTypeOffset, "acTL"))
+ return true;
+ if (startsWithAscii(buffer, chunkTypeOffset, "IDAT"))
+ return false;
+ const nextOffset = offset + 8 + chunkLength + 4;
+ if (nextOffset <= offset || nextOffset > buffer.length)
+ return false;
+ offset = nextOffset;
+ }
+ return false;
+}
+function isBmp(buffer) {
+ if (buffer.length < 26)
+ return false;
+ const declaredFileSize = readUint32LE(buffer, 2);
+ const pixelDataOffset = readUint32LE(buffer, 10);
+ const dibHeaderSize = readUint32LE(buffer, 14);
+ if (declaredFileSize !== 0 && declaredFileSize < 26)
+ return false;
+ if (pixelDataOffset < 14 + dibHeaderSize)
+ return false;
+ if (declaredFileSize !== 0 && pixelDataOffset >= declaredFileSize)
+ return false;
+ let colorPlanes;
+ let bitsPerPixel;
+ if (dibHeaderSize === 12) {
+ colorPlanes = readUint16LE(buffer, 22);
+ bitsPerPixel = readUint16LE(buffer, 24);
+ } else if (dibHeaderSize >= 40 && dibHeaderSize <= 124) {
+ if (buffer.length < 30)
+ return false;
+ colorPlanes = readUint16LE(buffer, 26);
+ bitsPerPixel = readUint16LE(buffer, 28);
+ } else {
+ return false;
+ }
+ return colorPlanes === 1 && [1, 4, 8, 16, 24, 32].includes(bitsPerPixel);
+}
+function readUint16LE(buffer, offset) {
+ return (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8);
+}
+function readUint32BE(buffer, offset) {
+ return (buffer[offset] ?? 0) * 16777216 + ((buffer[offset + 1] ?? 0) << 16) + ((buffer[offset + 2] ?? 0) << 8) + (buffer[offset + 3] ?? 0);
+}
+function readUint32LE(buffer, offset) {
+ return (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8) + ((buffer[offset + 2] ?? 0) << 16) + (buffer[offset + 3] ?? 0) * 16777216;
+}
+function startsWith2(buffer, bytes) {
+ if (buffer.length < bytes.length)
+ return false;
+ return bytes.every((byte, index3) => buffer[index3] === byte);
+}
+function startsWithAscii(buffer, offset, text) {
+ if (buffer.length < offset + text.length)
+ return false;
+ for (let index3 = 0; index3 < text.length; index3++) {
+ if (buffer[offset + index3] !== text.charCodeAt(index3))
+ return false;
+ }
+ return true;
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/read.js
+var readSchema = typebox_exports.Object({
+ path: typebox_exports.String({ description: "Path to the file to read (relative or absolute)" }),
+ offset: typebox_exports.Optional(typebox_exports.Number({ description: "Line number to start reading from (1-indexed)" })),
+ limit: typebox_exports.Optional(typebox_exports.Number({ description: "Maximum number of lines to read" }))
+});
+var READ_CHUNK = 64 * 1024;
+function sliceIndex(value) {
+ return Number.isNaN(value) ? 0 : Math.trunc(value);
+}
+async function readHead(reader, start, end, skipBom, context) {
+ const decoder2 = rangeDecoder();
+ let text = "";
+ let newlines = 0;
+ for (let position = skipBom && start === 0 ? 3 : start; position < end; ) {
+ const bytes = getOrThrow(await reader.read(position, Math.min(READ_CHUNK, end - position), context));
+ if (bytes.length === 0)
+ break;
+ position += bytes.length;
+ const decoded = decoder2.decode(bytes, { stream: true });
+ text += decoded;
+ for (let index3 = decoded.indexOf("\n"); index3 !== -1; index3 = decoded.indexOf("\n", index3 + 1))
+ newlines++;
+ if (newlines >= DEFAULT_MAX_LINES || utf8ByteLength(text) > DEFAULT_MAX_BYTES + 1)
+ return text;
+ }
+ return text + decoder2.decode();
+}
+function createReadTool() {
+ return defineTool({
+ name: "read",
+ description: `Read the contents of a text file. Output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,
+ parameters: readSchema,
+ async execute(args, api, context) {
+ const { path: path5, offset, limit: limit2 } = args;
+ const env = requireEnv(api);
+ const absolutePath = await resolveReadToolPath(env, path5, context);
+ const reader = getOrThrow(await env.openBinaryReader(absolutePath, void 0, context));
+ try {
+ for (let attempt = 0; ; attempt++) {
+ const before = getOrThrow(await reader.info(context));
+ const result = await readText(reader, before, path5, offset, limit2, context);
+ const after = getOrThrow(await reader.info(context));
+ if (after.size === before.size && after.mtimeMs === before.mtimeMs)
+ return result;
+ if (attempt === 1)
+ throw new Error(`${path5} changed while it was read`);
+ }
+ } finally {
+ await reader.close(context);
+ }
+ }
+ });
+}
+async function readText(reader, info, path5, offset, limit2, context) {
+ const mimeType = await detectSupportedImageMimeTypeOf({
+ size: info.size,
+ read: async (position, length) => getOrThrow(await reader.read(position, length, context))
+ });
+ if (mimeType) {
+ return {
+ content: [],
+ isError: true,
+ diagnostics: [
+ {
+ severity: "error",
+ code: "unsupported_image",
+ message: `${path5} is an image (${mimeType}); reading images is not supported`
+ }
+ ]
+ };
+ }
+ const startLine = offset ? Math.max(0, offset - 1) : 0;
+ const startLineDisplay = startLine + 1;
+ const sliceStart = sliceIndex(startLine);
+ const scanStart = Number.isSafeInteger(sliceStart) ? sliceStart : 0;
+ const requestedEnd = limit2 === void 0 ? void 0 : Math.max(scanStart + 1, sliceIndex(startLine + limit2));
+ const scanEnd = requestedEnd !== void 0 && Number.isSafeInteger(requestedEnd) ? requestedEnd : void 0;
+ const scanOf = async (endLine) => getOrThrow(await reader.scanLines({ startLine: scanStart, ...endLine === void 0 ? {} : { endLine } }, context));
+ let scan = await scanOf(scanEnd);
+ const totalFileLines = scan.newlines + 1;
+ if (startLine >= totalFileLines) {
+ throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);
+ }
+ let userLimitedLines;
+ let selectedLineCount = totalFileLines - sliceStart;
+ if (limit2 !== void 0) {
+ const endLine = Math.min(startLine + limit2, totalFileLines);
+ userLimitedLines = endLine - startLine;
+ const relativeEnd = sliceIndex(endLine);
+ const sliceEnd = relativeEnd < 0 ? Math.max(totalFileLines + relativeEnd, 0) : relativeEnd;
+ selectedLineCount = Math.max(0, sliceEnd - sliceStart);
+ if (selectedLineCount > 0 && relativeEnd < 0)
+ scan = await scanOf(sliceEnd);
+ }
+ const empty = selectedLineCount === 0;
+ const endsWithNewline = !empty && scan.lastLineStart === scan.end && scan.lastLineStart > scan.start;
+ const totals = {
+ lines: empty || scan.selectedBytes === 0 ? 0 : selectedLineCount - (endsWithNewline ? 1 : 0),
+ bytes: empty ? 0 : scan.selectedBytes
+ };
+ const firstBytes = getOrThrow(await reader.read(0, 3, context));
+ const head = empty ? "" : await readHead(reader, scan.start, scan.end, startsWithBom(firstBytes), context);
+ const { content: headText, ...truncation } = truncateHeadOf(head, totals);
+ const diagnostics = [];
+ let outputText = headText;
+ let details;
+ if (truncation.firstLineExceedsLimit) {
+ const integral = Number.isInteger(startLine);
+ const lineBytes = new TextEncoder().encode(integral ? head.split("\n")[0] ?? "" : "");
+ const lineSize = integral ? scan.firstLineBytes : 0;
+ const end = characterEnd(lineBytes, DEFAULT_MAX_BYTES);
+ outputText = new TextDecoder().decode(lineBytes.subarray(0, end));
+ diagnostics.push({
+ severity: "warn",
+ code: "truncated",
+ message: `Line ${startLineDisplay} is ${formatSize(lineSize)}, exceeds the ${formatSize(DEFAULT_MAX_BYTES)} limit; showing its first ${formatSize(end)}. Use bash: sed -n '${startLineDisplay}p' ${path5} | tail -c +${end + 1}`
+ });
+ details = { truncation: { ...truncation, outputBytes: end, outputLines: 1 } };
+ } else if (truncation.truncated) {
+ const endLineDisplay = startLineDisplay + truncation.outputLines - 1;
+ const nextOffset = endLineDisplay + 1;
+ const limitText = truncation.truncatedBy === "lines" ? "" : ` (${formatSize(DEFAULT_MAX_BYTES)} limit)`;
+ diagnostics.push({
+ severity: "info",
+ code: "truncated",
+ message: `Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}${limitText}. Use offset=${nextOffset} to continue.`
+ });
+ details = { truncation };
+ } else if (userLimitedLines !== void 0 && startLine + userLimitedLines < totalFileLines) {
+ const remaining = totalFileLines - (startLine + userLimitedLines);
+ const nextOffset = startLine + userLimitedLines + 1;
+ diagnostics.push({
+ severity: "info",
+ message: `${remaining} more lines in file. Use offset=${nextOffset} to continue.`
+ });
+ }
+ return {
+ content: outputText === "" ? [] : [{ type: "text", text: outputText }],
+ ...details === void 0 ? {} : { details },
+ diagnostics
+ };
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/write.js
+var writeSchema = typebox_exports.Object({
+ path: typebox_exports.String({ description: "Path to the file to write (relative or absolute)" }),
+ content: typebox_exports.String({ description: "Content to write to the file" })
+});
+function createWriteTool() {
+ return defineTool({
+ name: "write",
+ description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
+ parameters: writeSchema,
+ async execute(args, api, context) {
+ const { path: path5, content } = args;
+ const env = requireEnv(api);
+ const absolutePath = await resolveToolPath(env, path5, context);
+ return withFileMutationQueue(env, absolutePath, async () => {
+ if (context.abortSignal?.aborted)
+ throw new Error("Operation aborted");
+ getOrThrow(await env.writeFile(absolutePath, content, context));
+ if (context.abortSignal?.aborted)
+ throw new Error("Operation aborted");
+ return { content: [{ type: "text", text: `Successfully wrote to ${path5}` }] };
+ }, context);
+ }
+ });
+}
+
+// node_modules/@earendil-works/pi-durable/dist/tools/index.js
+var CodingTools = defineExtension({
+ name: "coding-tools",
+ tools: [createReadTool(), createWriteTool(), createEditTool(), createBashTool()]
+});
+
+// node_modules/@earendil-works/pi-durable/dist/storage/jsonl/storage.js
+var FORMAT_VERSION = 1;
+var MAIN_FILE = "main.jsonl";
+var RECLAIM_SUFFIX = ".reclaim";
+var textDecoder = new TextDecoder("utf-8", { fatal: true });
+var JsonlCorruptionError = class extends Error {
+ constructor(message, cause) {
+ super(message, cause === void 0 ? void 0 : { cause });
+ this.name = "JsonlCorruptionError";
+ }
+};
+var JsonlStoragePoisonedError = class extends Error {
+ constructor(cause) {
+ super("JSONL storage is poisoned and must be reopened", { cause });
+ this.name = "JsonlStoragePoisonedError";
+ }
+};
+var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
+var isSafeInteger = (value) => Number.isSafeInteger(value);
+var sidecarFileName = (kind, id) => `${kind}-${id}.jsonl`;
+var isSidecarFileName = (name) => /^(?:doc|task)-(?:0|[1-9]\d*)\.jsonl$/.test(name);
+var isReclaimFileName = (name) => /^(?:doc|task)-(?:0|[1-9]\d*)\.jsonl\.reclaim$/.test(name);
+var isCurrentOnly2 = (record) => record.scope.kind !== "conversation" || record.history === "latest";
+var sidecarKey = (file, seq, ordinal) => JSON.stringify([file, seq, ordinal]);
+var jsonLine = (value) => `${JSON.stringify(value)}
+`;
+var errorFromFile = (action, error) => new Error(`JSONL ${action} failed: ${error.message}`, { cause: error });
+var parseJson = (text, description) => {
+ try {
+ return JSON.parse(text);
+ } catch (error) {
+ throw new JsonlCorruptionError(`Malformed complete ${description}`, error instanceof Error ? error : void 0);
+ }
+};
+var validateMainOperation = (value, description) => {
+ if (!isObject(value) || typeof value.type !== "string") {
+ throw new JsonlCorruptionError(`Invalid write in ${description}`);
+ }
+ switch (value.type) {
+ case "conversation":
+ case "entry":
+ case "submission":
+ if (!isObject(value.value) || !isSafeInteger(value.value.id)) {
+ throw new JsonlCorruptionError(`Invalid ${value.type} write in ${description}`);
+ }
+ return value;
+ case "task":
+ if (!isObject(value.value) || !isSafeInteger(value.value.id) || !isObject(value.value.state) || value.value.state.status !== "terminal") {
+ throw new JsonlCorruptionError(`Invalid terminal task write in ${description}`);
+ }
+ return value;
+ case "document.retire":
+ if (!isSafeInteger(value.id))
+ throw new JsonlCorruptionError(`Invalid document retirement in ${description}`);
+ return value;
+ case "task.sidecar":
+ if (!isSafeInteger(value.id) || !isSafeInteger(value.ordinal) || value.ordinal < 0) {
+ throw new JsonlCorruptionError(`Invalid task sidecar write in ${description}`);
+ }
+ return value;
+ case "document.create":
+ if (!isObject(value.record) || !isSafeInteger(value.record.id) || !isSafeInteger(value.ordinal) || value.ordinal < 0) {
+ throw new JsonlCorruptionError(`Invalid document creation in ${description}`);
+ }
+ return value;
+ case "document.change":
+ if (!isSafeInteger(value.id) || !isSafeInteger(value.ordinal) || value.ordinal < 0) {
+ throw new JsonlCorruptionError(`Invalid document change in ${description}`);
+ }
+ return value;
+ default:
+ throw new JsonlCorruptionError(`Unknown write type in ${description}`);
+ }
+};
+var parseMainMarker = (text, line) => {
+ const description = `${MAIN_FILE} line ${line}`;
+ const value = parseJson(text, description);
+ if (!isObject(value) || value.format !== FORMAT_VERSION || value.type !== "commit" || !isSafeInteger(value.seq) || value.seq < 1 || !Array.isArray(value.writes)) {
+ throw new JsonlCorruptionError(`Invalid commit marker in ${description}`);
+ }
+ return {
+ format: FORMAT_VERSION,
+ type: "commit",
+ seq: seqFromNumber(value.seq),
+ writes: value.writes.map((write) => validateMainOperation(write, description))
+ };
+};
+var validateDocumentContent = (value, description) => {
+ if (!isObject(value) || !isSafeInteger(value.version) || value.version < 1) {
+ throw new JsonlCorruptionError(`Invalid document content in ${description}`);
+ }
+ if (value.kind === "base" && isObject(value.value))
+ return value;
+ if (value.kind === "delta" && Array.isArray(value.ops))
+ return value;
+ throw new JsonlCorruptionError(`Invalid document content in ${description}`);
+};
+var parseSidecarRecord = (text, file, line) => {
+ const description = `${file} line ${line}`;
+ const value = parseJson(text, description);
+ if (!isObject(value) || value.format !== FORMAT_VERSION || value.type !== "record" || !isSafeInteger(value.seq) || value.seq < 1 || !isSafeInteger(value.ordinal) || value.ordinal < 0 || !isObject(value.payload) || typeof value.payload.type !== "string") {
+ throw new JsonlCorruptionError(`Invalid sidecar record in ${description}`);
+ }
+ if (value.payload.type === "task") {
+ if (!isObject(value.payload.value) || !isSafeInteger(value.payload.value.id) || !isObject(value.payload.value.state) || value.payload.value.state.status === "terminal") {
+ throw new JsonlCorruptionError(`Invalid live task record in ${description}`);
+ }
+ } else if (value.payload.type === "document") {
+ if (!isSafeInteger(value.payload.id)) {
+ throw new JsonlCorruptionError(`Invalid document record in ${description}`);
+ }
+ validateDocumentContent(value.payload.content, description);
+ } else {
+ throw new JsonlCorruptionError(`Unknown sidecar record type in ${description}`);
+ }
+ return value;
+};
+var JsonlStorage = class _JsonlStorage {
+ fs;
+ directory;
+ mainPath;
+ fsync;
+ memory = new MemoryStorage();
+ currentOnlyDocuments = /* @__PURE__ */ new Set();
+ liveTaskSidecars = /* @__PURE__ */ new Set();
+ closed = false;
+ poisonError;
+ constructor(fs3, directory, mainPath, options) {
+ this.fs = fs3;
+ this.directory = directory;
+ this.mainPath = mainPath;
+ this.fsync = options.fsync ?? false;
+ }
+ /** Open or create a JSONL storage directory using the supplied filesystem. */
+ static async open(directory, fs3, context, options = {}) {
+ const absolute = await fs3.absolutePath(directory, context);
+ if (!absolute.ok)
+ throw errorFromFile("path resolution", absolute.error);
+ const created = await fs3.createDir(absolute.value, { recursive: true }, context);
+ if (!created.ok)
+ throw errorFromFile("directory creation", created.error);
+ const mainPathResult = await fs3.joinPath([absolute.value, MAIN_FILE], context);
+ if (!mainPathResult.ok)
+ throw errorFromFile("path join", mainPathResult.error);
+ const storage = new _JsonlStorage(fs3, absolute.value, mainPathResult.value, options);
+ await storage.recover(context);
+ return storage;
+ }
+ async commit(writes, context) {
+ this.assertUsable();
+ const prepared = this.memory.prepareCommit(writes);
+ const encoded = this.encodeCommit(prepared.seq, prepared.writes);
+ const reclamations = this.planReclamations(prepared.writes, encoded);
+ const sidecars = await Promise.all([...encoded.sidecars].map(async ([file, content]) => ({
+ file,
+ content,
+ path: await this.resolveFile(file, context)
+ })));
+ for (const sidecar of sidecars) {
+ const result = await this.fs.appendFile(sidecar.path, sidecar.content, context);
+ if (!result.ok)
+ throw this.poison(errorFromFile(`append to ${sidecar.file}`, result.error));
+ }
+ if (this.fsync) {
+ for (const sidecar of sidecars) {
+ const result = await this.fs.flushFile(sidecar.path, context);
+ if (!result.ok)
+ throw this.poison(errorFromFile(`flush of ${sidecar.file}`, result.error));
+ }
+ }
+ const marker = await this.fs.appendFile(this.mainPath, encoded.marker, context);
+ if (!marker.ok)
+ throw this.poison(errorFromFile(`append to ${MAIN_FILE}`, marker.error));
+ const seq = prepared.apply();
+ this.adoptSidecarState(prepared.writes);
+ await this.reclaimSidecars(reclamations, context);
+ return seq;
+ }
+ async mintId() {
+ return this.store.mintId();
+ }
+ async conversation(id, context) {
+ return this.store.conversation(id, context);
+ }
+ async scanConversations(query, limit2, cursor, context) {
+ return this.store.scanConversations(query, limit2, cursor, context);
+ }
+ async entry(idOrConversationId, idOrContext, context) {
+ if (context === void 0)
+ return this.store.entry(idFromNumber(idOrConversationId), idOrContext);
+ if (typeof idOrContext !== "number")
+ throw new TypeError("Storage.entry() requires an entry ID");
+ return this.store.entry(idFromNumber(idOrConversationId), idFromNumber(idOrContext), context);
+ }
+ async findLatestHeadMarker(conversationId, atOrBeforeEntryId, context) {
+ return this.store.findLatestHeadMarker(conversationId, atOrBeforeEntryId, context);
+ }
+ async scanEntries(query, limit2, cursor, context) {
+ return this.store.scanEntries(query, limit2, cursor, context);
+ }
+ async task(id, context) {
+ return this.store.task(id, context);
+ }
+ async scanTasks(query, limit2, cursor, context) {
+ return this.store.scanTasks(query, limit2, cursor, context);
+ }
+ async submission(id, context) {
+ return this.store.submission(id, context);
+ }
+ async scanSubmissions(query, limit2, cursor, context) {
+ return this.store.scanSubmissions(query, limit2, cursor, context);
+ }
+ async submissionByRequest(conversationId, requestId, context) {
+ return this.store.submissionByRequest(conversationId, requestId, context);
+ }
+ async findDocument(address, at, context) {
+ return this.store.findDocument(address, at, context);
+ }
+ async document(id, at, context) {
+ return this.store.document(id, at, context);
+ }
+ async scanDocuments(query, limit2, cursor, context) {
+ return this.store.scanDocuments(query, limit2, cursor, context);
+ }
+ async close(context) {
+ if (this.closed)
+ return;
+ this.closed = true;
+ await this.memory.close(context);
+ }
+ encodeCommit(seq, writes) {
+ const mainWrites = [];
+ const records = /* @__PURE__ */ new Map();
+ let nextOrdinal = 0;
+ const addSidecar = (file, payload) => {
+ const ordinal = nextOrdinal++;
+ let fileRecords = records.get(file);
+ if (fileRecords === void 0) {
+ fileRecords = [];
+ records.set(file, fileRecords);
+ }
+ fileRecords.push({ format: FORMAT_VERSION, type: "record", seq, ordinal, payload });
+ return ordinal;
+ };
+ for (const write of writes) {
+ switch (write.type) {
+ case "conversation":
+ case "entry":
+ case "submission":
+ case "document.retire":
+ mainWrites.push(write);
+ break;
+ case "task":
+ if (write.value.state.status === "terminal")
+ mainWrites.push(write);
+ else {
+ const ordinal = addSidecar(sidecarFileName("task", write.value.id), {
+ type: "task",
+ value: write.value
+ });
+ mainWrites.push({ type: "task.sidecar", id: write.value.id, ordinal });
+ }
+ break;
+ case "document.create": {
+ const ordinal = addSidecar(sidecarFileName("doc", write.record.id), {
+ type: "document",
+ id: write.record.id,
+ content: write.content
+ });
+ mainWrites.push({ type: "document.create", record: write.record, ordinal });
+ break;
+ }
+ case "document.change": {
+ const ordinal = addSidecar(sidecarFileName("doc", write.id), {
+ type: "document",
+ id: write.id,
+ content: write.content
+ });
+ mainWrites.push({ type: "document.change", id: write.id, ordinal });
+ break;
+ }
+ }
+ }
+ const sidecars = /* @__PURE__ */ new Map();
+ for (const [file, fileRecords] of records) {
+ sidecars.set(file, fileRecords.map((record) => jsonLine(record)).join(""));
+ }
+ const marker = {
+ format: FORMAT_VERSION,
+ type: "commit",
+ seq,
+ writes: mainWrites
+ };
+ return { marker: jsonLine(marker), sidecars };
+ }
+ planReclamations(writes, encoded) {
+ const createdCurrentOnlyDocuments = /* @__PURE__ */ new Set();
+ const retiredDocuments = /* @__PURE__ */ new Set();
+ const baseDocuments = /* @__PURE__ */ new Set();
+ const finalTasks = /* @__PURE__ */ new Map();
+ for (const write of writes) {
+ switch (write.type) {
+ case "document.create":
+ if (isCurrentOnly2(write.record))
+ createdCurrentOnlyDocuments.add(write.record.id);
+ break;
+ case "document.change":
+ if (write.content.kind === "base")
+ baseDocuments.add(write.id);
+ break;
+ case "document.retire":
+ retiredDocuments.add(write.id);
+ break;
+ case "task":
+ finalTasks.set(write.value.id, write.value);
+ break;
+ }
+ }
+ const replacements = /* @__PURE__ */ new Map();
+ const isCurrentOnlyDocument = (id) => this.currentOnlyDocuments.has(id) || createdCurrentOnlyDocuments.has(id);
+ for (const id of retiredDocuments) {
+ if (isCurrentOnlyDocument(id))
+ replacements.set(sidecarFileName("doc", id), "");
+ }
+ for (const id of baseDocuments) {
+ if (!isCurrentOnlyDocument(id) || retiredDocuments.has(id))
+ continue;
+ const file = sidecarFileName("doc", id);
+ const content = encoded.sidecars.get(file);
+ if (content !== void 0)
+ replacements.set(file, content);
+ }
+ for (const [id, task] of finalTasks) {
+ if (task.state.status === "terminal" && (this.liveTaskSidecars.has(id) || encoded.sidecars.has(sidecarFileName("task", id)))) {
+ replacements.set(sidecarFileName("task", id), "");
+ }
+ }
+ return replacements;
+ }
+ adoptSidecarState(writes) {
+ for (const write of writes) {
+ if (write.type === "document.create") {
+ if (isCurrentOnly2(write.record))
+ this.currentOnlyDocuments.add(write.record.id);
+ } else if (write.type === "task") {
+ if (write.value.state.status === "terminal")
+ this.liveTaskSidecars.delete(write.value.id);
+ else
+ this.liveTaskSidecars.add(write.value.id);
+ }
+ }
+ }
+ /** The marker already published this state, so reclamation is retryable best-effort maintenance. */
+ async reclaimSidecars(replacements, context) {
+ if (replacements.size === 0)
+ return;
+ if (this.fsync) {
+ const flushed = await this.fs.flushFile(this.mainPath, context);
+ if (!flushed.ok)
+ return;
+ }
+ for (const [file, content] of replacements)
+ await this.replaceSidecar(file, content, context);
+ }
+ async replaceSidecar(file, content, context) {
+ const path5 = await this.fs.joinPath([this.directory, file], context);
+ if (!path5.ok)
+ return;
+ if (content === "") {
+ await this.fs.remove(path5.value, { force: true }, context);
+ return;
+ }
+ const temporaryPath = await this.fs.joinPath([this.directory, `${file}${RECLAIM_SUFFIX}`], context);
+ if (!temporaryPath.ok)
+ return;
+ const written = await this.fs.writeFile(temporaryPath.value, content, context);
+ if (!written.ok)
+ return;
+ if (this.fsync) {
+ const flushed = await this.fs.flushFile(temporaryPath.value, context);
+ if (!flushed.ok)
+ return;
+ }
+ await this.fs.renameFile(temporaryPath.value, path5.value, context);
+ }
+ async recover(context) {
+ const fs3 = this.fs;
+ const directory = this.directory;
+ const memory = this.memory;
+ const main2 = await _JsonlStorage.readLines(fs3, this.mainPath, MAIN_FILE, context, (text, line) => parseMainMarker(text, line));
+ let previousSeq = 0;
+ for (const marker of main2.lines) {
+ if (marker.value.seq <= previousSeq) {
+ throw new JsonlCorruptionError(`Commit sequence does not strictly increase in ${MAIN_FILE}`);
+ }
+ previousSeq = marker.value.seq;
+ }
+ const listed = await fs3.listDir(directory, context);
+ if (!listed.ok)
+ throw errorFromFile("directory listing", listed.error);
+ for (const info of listed.value) {
+ if (info.kind === "file" && isReclaimFileName(info.name)) {
+ await fs3.remove(info.path, { force: true }, context);
+ }
+ }
+ const sidecarFiles = listed.value.filter((info) => info.kind === "file" && isSidecarFileName(info.name)).map((info) => info.name).sort();
+ const parsedFiles = /* @__PURE__ */ new Map();
+ const recordByKey = /* @__PURE__ */ new Map();
+ for (const file of sidecarFiles) {
+ const pathResult = await fs3.joinPath([directory, file], context);
+ if (!pathResult.ok)
+ throw errorFromFile("path join", pathResult.error);
+ const parsed = await _JsonlStorage.readLines(fs3, pathResult.value, file, context, (text, line) => parseSidecarRecord(text, file, line));
+ parsedFiles.set(file, parsed);
+ let previous;
+ for (const line of parsed.lines) {
+ if (previous !== void 0 && (line.value.seq < previous.seq || line.value.seq === previous.seq && line.value.ordinal <= previous.ordinal)) {
+ throw new JsonlCorruptionError(`Sidecar records are out of order in ${file}`);
+ }
+ previous = line.value;
+ recordByKey.set(sidecarKey(file, line.value.seq, line.value.ordinal), line);
+ }
+ }
+ const currentOnlyDocuments = /* @__PURE__ */ new Set();
+ const retiredDocuments = /* @__PURE__ */ new Set();
+ const finalTaskIsLive = /* @__PURE__ */ new Map();
+ for (const { value: marker } of main2.lines) {
+ for (const operation of marker.writes) {
+ if (operation.type === "document.create") {
+ if (isCurrentOnly2(operation.record))
+ currentOnlyDocuments.add(operation.record.id);
+ } else if (operation.type === "document.retire") {
+ retiredDocuments.add(operation.id);
+ } else if (operation.type === "task") {
+ finalTaskIsLive.set(operation.value.id, false);
+ } else if (operation.type === "task.sidecar") {
+ finalTaskIsLive.set(operation.id, true);
+ }
+ }
+ }
+ const retiredCurrentOnlyDocuments = new Set([...retiredDocuments].filter((id) => currentOnlyDocuments.has(id)));
+ const latestBases = /* @__PURE__ */ new Map();
+ for (const { value: marker } of main2.lines) {
+ for (const operation of marker.writes) {
+ if (operation.type !== "document.create" && operation.type !== "document.change")
+ continue;
+ const id = operation.type === "document.create" ? operation.record.id : operation.id;
+ if (!currentOnlyDocuments.has(id))
+ continue;
+ const record = recordByKey.get(sidecarKey(sidecarFileName("doc", id), marker.seq, operation.ordinal))?.value;
+ if (record?.payload.type !== "document" || record.payload.id !== id || record.payload.content.kind !== "base") {
+ continue;
+ }
+ const previous = latestBases.get(id);
+ if (previous === void 0 || record.seq > previous.seq || record.seq === previous.seq && record.ordinal > previous.ordinal) {
+ latestBases.set(id, record);
+ }
+ }
+ }
+ const isBeforeLatestBase = (id, seq, ordinal) => {
+ const base = latestBases.get(id);
+ return base !== void 0 && (seq < base.seq || seq === base.seq && ordinal < base.ordinal);
+ };
+ const terminalTasks = new Set([...finalTaskIsLive].filter(([, live]) => !live).map(([id]) => id));
+ const confirmed = /* @__PURE__ */ new Set();
+ for (const line of main2.lines) {
+ const marker = line.value;
+ const writes = [];
+ for (const operation of marker.writes) {
+ switch (operation.type) {
+ case "conversation":
+ case "entry":
+ case "submission":
+ case "task":
+ case "document.retire":
+ writes.push(operation);
+ break;
+ case "task.sidecar": {
+ const optional = terminalTasks.has(operation.id);
+ const record = _JsonlStorage.confirmRecord(marker, operation.ordinal, sidecarFileName("task", operation.id), recordByKey, confirmed, optional);
+ if (record !== void 0) {
+ if (record.payload.type !== "task" || record.payload.value.id !== operation.id) {
+ throw new JsonlCorruptionError(`Confirmed task sidecar data does not match commit ${marker.seq}`);
+ }
+ if (!optional)
+ writes.push({ type: "task", value: record.payload.value });
+ }
+ break;
+ }
+ case "document.create":
+ case "document.change": {
+ const id = operation.type === "document.create" ? operation.record.id : operation.id;
+ const reclaimed = retiredCurrentOnlyDocuments.has(id) || isBeforeLatestBase(id, marker.seq, operation.ordinal);
+ const record = _JsonlStorage.confirmRecord(marker, operation.ordinal, sidecarFileName("doc", id), recordByKey, confirmed, reclaimed);
+ let content;
+ if (record !== void 0) {
+ if (record.payload.type !== "document" || record.payload.id !== id) {
+ throw new JsonlCorruptionError(`Confirmed document sidecar data does not match commit ${marker.seq}`);
+ }
+ content = record.payload.content;
+ }
+ if (operation.type === "document.create") {
+ if (content !== void 0 && content.kind !== "base") {
+ throw new JsonlCorruptionError(`Document creation lacks a confirmed base in commit ${marker.seq}`);
+ }
+ writes.push({
+ type: "document.create",
+ record: operation.record,
+ content: reclaimed || content === void 0 ? { kind: "base", version: 1, value: {} } : content
+ });
+ } else if (!reclaimed && content !== void 0) {
+ writes.push({ type: "document.change", id, content });
+ }
+ break;
+ }
+ }
+ }
+ try {
+ memory.prepareCommit(writes, marker.seq).apply();
+ } catch (error) {
+ throw new JsonlCorruptionError(`Invalid committed state at sequence ${marker.seq}`, error instanceof Error ? error : void 0);
+ }
+ }
+ const reclamations = /* @__PURE__ */ new Map();
+ for (const [file, parsed] of parsedFiles) {
+ let unconfirmedAt;
+ for (const line of parsed.lines) {
+ const key = sidecarKey(file, line.value.seq, line.value.ordinal);
+ if (confirmed.has(key)) {
+ if (unconfirmedAt !== void 0) {
+ throw new JsonlCorruptionError(`Confirmed record follows an unconfirmed tail in ${file}`);
+ }
+ } else if (unconfirmedAt === void 0) {
+ unconfirmedAt = line.start;
+ }
+ }
+ if (unconfirmedAt !== void 0) {
+ const truncated2 = await fs3.truncateFile(parsed.path, unconfirmedAt, context);
+ if (!truncated2.ok)
+ throw errorFromFile(`tail truncation of ${file}`, truncated2.error);
+ }
+ const numericId = Number(file.slice(file.indexOf("-") + 1, -".jsonl".length));
+ const confirmedLines = parsed.lines.filter((line) => confirmed.has(sidecarKey(file, line.value.seq, line.value.ordinal)));
+ let retainedLines;
+ if (file.startsWith("task-") && terminalTasks.has(idFromNumber(numericId))) {
+ retainedLines = [];
+ } else if (file.startsWith("doc-")) {
+ const documentId = idFromNumber(numericId);
+ if (retiredCurrentOnlyDocuments.has(documentId)) {
+ retainedLines = [];
+ } else if (latestBases.has(documentId)) {
+ retainedLines = confirmedLines.filter((line) => !isBeforeLatestBase(documentId, line.value.seq, line.value.ordinal));
+ }
+ }
+ if (retainedLines !== void 0 && (retainedLines.length < confirmedLines.length || retainedLines.length === 0)) {
+ reclamations.set(file, retainedLines.map((line) => jsonLine(line.value)).join(""));
+ }
+ }
+ await this.reclaimSidecars(reclamations, context);
+ for (const id of currentOnlyDocuments)
+ this.currentOnlyDocuments.add(id);
+ for (const [id, live] of finalTaskIsLive) {
+ if (live)
+ this.liveTaskSidecars.add(id);
+ }
+ }
+ static confirmRecord(marker, ordinal, file, recordByKey, confirmed, optional) {
+ const key = sidecarKey(file, marker.seq, ordinal);
+ if (confirmed.has(key))
+ throw new JsonlCorruptionError(`Sidecar record is confirmed more than once`);
+ const line = recordByKey.get(key);
+ if (line === void 0) {
+ if (optional)
+ return void 0;
+ throw new JsonlCorruptionError(`Missing confirmed sidecar record ${file} at sequence ${marker.seq}`);
+ }
+ confirmed.add(key);
+ return line.value;
+ }
+ static async readLines(fs3, path5, name, context, parse) {
+ const read2 = await fs3.readBinaryFile(path5, context);
+ if (!read2.ok) {
+ if (read2.error.code === "not_found")
+ return { path: path5, lines: [] };
+ throw errorFromFile(`read of ${name}`, read2.error);
+ }
+ const bytes = read2.value;
+ let completeSize = bytes.length;
+ if (completeSize > 0 && bytes[completeSize - 1] !== 10) {
+ completeSize = bytes.lastIndexOf(10) + 1;
+ const truncated2 = await fs3.truncateFile(path5, completeSize, context);
+ if (!truncated2.ok)
+ throw errorFromFile(`torn-line truncation of ${name}`, truncated2.error);
+ }
+ const lines2 = [];
+ let start = 0;
+ let lineNumber = 1;
+ for (let end = 0; end < completeSize; end++) {
+ if (bytes[end] !== 10)
+ continue;
+ let text;
+ try {
+ text = textDecoder.decode(bytes.subarray(start, end));
+ } catch (error) {
+ throw new JsonlCorruptionError(`Invalid UTF-8 in complete ${name} line ${lineNumber}`, error instanceof Error ? error : void 0);
+ }
+ lines2.push({ value: parse(text, lineNumber), start });
+ start = end + 1;
+ lineNumber++;
+ }
+ return { path: path5, lines: lines2 };
+ }
+ async resolveFile(file, context) {
+ const path5 = await this.fs.joinPath([this.directory, file], context);
+ if (!path5.ok)
+ throw errorFromFile("path join", path5.error);
+ return path5.value;
+ }
+ get store() {
+ this.assertUsable();
+ return this.memory;
+ }
+ poison(cause) {
+ this.poisonError ??= new JsonlStoragePoisonedError(cause);
+ return this.poisonError;
+ }
+ assertUsable() {
+ if (this.closed)
+ throw new Error("JsonlStorage is closed");
+ if (this.poisonError !== void 0)
+ throw this.poisonError;
+ }
+};
+
+// node_modules/@earendil-works/pi-durable/dist/storage/jsonl/node.js
+async function openNodeJsonlStorage(directory, context, options = {}) {
+ return JsonlStorage.open(directory, new NodeExecutionEnv({ cwd: process.cwd() }), context, options);
+}
+
+// src/protocol.mjs
+import { createHash as createHash2 } from "node:crypto";
+import { constants as constants2 } from "node:fs";
+import * as fs from "node:fs/promises";
+import path2 from "node:path";
+var CONTRACT = "esf/pi/v1";
+var SUMMARY_LIMIT = 128 * 1024;
+var sha256 = (value) => createHash2("sha256").update(value).digest("hex");
+async function readJSON(file, maxBytes = SUMMARY_LIMIT) {
+ const handle = await fs.open(file, constants2.O_RDONLY | constants2.O_NOFOLLOW);
+ try {
+ const stat2 = await handle.stat();
+ if (!stat2.isFile() || stat2.size > maxBytes) throw new Error("invalid or oversized Pi state receipt");
+ return JSON.parse(await handle.readFile("utf8"));
+ } finally {
+ await handle.close();
+ }
+}
+function validateRequest(r) {
+ const digest = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
+ if (!r || r.contract_version !== CONTRACT || !r.run_id || typeof r.prompt !== "string" || !r.prompt.trim() || !digest(r.fingerprint) || !digest(r.runner_sha256) || !digest(r.runtime_sha256) || r.request_id !== sha256(`${r.run_id}\0${r.prompt}`) || !path2.isAbsolute(r.repository_dir) || path2.normalize(r.repository_dir) !== r.repository_dir || r.state_dir !== path2.join(path2.dirname(r.repository_dir), ".factory", "pi", sha256(r.run_id)) || !Number.isSafeInteger(r.timeout_ms) || r.timeout_ms <= 0 || r.timeout_ms > 2147483647 || ![0, 1].includes(r.max_process_restarts) || !["openai-completions", "openai-responses"].includes(r.api)) throw new Error("invalid Pi request contract");
+ const endpoint = new URL(r.base_url);
+ if (!["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) throw new Error("invalid Pi endpoint");
+ const m = r.metadata;
+ if (!m || m.id !== r.model || m.api !== r.api || !Number.isSafeInteger(m.contextWindow) || !Number.isSafeInteger(m.maxTokens) || m.maxTokens <= 0 || m.contextWindow <= m.maxTokens || m.input?.length !== 1 || m.input[0] !== "text") throw new Error("invalid pinned model definition");
+ if (r.thinking_level !== "off" && (!m.reasoning || !m.thinkingLevels?.includes(r.thinking_level))) throw new Error("unsupported model reasoning level");
+ if (m.pricingKnown && !m.cost) throw new Error("known pricing requires rates");
+ if (m.cost && ["input", "output", "cacheRead", "cacheWrite"].some((k) => !Number.isFinite(m.cost[k]) || m.cost[k] < 0)) throw new Error("invalid model cost");
+ return r;
+}
+async function writeJSON(file, value, maxBytes = SUMMARY_LIMIT) {
+ const bytes = JSON.stringify(value) + "\n";
+ if (Buffer.byteLength(bytes) > maxBytes) throw new Error("Pi summary exceeds size limit");
+ const temp = `${file}.${process.pid}.tmp`;
+ const handle = await fs.open(temp, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL | constants2.O_NOFOLLOW, 384);
+ try {
+ await handle.writeFile(bytes);
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+ try {
+ await fs.rename(temp, file);
+ } finally {
+ await fs.rm(temp, { force: true });
+ }
+ const directory = await fs.open(path2.dirname(file), constants2.O_RDONLY);
+ try {
+ await directory.sync();
+ } finally {
+ await directory.close();
+ }
+}
+async function prepareState(r) {
+ await fs.mkdir(r.state_dir, { recursive: true, mode: 448 });
+ if (!(await fs.lstat(r.state_dir)).isDirectory() || (await fs.lstat(r.state_dir)).isSymbolicLink()) throw new Error("invalid Pi state directory");
+ const lock = await fs.open(path2.join(r.state_dir, "owner.lock"), "wx", 384);
+ try {
+ await lock.writeFile(String(process.pid));
+ await lock.sync();
+ const identityPath = path2.join(r.state_dir, "identity.json");
+ const expected = { ...r };
+ let previous;
+ try {
+ previous = await readJSON(identityPath, 4 * 1024 * 1024);
+ } catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ }
+ if (previous) {
+ if (JSON.stringify(previous) !== JSON.stringify(expected)) throw new Error("Pi session fingerprint or configuration mismatch");
+ const stat2 = await fs.lstat(path2.join(r.state_dir, "journal", "main.jsonl"));
+ if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size === 0) throw new Error("Pi journal is missing or invalid");
+ } else {
+ try {
+ await fs.lstat(path2.join(r.state_dir, "journal"));
+ throw new Error("Pi journal has no session identity");
+ } catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ }
+ await writeJSON(identityPath, expected, 4 * 1024 * 1024);
+ }
+ await fs.rm(path2.join(r.state_dir, "terminal.json"), { force: true });
+ return async () => {
+ await lock.close();
+ await fs.unlink(path2.join(r.state_dir, "owner.lock"));
+ };
+ } catch (error) {
+ await lock.close();
+ await fs.rm(path2.join(r.state_dir, "owner.lock"), { force: true });
+ throw error;
+ }
+}
+async function processInventory() {
+ const found = /* @__PURE__ */ new Map();
+ for (const pid of (await fs.readdir("/proc")).filter((name) => /^\d+$/.test(name))) {
+ const stat2 = await fs.readFile(`/proc/${pid}/stat`, "utf8");
+ const fields = stat2.slice(stat2.lastIndexOf(")") + 2).trim().split(/\s+/);
+ if (fields.length < 20) throw new Error("unreadable process inventory");
+ found.set(Number(pid), fields[19]);
+ }
+ return found;
+}
+function extraProcesses(baseline, current) {
+ return [...current].filter(([pid, start]) => baseline.get(pid) !== start).map(([pid]) => pid);
+}
+function summarizeUsage(r, ledger, uncertain) {
+ const models = ledger?.models ?? {};
+ const tools = ledger?.tools ?? {};
+ const values = Object.values(models);
+ const valid = values.length > 0 && values.every((u) => ["input", "output", "cacheRead", "cacheWrite", "totalTokens"].every((k) => Number.isSafeInteger(u[k]) && u[k] >= 0) && u.totalTokens > 0);
+ const tokensIn = valid ? values.reduce((n, u) => n + u.input + u.cacheRead + u.cacheWrite, 0) : null;
+ const tokensOut = valid ? values.reduce((n, u) => n + u.output, 0) : null;
+ const complete2 = !uncertain && valid && Number.isSafeInteger(tokensIn) && Number.isSafeInteger(tokensOut);
+ const estimate = complete2 && r.metadata.pricingKnown && values.every((u) => Number.isFinite(u.cost?.total) && u.cost.total >= 0) ? values.reduce((n, u) => n + u.cost.total, 0) : null;
+ const cost = Number.isFinite(estimate) ? estimate : null;
+ return {
+ contract_version: CONTRACT,
+ run_id: r.run_id,
+ fingerprint: r.fingerprint,
+ complete: complete2,
+ tokens_in: complete2 ? tokensIn : null,
+ tokens_out: complete2 ? tokensOut : null,
+ cost_usd: cost,
+ cost_basis: cost === null ? "unavailable" : "estimated",
+ recorded_tokens_in: tokensIn,
+ recorded_tokens_out: tokensOut,
+ uncertainty: uncertain ? "interrupted or incomplete provider usage; recorded measurements are a known floor" : valid ? null : "provider usage unavailable",
+ models,
+ tools
+ };
+}
+
+// src/engine.mjs
+var instructions = `You are a coding agent inside one disposable ESF CubeSandbox microVM.
+Use the supplied repository and task. Read AGENTS.md and the factory inventory before editing.
+Do not alter factory metadata, verification commands, or installed agent/runtime files.
+The factory independently verifies your changes. Your final answer is not verification evidence.
+If blocked, write ../.factory/blocked.json beside the repository with a nonempty reason and optional detail, then stop.
+An interrupted tool may have partially changed files. Inspect the current tree before making more changes.
+Do not create background/daemon processes or access destinations outside operator policy.`;
+async function engine(request, channel) {
+ const r = validateRequest(request);
+ const abort = new AbortController();
+ const context = withAbortSignal(abort.signal, BACKGROUND_CONTEXT);
+ let harness, root, events;
+ channel.onStop(async () => {
+ abort.abort();
+ if (root) await root.abort(BACKGROUND_CONTEXT).catch(() => {
+ });
+ });
+ const models = createModels();
+ const api = r.api === "openai-responses" ? openAIResponsesApi() : openAICompletionsApi();
+ const tracked = (method) => (model, messages, options) => {
+ const outer = new AssistantMessageEventStream();
+ (async () => {
+ const source = api[method](model, messages, options);
+ for await (const event of source) {
+ if (event.type === "done" || event.type === "error") {
+ const message = event.message ?? event.error;
+ if (!message?.usage?.totalTokens || event.type === "error") await channel.notify("usage-incomplete");
+ }
+ outer.push(event);
+ }
+ outer.end(await source.result());
+ })().catch((error) => {
+ outer.end();
+ channel.fatal(error);
+ });
+ return outer;
+ };
+ const metadata = r.metadata;
+ models.setProvider(createProvider({
+ id: r.provider,
+ name: r.provider,
+ baseUrl: r.base_url,
+ auth: { apiKey: { name: "ESF operator model connection", resolve: async () => ({ auth: { apiKey: process.env.ESF_PI_API_KEY ?? "cube-egress-managed-placeholder" }, source: "ESF" }) } },
+ models: [{
+ id: r.model,
+ name: metadata.name,
+ provider: r.provider,
+ api: r.api,
+ baseUrl: r.base_url,
+ reasoning: metadata.reasoning,
+ input: metadata.input,
+ contextWindow: metadata.contextWindow,
+ maxTokens: metadata.maxTokens,
+ thinkingLevelMap: metadata.thinkingLevelMap,
+ compat: metadata.compat,
+ cost: metadata.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
+ }],
+ api: { [r.api]: { stream: tracked("stream"), streamSimple: tracked("streamSimple") } }
+ }));
+ const bash = createBashTool();
+ const guardedBash = { ...bash, replay: "unsafe", execute: async (args, api2, ctx) => {
+ await channel.notify("shell-start", { call_id: api2.callId });
+ try {
+ return await bash.execute(args, api2, ctx);
+ } finally {
+ await channel.notify("shell-end", { call_id: api2.callId });
+ }
+ } };
+ const registry = createRegistry();
+ registry.install(defineExtension({
+ name: "esf-coding",
+ sections: [section("esf", () => instructions, { tag: false })],
+ tools: [createReadTool(), createWriteTool(), createEditTool(), guardedBash].map((tool) => ({ ...tool, replay: "unsafe" }))
+ }));
+ try {
+ const storage = await openNodeJsonlStorage(path3.join(r.state_dir, "journal"), context, { fsync: true });
+ harness = await Harness.open(storage, {
+ models,
+ registry,
+ env: (target) => new NodeExecutionEnv({ cwd: target.cwd ?? r.repository_dir }),
+ settings: {
+ toolExecution: "sequential",
+ retry: { enabled: false },
+ stream: { maxRetries: 0, maxTokens: metadata.maxTokens },
+ compaction: {
+ enabled: true,
+ reserveTokens: metadata.maxTokens,
+ keepRecentTokens: Math.min(2e4, Math.floor(metadata.contextWindow / 4)),
+ backgroundTokens: 0
+ }
+ }
+ }, context);
+ root = await harness.root(context, { agent: {
+ model: { provider: r.provider, modelId: r.model },
+ thinkingLevel: r.thinking_level,
+ cwd: r.repository_dir
+ } });
+ events = await watchEvents(harness, root.id, context);
+ await channel.audit(events.snapshot);
+ await channel.usage(events.snapshot.usage);
+ events.start(async (batch) => {
+ for (const event of batch) {
+ await channel.audit(event);
+ if (event.type === "usage_changed" || event.type === "snapshot") await channel.usage(event.usage);
+ }
+ });
+ const submission = await root.submit({ type: "input", content: r.prompt, requestId: r.request_id }, context);
+ const settled = await submission.wait(context);
+ await channel.audit({ type: "submission", record: settled });
+ const ledger = await harness.usage(context);
+ await events.stop();
+ events = void 0;
+ await harness.close(BACKGROUND_CONTEXT);
+ harness = void 0;
+ return {
+ status: settled.status === "done" ? "completed" : "failed",
+ error: settled.status === "done" ? void 0 : `Pi submission ${settled.reason ?? settled.status}`,
+ ledger
+ };
+ } finally {
+ await events?.stop().catch(() => {
+ });
+ await harness?.close(BACKGROUND_CONTEXT).catch(() => {
+ });
+ }
+}
+
+// src/supervisor.mjs
+import { spawn as spawn2 } from "node:child_process";
+import { createReadStream } from "node:fs";
+import { createHash as createHash3 } from "node:crypto";
+import * as fs2 from "node:fs/promises";
+import path4 from "node:path";
+import { performance as performance2 } from "node:perf_hooks";
+async function supervise(request, executable, options = {}) {
+ const r = validateRequest(request);
+ const release = await prepareState(r);
+ const started = performance2.now();
+ const inspect = options.inventory ?? processInventory;
+ let ledger = { models: {}, tools: {} }, uncertain = false, restarts = 0, stopped;
+ const attempts = [];
+ let activeChild;
+ const stop = (reason) => {
+ stopped ??= reason;
+ activeChild?.send({ type: "stop" }, () => {
+ });
+ const child = activeChild;
+ const kill = setTimeout(() => {
+ if (child?.exitCode === null && child?.signalCode === null) child.kill("SIGKILL");
+ }, 1e3);
+ kill.unref();
+ };
+ const cancel = () => stop("cancelled");
+ process.on("SIGTERM", cancel);
+ process.on("SIGINT", cancel);
+ const timer = setTimeout(() => stop("timeout"), r.timeout_ms);
+ const log = options.log ?? ((event) => process.stdout.write(JSON.stringify(event) + "\n"));
+ const base = { contract_version: CONTRACT, run_id: r.run_id, request_id: r.request_id, fingerprint: r.fingerprint, model: r.model };
+ let result;
+ try {
+ try {
+ const previous = await readJSON(path4.join(r.state_dir, "usage.json"));
+ if (previous.contract_version !== CONTRACT || previous.run_id !== r.run_id || previous.fingerprint !== r.fingerprint) throw new Error("Pi usage identity mismatch");
+ uncertain = previous.complete !== true;
+ } catch (error) {
+ if (error.code !== "ENOENT") throw error;
+ try {
+ await fs2.lstat(path4.join(r.state_dir, "journal"));
+ uncertain = true;
+ } catch (missing) {
+ if (missing.code !== "ENOENT") throw missing;
+ }
+ }
+ const baseline = await inspect();
+ for (; ; ) {
+ const remaining = r.timeout_ms - (performance2.now() - started);
+ if (stopped || remaining <= 0) {
+ stopped ??= "timeout";
+ result = { status: stopped, error: stopped };
+ break;
+ }
+ if (restarts > 0) {
+ const stat2 = await fs2.lstat(path4.join(r.state_dir, "journal", "main.jsonl"));
+ if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size === 0) throw new Error("cannot recover missing Pi journal");
+ }
+ for (const [file, expected] of [[process.execPath, r.runtime_sha256], [executable, r.runner_sha256]]) {
+ const hash = createHash3("sha256");
+ for await (const bytes of createReadStream(file)) hash.update(bytes);
+ if (hash.digest("hex") !== expected) throw new Error("Pi execution-chain digest mismatch");
+ }
+ if (stopped || performance2.now() - started >= r.timeout_ms) {
+ stopped ??= "timeout";
+ result = { status: stopped, error: stopped };
+ break;
+ }
+ let terminal, fatal, protocolError;
+ const activeShell = /* @__PURE__ */ new Set();
+ const child = spawn2(process.execPath, [...process.execArgv, executable, "--engine"], {
+ cwd: r.repository_dir,
+ stdio: ["pipe", "pipe", "pipe", "ipc"],
+ env: { ...process.env }
+ });
+ activeChild = child;
+ log({ ...base, type: "engine_started", pid: child.pid, attempt: restarts + 1 });
+ child.stdout.pipe(process.stdout, { end: false });
+ child.stderr.pipe(process.stderr, { end: false });
+ child.on("message", (message) => {
+ try {
+ if (!message || typeof message !== "object") throw new Error("invalid engine message");
+ if (message.type === "shell-start") {
+ if (!message.call_id || activeShell.has(message.call_id)) throw new Error("invalid shell ownership");
+ activeShell.add(message.call_id);
+ log({ ...base, type: "shell_guard", phase: "active", call_id: message.call_id });
+ } else if (message.type === "shell-end") {
+ if (!activeShell.delete(message.call_id)) throw new Error("unknown shell ownership");
+ log({ ...base, type: "shell_guard", phase: "released", call_id: message.call_id });
+ } else if (message.type === "usage-incomplete") uncertain = true;
+ else if (message.type === "usage") ledger = message.ledger;
+ else if (message.type === "audit") log({ ...base, type: "agent_event", attempt: restarts + 1, event: message.event });
+ else if (message.type === "terminal") {
+ if (terminal || !["completed", "failed"].includes(message.result?.status)) throw new Error("invalid terminal result");
+ terminal = message.result;
+ ledger = terminal.ledger;
+ } else if (message.type === "fatal") fatal = String(message.error ?? "Pi engine failed");
+ else throw new Error("unknown engine message");
+ if (message.id !== void 0) child.send({ type: "ack", id: message.id }, () => {
+ });
+ } catch (error) {
+ protocolError = error.message;
+ child.kill("SIGKILL");
+ }
+ });
+ const exited = new Promise((resolve3, reject) => {
+ child.once("error", reject);
+ child.once("exit", (code, signal) => resolve3({ code, signal }));
+ });
+ child.stdin.end(JSON.stringify(r));
+ const exit = await exited;
+ activeChild = void 0;
+ attempts.push({ attempt: restarts + 1, ...exit, active_shell: activeShell.size > 0 });
+ if (stopped) {
+ uncertain = true;
+ result = { status: stopped, error: stopped };
+ break;
+ }
+ if (protocolError || fatal) {
+ uncertain = true;
+ result = { status: "failed", error: protocolError ?? fatal };
+ break;
+ }
+ if (terminal) {
+ result = terminal;
+ uncertain ||= terminal.status !== "completed";
+ break;
+ }
+ uncertain = true;
+ if (activeShell.size) {
+ result = { status: "failed", error: "engine crashed during shell execution; recovery refused" };
+ break;
+ }
+ const additional = extraProcesses(baseline, await inspect());
+ if (additional.length) {
+ result = { status: "failed", error: "live additional processes remain; recovery refused" };
+ break;
+ }
+ if (restarts >= r.max_process_restarts) {
+ result = { status: "failed", error: "Pi process restart allowance exhausted" };
+ break;
+ }
+ restarts++;
+ log({ ...base, type: "process_recovery", restarts });
+ }
+ } catch (error) {
+ uncertain = true;
+ result = { status: stopped ?? "failed", error: error.message };
+ } finally {
+ clearTimeout(timer);
+ process.off("SIGTERM", cancel);
+ process.off("SIGINT", cancel);
+ }
+ try {
+ await writeJSON(path4.join(r.state_dir, "usage.json"), summarizeUsage(r, ledger, uncertain));
+ await writeJSON(path4.join(r.state_dir, "recovery.json"), { ...base, restarts, attempts, error: result.error });
+ await writeJSON(path4.join(r.state_dir, "terminal.json"), { ...base, status: result.status, error: result.error, restarts });
+ log({ ...base, type: "terminal", status: result.status, restarts });
+ return result.status === "completed" ? 0 : 1;
+ } finally {
+ await release();
+ }
+}
+
+// src/runner.mjs
+async function readRequest() {
+ const chunks = [];
+ let bytes = 0;
+ for await (const chunk of process.stdin) {
+ bytes += chunk.length;
+ if (bytes > 4 * 1024 * 1024) throw new Error("Pi request exceeds size limit");
+ chunks.push(chunk);
+ }
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
+}
+function engineChannel() {
+ let sequence2 = 0, stopping;
+ const pending = /* @__PURE__ */ new Map();
+ process.on("message", (message) => {
+ if (message.type === "stop") {
+ void stopping?.();
+ }
+ if (message.type === "ack") {
+ pending.get(message.id)?.();
+ pending.delete(message.id);
+ }
+ });
+ process.on("disconnect", () => {
+ void stopping?.();
+ });
+ const notify = (type, payload = {}) => new Promise((resolve3, reject) => {
+ const id = ++sequence2;
+ pending.set(id, resolve3);
+ process.send({ type, id, ...payload }, (error) => {
+ if (error) {
+ pending.delete(id);
+ reject(error);
+ }
+ });
+ });
+ return {
+ notify,
+ onStop: (callback) => {
+ stopping = callback;
+ },
+ audit: (event) => notify("audit", { event }),
+ usage: (ledger) => notify("usage", { ledger }),
+ fatal: (error) => {
+ process.send({ type: "fatal", error: String(error.message ?? error).slice(0, SUMMARY_LIMIT) });
+ void stopping?.();
+ }
+ };
+}
+async function main() {
+ const [major, minor] = process.versions.node.split(".").map(Number);
+ if (major < 22 || major === 22 && minor < 19) throw new Error("Pi requires Node >=22.19");
+ if (process.argv[2] === "--version") {
+ console.log(`esf-pi/1 pi-durable/1.0.3 node/${process.versions.node}`);
+ return 0;
+ }
+ const request = await readRequest();
+ if (process.argv[2] === "--engine") {
+ if (!process.send) throw new Error("Pi engine must be owned by its supervisor");
+ const channel = engineChannel();
+ try {
+ await channel.notify("terminal", { result: await engine(request, channel) });
+ return 0;
+ } catch (error) {
+ await channel.notify("fatal", { error: String(error.message ?? error).slice(0, SUMMARY_LIMIT) });
+ return 1;
+ } finally {
+ process.disconnect();
+ }
+ }
+ if (process.argv.length !== 2) throw new Error("Pi invocation is fixed");
+ return supervise(request, fileURLToPath2(import.meta.url));
+}
+if (process.argv[1] && fileURLToPath2(import.meta.url) === process.argv[1]) {
+ main().then((code) => {
+ process.exitCode = code;
+ }).catch((error) => {
+ console.error(`pi: ${error.message}`);
+ process.exitCode = 1;
+ });
+}
+export {
+ main,
+ readRequest
+};
diff --git a/agents/pi/export-catalog.mjs b/agents/pi/export-catalog.mjs
new file mode 100644
index 0000000..5c14599
--- /dev/null
+++ b/agents/pi/export-catalog.mjs
@@ -0,0 +1,21 @@
+// Export the published, locked 1.0.3 catalog for pre-allocation Go validation.
+// No network refresh occurs at configuration or execution time.
+import { MODELS } from './node_modules/@earendil-works/pi-ai/dist/models.generated.js';
+import { getSupportedThinkingLevels } from '@earendil-works/pi-ai/models';
+import * as fs from 'node:fs/promises';
+
+const catalog = {};
+for (const [provider, entries] of Object.entries(MODELS)) {
+ for (const model of Object.values(entries)) {
+ if (!['openai-completions', 'openai-responses'].includes(model.api) || !model.input.includes('text')) continue;
+ // Tiered prices require a richer ESF metadata contract; usage remains
+ // measurable, but v1 does not advertise a complete cost estimate for them.
+ const pricingKnown = !model.cost.tiers?.length && Object.values(model.cost).some(v => typeof v === 'number' && v > 0);
+ const definition = { id: model.id, name: model.name, api: model.api, reasoning: model.reasoning,
+ input: ['text'], contextWindow: model.contextWindow, maxTokens: model.maxTokens,
+ pricingKnown, cost: { input: model.cost.input, output: model.cost.output, cacheRead: model.cost.cacheRead, cacheWrite: model.cost.cacheWrite },
+ thinkingLevels: getSupportedThinkingLevels(model), thinkingLevelMap: model.thinkingLevelMap, compat: model.compat };
+ (catalog[provider] ??= {})[model.id] = definition;
+ }
+}
+await fs.writeFile(process.argv[2] ?? '../../internal/agentharness/pi-catalog.json', JSON.stringify(catalog, null, 2) + '\n');
diff --git a/agents/pi/inventory.json b/agents/pi/inventory.json
new file mode 100644
index 0000000..a87b350
--- /dev/null
+++ b/agents/pi/inventory.json
@@ -0,0 +1,25 @@
+{
+ "schema_version": 1,
+ "contract_version": "esf/pi/v1",
+ "support_status": "candidate-awaiting-model-backed-acceptance",
+ "pi_durable": {
+ "version": "1.0.3",
+ "license": "MIT",
+ "git_commit": "d78dc83d633229d12f8b79631384c4c2717c399f",
+ "minimum_node": "22.19.0"
+ },
+ "runner": {
+ "path": "/opt/esf/agents/pi-runner.mjs",
+ "sha256": "9dab48151c793cf3265af4058ea7aac8671d1778b31873ee25ac3fc24afe0e2c"
+ },
+ "runtime": {
+ "path": "/opt/esf/agents/node",
+ "version": "24.21.0",
+ "license": "MIT",
+ "image": "docker.io/library/node@sha256:0e0ff40c39bc087845bfb27465a0df4ea419520094bc35842ff83dd8cbe6f9b6",
+ "sha256": "7fde7b8afa198da66257f42ee2001d874c7355631e6d1579a5fb5ef1f246df4c"
+ },
+ "package_lock_sha256": "909cc3c6ceea137dc29d121f533ddcd4c82b3350457a5a21d29846bb23e5dd98",
+ "model_catalog_sha256": "0f261990fb8f92f7655fbef550d2af28ef510a3738b2ca5d8b8704a1e5c37f3a",
+ "third_party_notices_sha256": "1d09363e1a6adcaed895c481a39058f513f5caf8293220cf07a7a7078b275478"
+}
diff --git a/agents/pi/models/deterministic.json b/agents/pi/models/deterministic.json
new file mode 100644
index 0000000..f8a9143
--- /dev/null
+++ b/agents/pi/models/deterministic.json
@@ -0,0 +1,11 @@
+{
+ "id": "test-model",
+ "name": "ESF deterministic acceptance provider",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": ["text"],
+ "contextWindow": 32768,
+ "maxTokens": 1024,
+ "pricingKnown": false,
+ "thinkingLevels": ["off"]
+}
diff --git a/agents/pi/notices.mjs b/agents/pi/notices.mjs
new file mode 100644
index 0000000..c2e6a05
--- /dev/null
+++ b/agents/pi/notices.mjs
@@ -0,0 +1,35 @@
+import * as fs from 'node:fs/promises';
+import path from 'node:path';
+
+// Include notices for the modules actually bundled, plus the pinned runtime.
+// Read only installed packages from the frozen dependency graph.
+export async function writeNotices(inputs) {
+ const packages = new Map();
+ for (const input of inputs.filter(file => file.includes('node_modules/'))) {
+ let directory = path.dirname(path.resolve(input));
+ for (;;) {
+ try {
+ const pkg = JSON.parse(await fs.readFile(path.join(directory, 'package.json'), 'utf8'));
+ if (pkg.name && pkg.version) { packages.set(pkg.name, { directory, pkg }); break; }
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
+ const parent = path.dirname(directory);
+ if (parent === directory) throw new Error(`missing package identity for ${input}`);
+ directory = parent;
+ }
+ }
+ const sections = ['ESF Pi runner: bundled dependency and runtime notices\n'];
+ for (const [name, { directory, pkg }] of [...packages].sort(([a], [b]) => a.localeCompare(b, 'en'))) {
+ const notices = [];
+ if (name.startsWith('@earendil-works/')) notices.push(await fs.readFile('LICENSE.pi', 'utf8'));
+ else {
+ const files = (await fs.readdir(directory)).filter(file => /^(license|licence|copying|notice)([._-].*)?$/i.test(file)).sort();
+ for (const file of files) {
+ if ((await fs.stat(path.join(directory, file))).isFile()) notices.push(await fs.readFile(path.join(directory, file), 'utf8'));
+ }
+ }
+ if (!notices.length) throw new Error(`missing bundled license notice for ${name}@${pkg.version}`);
+ sections.push(`===== ${name}@${pkg.version} (${pkg.license ?? 'see notice'}) =====\n${notices.join('\n')}`);
+ }
+ sections.push(`===== Node.js 24.21.0 =====\n${await fs.readFile('LICENSE.node', 'utf8')}`);
+ await fs.writeFile('dist/THIRD_PARTY_NOTICES.txt', sections.join('\n\n') + '\n');
+}
diff --git a/agents/pi/package-lock.json b/agents/pi/package-lock.json
new file mode 100644
index 0000000..1ebb97e
--- /dev/null
+++ b/agents/pi/package-lock.json
@@ -0,0 +1,2105 @@
+{
+ "name": "esf-pi-agent",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "esf-pi-agent",
+ "version": "1.0.0",
+ "dependencies": {
+ "@earendil-works/chord": "1.0.3",
+ "@earendil-works/pi-ai": "1.0.3",
+ "@earendil-works/pi-durable": "1.0.3"
+ },
+ "devDependencies": {
+ "esbuild": "0.25.12"
+ },
+ "engines": {
+ "node": ">=22.19.0"
+ }
+ },
+ "node_modules/@anthropic-ai/sdk": {
+ "version": "0.129.0",
+ "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.129.0.tgz",
+ "integrity": "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw==",
+ "license": "MIT",
+ "dependencies": {
+ "json-schema-to-ts": "^3.1.1",
+ "standardwebhooks": "^1.0.0"
+ },
+ "bin": {
+ "anthropic-ai-sdk": "bin/cli"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.0 || ^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "zod": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@aws-sdk/client-bedrock-runtime": {
+ "version": "3.1127.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/client-bedrock-runtime/-/client-bedrock-runtime-3.1127.0.tgz",
+ "integrity": "sha512-IDl/lrPb90aH+pZFHGNDmgH9nAUQj5PlZH1sJ3w7RikctyjHSnY3oNjZhrLoaBoQn/rNK0zsP6OHEqEhj2tdLA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.977.9",
+ "@aws-sdk/credential-provider-node": "^3.972.82",
+ "@aws-sdk/eventstream-handler-node": "^3.972.34",
+ "@aws-sdk/middleware-eventstream": "^3.972.29",
+ "@aws-sdk/middleware-websocket": "^3.972.52",
+ "@aws-sdk/token-providers": "3.1127.0",
+ "@aws-sdk/types": "^3.974.5",
+ "@smithy/core": "^3.33.3",
+ "@smithy/fetch-http-handler": "^5.7.2",
+ "@smithy/node-http-handler": "^4.11.3",
+ "@smithy/types": "^4.17.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/core": {
+ "version": "3.978.1",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.1.tgz",
+ "integrity": "sha512-LbY9aGsEiznDWmUc30Nwv3aIX/+dbwTx8KfS0yOC3NPYMO+O91e6jkT1azf34FwjOndq8/Q+RcVVZz5xnerwdg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "^3.974.6",
+ "@aws-sdk/xml-builder": "^3.972.41",
+ "@aws/lambda-invoke-store": "^0.3.0",
+ "@smithy/core": "^3.35.0",
+ "@smithy/signature-v4": "^5.7.3",
+ "@smithy/types": "^4.19.0",
+ "bowser": "^2.11.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-env": {
+ "version": "3.972.72",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.72.tgz",
+ "integrity": "sha512-xTKO/FWJPozTIXbozVnVGoNBhaGba8TBcx+KyUjRVeOlXE+dUc7GTR1cLvu0uTdIdmemzaFbqqCshXeZA1fZew==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-http": {
+ "version": "3.972.74",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.74.tgz",
+ "integrity": "sha512-u91E/hT8f4d1xy0Jl7VG4nVKJ3lxbrZkoBTeSVoJdWBiSEUMwMS/9+e0H/aJVQV//Lt5wuzP+E69v4aRSsNTmw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/fetch-http-handler": "^5.8.0",
+ "@smithy/node-http-handler": "^4.12.1",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-ini": {
+ "version": "3.973.17",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.17.tgz",
+ "integrity": "sha512-ged4KXdBkvIC81bLvNHHuQKdKak/VXhQTR1NWYTTqW0474nlmsxy9O/vlgTIohDDWH3xpBdtVMZRyjb+DnocDA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/credential-provider-env": "^3.972.72",
+ "@aws-sdk/credential-provider-http": "^3.972.74",
+ "@aws-sdk/credential-provider-login": "^3.972.79",
+ "@aws-sdk/credential-provider-process": "^3.972.72",
+ "@aws-sdk/credential-provider-sso": "^3.973.16",
+ "@aws-sdk/credential-provider-web-identity": "^3.972.78",
+ "@aws-sdk/nested-clients": "^3.997.46",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/credential-provider-imds": "^4.5.2",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-login": {
+ "version": "3.972.79",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.79.tgz",
+ "integrity": "sha512-L+Z85anONJd8MaiuraO4wRxATCdEejBZ3K3eymzWI5JPXa9sOS9CkIm72PBKqXKX+Z9p9NGMX5AIMXm0LEflgw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/nested-clients": "^3.997.46",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-node": {
+ "version": "3.972.84",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.84.tgz",
+ "integrity": "sha512-oHt854odINVwzwsh+c5x69j0ajm4DbqqqVJ+O1ECsCIZeMDAbzFpXItaqP7UZstJj/ATdTk/KFSH0LaNAgV+kA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/credential-provider-env": "^3.972.72",
+ "@aws-sdk/credential-provider-http": "^3.972.74",
+ "@aws-sdk/credential-provider-ini": "^3.973.17",
+ "@aws-sdk/credential-provider-process": "^3.972.72",
+ "@aws-sdk/credential-provider-sso": "^3.973.16",
+ "@aws-sdk/credential-provider-web-identity": "^3.972.78",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/credential-provider-imds": "^4.5.2",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-process": {
+ "version": "3.972.72",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.72.tgz",
+ "integrity": "sha512-rLIp2xbMjX/k9/od7APpqq1ZgXXnV0pOL1Th3ZsL8Wu0TRtBsDTVS8iPqcfRFcHakFxPvR04OSTv2ka2qOb/2A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-sso": {
+ "version": "3.973.16",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.16.tgz",
+ "integrity": "sha512-IGihaJfFZYacJJr/odqILCoK7W/mvrZ7cuK7ECn3sAu4vLC6u0V8bS7mCGbdugJ8Aum2tnvqmx0F2MRFp2rn9g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/nested-clients": "^3.997.46",
+ "@aws-sdk/token-providers": "3.1138.0",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers": {
+ "version": "3.1138.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1138.0.tgz",
+ "integrity": "sha512-GpyAr0DD63YOEmYFM6Df+gJuIgC92MMTiBK4FTKfxii5MJ9ge20epR7LyroulscYlG89J+ZB2ivFDPjvfQhzdw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/nested-clients": "^3.997.46",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/credential-provider-web-identity": {
+ "version": "3.972.78",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.78.tgz",
+ "integrity": "sha512-/y9WvNtlcPBGLR0qc1a+9J/xtYZfVczvLUOuXaVWylzttH7ewsxwHtjmiJSolNrVSDorIxHGHMU61CbonRkmwA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/nested-clients": "^3.997.46",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/eventstream-handler-node": {
+ "version": "3.972.35",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-handler-node/-/eventstream-handler-node-3.972.35.tgz",
+ "integrity": "sha512-a8xilRoRaalvSPZdfrs0VY3/BPc0uYhXW56Z/k6nmZ5Vk430LHeowf9APIPq8utM3tMJSNGSSuJMlB9YrPsN+A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/middleware-eventstream": {
+ "version": "3.972.30",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-eventstream/-/middleware-eventstream-3.972.30.tgz",
+ "integrity": "sha512-B6gvZlcnRBNWraKgyEjKsbhv+VjtbyHmpU7hmtTHzXpDSxHPpCJnYLpglEOOsF+SFne20DbZC5IVC1aNr2Pb4A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/middleware-websocket": {
+ "version": "3.972.54",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-websocket/-/middleware-websocket-3.972.54.tgz",
+ "integrity": "sha512-bhESdru8u8KosziH8jcVta/NM/dNreeRz2+2aU86si5bfBYOiJ6IiqD+9U4URUcU5WJO3Yw+jO3GLDIHlscXMQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/fetch-http-handler": "^5.8.0",
+ "@smithy/signature-v4": "^5.7.3",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/nested-clients": {
+ "version": "3.997.46",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.46.tgz",
+ "integrity": "sha512-oRxtBcka/JGHGs9l9p9IVajGoTP8vTPmoAzdHGy4Qcy9P5vPnDf6nhIeM/COQNY9k/OahImTRaLkHftoXvfcmQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.978.1",
+ "@aws-sdk/signature-v4-multi-region": "^3.996.47",
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/core": "^3.35.0",
+ "@smithy/fetch-http-handler": "^5.8.0",
+ "@smithy/node-http-handler": "^4.12.1",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/signature-v4-multi-region": {
+ "version": "3.996.47",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.47.tgz",
+ "integrity": "sha512-Zk08macMvQTHzQJCLJVkOlviVoqwYMrpXv4lmLN7b7sAbiMoOK7Go0NYdR5UeF+MW8LIbRmwrNy9u/5VvX1U5g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/types": "^3.974.6",
+ "@smithy/signature-v4": "^5.7.3",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/token-providers": {
+ "version": "3.1127.0",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1127.0.tgz",
+ "integrity": "sha512-Dv2TMWBshJ+tF6ahs2Sy5bh4Iabsd4GAQqVvE9XZmYmnoaVbpS2QKIKE/HRacc7bTtbjEEvP+laGzHvHlf1CiQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@aws-sdk/core": "^3.977.9",
+ "@aws-sdk/nested-clients": "^3.997.44",
+ "@aws-sdk/types": "^3.974.5",
+ "@smithy/core": "^3.33.3",
+ "@smithy/types": "^4.17.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/types": {
+ "version": "3.974.6",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.6.tgz",
+ "integrity": "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws-sdk/xml-builder": {
+ "version": "3.972.41",
+ "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.41.tgz",
+ "integrity": "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/@aws/lambda-invoke-store": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz",
+ "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@babel/runtime": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@earendil-works/chord": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@earendil-works/chord/-/chord-1.0.3.tgz",
+ "integrity": "sha512-H5pKMs3S1z2q4V7NkDGKDFzOMW+OkzdsnGxxj5wNJUANG03VKj29UVmc1xnnnf0FAc03COHYNxwgNApO0nt0fg==",
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "0.28.2"
+ },
+ "engines": {
+ "node": ">=22.19.0"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/android-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/android-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/android-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/linux-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/@esbuild/win32-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@earendil-works/chord/node_modules/esbuild": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.2",
+ "@esbuild/android-arm": "0.28.2",
+ "@esbuild/android-arm64": "0.28.2",
+ "@esbuild/android-x64": "0.28.2",
+ "@esbuild/darwin-arm64": "0.28.2",
+ "@esbuild/darwin-x64": "0.28.2",
+ "@esbuild/freebsd-arm64": "0.28.2",
+ "@esbuild/freebsd-x64": "0.28.2",
+ "@esbuild/linux-arm": "0.28.2",
+ "@esbuild/linux-arm64": "0.28.2",
+ "@esbuild/linux-ia32": "0.28.2",
+ "@esbuild/linux-loong64": "0.28.2",
+ "@esbuild/linux-mips64el": "0.28.2",
+ "@esbuild/linux-ppc64": "0.28.2",
+ "@esbuild/linux-riscv64": "0.28.2",
+ "@esbuild/linux-s390x": "0.28.2",
+ "@esbuild/linux-x64": "0.28.2",
+ "@esbuild/netbsd-arm64": "0.28.2",
+ "@esbuild/netbsd-x64": "0.28.2",
+ "@esbuild/openbsd-arm64": "0.28.2",
+ "@esbuild/openbsd-x64": "0.28.2",
+ "@esbuild/openharmony-arm64": "0.28.2",
+ "@esbuild/sunos-x64": "0.28.2",
+ "@esbuild/win32-arm64": "0.28.2",
+ "@esbuild/win32-ia32": "0.28.2",
+ "@esbuild/win32-x64": "0.28.2"
+ }
+ },
+ "node_modules/@earendil-works/pi-ai": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@earendil-works/pi-ai/-/pi-ai-1.0.3.tgz",
+ "integrity": "sha512-p+/EUrbmfT0xWOtL/NJRtWOsyzcKKFSyiivHLDBMG0DUVpHdaIykd5jFibq0YZDFGBN/nv61zdOelMb+ylPfSg==",
+ "license": "MIT",
+ "dependencies": {
+ "@anthropic-ai/sdk": "0.129.0",
+ "@aws-sdk/client-bedrock-runtime": "3.1127.0",
+ "@earendil-works/pi-telemetry": "^1.0.3",
+ "@google/genai": "2.21.0",
+ "@smithy/node-http-handler": "4.12.1",
+ "http-proxy-agent": "9.1.0",
+ "https-proxy-agent": "9.1.0",
+ "openai": "7.19.0",
+ "partial-json": "0.1.7",
+ "typebox": "1.3.27"
+ },
+ "bin": {
+ "pi-ai": "dist/cli.js"
+ },
+ "engines": {
+ "node": ">=22.19.0"
+ }
+ },
+ "node_modules/@earendil-works/pi-durable": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@earendil-works/pi-durable/-/pi-durable-1.0.3.tgz",
+ "integrity": "sha512-ARA+YQcqiQJz2pqxLL2ZA4ayZoulSDu1cMCMIYiKBnByTryGVfBhkEv6pT+QOP+3NgXzs0zPi3FpvyuSJ9harg==",
+ "license": "MIT",
+ "dependencies": {
+ "@earendil-works/chord": "^1.0.3",
+ "@earendil-works/pi-ai": "^1.0.3",
+ "diff": "8.0.4",
+ "typebox": "1.3.27"
+ },
+ "engines": {
+ "node": ">=22.19.0"
+ }
+ },
+ "node_modules/@earendil-works/pi-telemetry": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@earendil-works/pi-telemetry/-/pi-telemetry-1.0.3.tgz",
+ "integrity": "sha512-Li4YamN09x9zzCquPbtEL2AQmwqv3Vn3sNOYqG0DRg24fjiMfntCsb7QKbejCXZssTAyaN+hutLl6O0UnJDrfg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=22.19.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
+ "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
+ "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
+ "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
+ "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
+ "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
+ "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
+ "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
+ "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
+ "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
+ "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
+ "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
+ "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
+ "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
+ "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
+ "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
+ "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
+ "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
+ "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
+ "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
+ "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
+ "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
+ "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
+ "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@google/genai": {
+ "version": "2.21.0",
+ "resolved": "https://registry.npmjs.org/@google/genai/-/genai-2.21.0.tgz",
+ "integrity": "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q==",
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "google-auth-library": "^10.3.0",
+ "p-retry": "^4.6.2",
+ "protobufjs": "^7.5.4",
+ "ws": "^8.18.0"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "peerDependencies": {
+ "@modelcontextprotocol/sdk": "^1.25.2"
+ },
+ "peerDependenciesMeta": {
+ "@modelcontextprotocol/sdk": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@protobufjs/aspromise": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
+ "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/base64": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
+ "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/codegen": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
+ "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/eventemitter": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
+ "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/fetch": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
+ "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@protobufjs/aspromise": "^1.1.1"
+ }
+ },
+ "node_modules/@protobufjs/float": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
+ "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/path": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
+ "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/pool": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
+ "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/utf8": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz",
+ "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@smithy/core": {
+ "version": "3.35.1",
+ "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.35.1.tgz",
+ "integrity": "sha512-i4YPS4B6ts7bjn7UwLnGjiZdprOvHvgGobFZsYK3GIY3E5hIqtj0rReU69BcTpGp+fvtraSNXeG1l+jtJvF55w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/credential-provider-imds": {
+ "version": "4.5.2",
+ "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz",
+ "integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.2",
+ "@smithy/types": "^4.17.2",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/fetch-http-handler": {
+ "version": "5.8.0",
+ "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz",
+ "integrity": "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.3",
+ "@smithy/types": "^4.18.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/node-http-handler": {
+ "version": "4.12.1",
+ "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz",
+ "integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.33.3",
+ "@smithy/types": "^4.18.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/signature-v4": {
+ "version": "5.7.4",
+ "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.4.tgz",
+ "integrity": "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@smithy/core": "^3.35.0",
+ "@smithy/types": "^4.19.0",
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@smithy/types": {
+ "version": "4.19.0",
+ "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz",
+ "integrity": "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "tslib": "^2.6.2"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@stablelib/base64": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
+ "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.4",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz",
+ "integrity": "sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==",
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@types/retry": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
+ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
+ "license": "MIT"
+ },
+ "node_modules/agent-base": {
+ "version": "9.0.0",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-9.0.0.tgz",
+ "integrity": "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/bignumber.js": {
+ "version": "9.3.1",
+ "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
+ "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/bowser": {
+ "version": "2.14.1",
+ "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz",
+ "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==",
+ "license": "MIT"
+ },
+ "node_modules/buffer-equal-constant-time": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/data-uri-to-buffer": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
+ "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/diff": {
+ "version": "8.0.4",
+ "resolved": "https://registry.npmjs.org/diff/-/diff-8.0.4.tgz",
+ "integrity": "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.3.1"
+ }
+ },
+ "node_modules/ecdsa-sig-formatter": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.25.12",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
+ "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.12",
+ "@esbuild/android-arm": "0.25.12",
+ "@esbuild/android-arm64": "0.25.12",
+ "@esbuild/android-x64": "0.25.12",
+ "@esbuild/darwin-arm64": "0.25.12",
+ "@esbuild/darwin-x64": "0.25.12",
+ "@esbuild/freebsd-arm64": "0.25.12",
+ "@esbuild/freebsd-x64": "0.25.12",
+ "@esbuild/linux-arm": "0.25.12",
+ "@esbuild/linux-arm64": "0.25.12",
+ "@esbuild/linux-ia32": "0.25.12",
+ "@esbuild/linux-loong64": "0.25.12",
+ "@esbuild/linux-mips64el": "0.25.12",
+ "@esbuild/linux-ppc64": "0.25.12",
+ "@esbuild/linux-riscv64": "0.25.12",
+ "@esbuild/linux-s390x": "0.25.12",
+ "@esbuild/linux-x64": "0.25.12",
+ "@esbuild/netbsd-arm64": "0.25.12",
+ "@esbuild/netbsd-x64": "0.25.12",
+ "@esbuild/openbsd-arm64": "0.25.12",
+ "@esbuild/openbsd-x64": "0.25.12",
+ "@esbuild/openharmony-arm64": "0.25.12",
+ "@esbuild/sunos-x64": "0.25.12",
+ "@esbuild/win32-arm64": "0.25.12",
+ "@esbuild/win32-ia32": "0.25.12",
+ "@esbuild/win32-x64": "0.25.12"
+ }
+ },
+ "node_modules/extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
+ "license": "MIT"
+ },
+ "node_modules/fast-sha256": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
+ "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
+ "license": "Unlicense"
+ },
+ "node_modules/fetch-blob": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
+ "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/jimmywarting"
+ },
+ {
+ "type": "paypal",
+ "url": "https://paypal.me/jimmywarting"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "node-domexception": "^1.0.0",
+ "web-streams-polyfill": "^3.0.3"
+ },
+ "engines": {
+ "node": "^12.20 || >= 14.13"
+ }
+ },
+ "node_modules/formdata-polyfill": {
+ "version": "4.0.10",
+ "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
+ "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
+ "license": "MIT",
+ "dependencies": {
+ "fetch-blob": "^3.1.2"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/gaxios": {
+ "version": "7.3.1",
+ "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.3.1.tgz",
+ "integrity": "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "extend": "^3.0.2",
+ "https-proxy-agent": "^7.0.1",
+ "node-fetch": "^3.3.2"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/gaxios/node_modules/agent-base": {
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/gaxios/node_modules/https-proxy-agent": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/gcp-metadata": {
+ "version": "8.1.2",
+ "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.2.tgz",
+ "integrity": "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "gaxios": "^7.0.0",
+ "google-logging-utils": "^1.0.0",
+ "json-bigint": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/google-auth-library": {
+ "version": "10.9.1",
+ "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-10.9.1.tgz",
+ "integrity": "sha512-i1ydyHrqcIxXkWh/uBmVkzCvIuq5yiK2ATndIe5XxKholrG/MTYP9xGYka4sQhrbIAgGjL2B6NOE7rFaiF3fXw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "base64-js": "^1.3.0",
+ "ecdsa-sig-formatter": "^1.0.11",
+ "gaxios": "^7.1.4",
+ "gcp-metadata": "8.1.2",
+ "google-logging-utils": "1.1.3",
+ "jws": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/google-logging-utils": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-1.1.3.tgz",
+ "integrity": "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/http-proxy-agent": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-9.1.0.tgz",
+ "integrity": "sha512-2NxoveTT58mjYT4n3RPTEfCZGLMbidoO8XEieXfpSYxu+PQJ1qpx4ypwH6N+uF9twBPIvRRgvkvW5HUTYWENig==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "9.0.0",
+ "debug": "^4.3.4",
+ "proxy-agent-negotiate": "1.1.0"
+ },
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/https-proxy-agent": {
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-9.1.0.tgz",
+ "integrity": "sha512-ag87y7cJJ9/3+GxFr8Oy4O5faDsGRGnBGsJj/YjOSsSx/5eadKLYTMPlzuR6obgoCDDm0abAAZitXXQkMOPSpA==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "9.0.0",
+ "debug": "^4.3.4",
+ "proxy-agent-negotiate": "1.1.0"
+ },
+ "engines": {
+ "node": ">= 20"
+ }
+ },
+ "node_modules/json-bigint": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
+ "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",
+ "license": "MIT",
+ "dependencies": {
+ "bignumber.js": "^9.0.0"
+ }
+ },
+ "node_modules/json-schema-to-ts": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
+ "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.18.3",
+ "ts-algebra": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/jwa": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
+ "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer-equal-constant-time": "^1.0.1",
+ "ecdsa-sig-formatter": "1.0.11",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/jws": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
+ "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
+ "license": "MIT",
+ "dependencies": {
+ "jwa": "^2.0.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "node_modules/long": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/node-domexception": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
+ "deprecated": "Use your platform's native DOMException instead",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/jimmywarting"
+ },
+ {
+ "type": "github",
+ "url": "https://paypal.me/jimmywarting"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.5.0"
+ }
+ },
+ "node_modules/node-fetch": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
+ "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
+ "license": "MIT",
+ "dependencies": {
+ "data-uri-to-buffer": "^4.0.0",
+ "fetch-blob": "^3.1.4",
+ "formdata-polyfill": "^4.0.10"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/node-fetch"
+ }
+ },
+ "node_modules/openai": {
+ "version": "7.19.0",
+ "resolved": "https://registry.npmjs.org/openai/-/openai-7.19.0.tgz",
+ "integrity": "sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=22.0.0"
+ },
+ "peerDependencies": {
+ "@aws-sdk/credential-provider-node": ">=3.972.0 <4",
+ "@smithy/hash-node": ">=4.3.0 <5",
+ "@smithy/signature-v4": ">=5.4.0 <6",
+ "undici": ">=5 <9",
+ "ws": "^8.21.0",
+ "zod": "^3.25 || ^4.0"
+ },
+ "peerDependenciesMeta": {
+ "@aws-sdk/credential-provider-node": {
+ "optional": true
+ },
+ "@smithy/hash-node": {
+ "optional": true
+ },
+ "@smithy/signature-v4": {
+ "optional": true
+ },
+ "undici": {
+ "optional": true
+ },
+ "ws": {
+ "optional": true
+ },
+ "zod": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/p-retry": {
+ "version": "4.6.2",
+ "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
+ "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/retry": "0.12.0",
+ "retry": "^0.13.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/partial-json": {
+ "version": "0.1.7",
+ "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz",
+ "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==",
+ "license": "MIT"
+ },
+ "node_modules/protobufjs": {
+ "version": "7.6.6",
+ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz",
+ "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==",
+ "hasInstallScript": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@protobufjs/aspromise": "^1.1.2",
+ "@protobufjs/base64": "^1.1.2",
+ "@protobufjs/codegen": "^2.0.5",
+ "@protobufjs/eventemitter": "^1.1.1",
+ "@protobufjs/fetch": "^1.1.1",
+ "@protobufjs/float": "^1.0.2",
+ "@protobufjs/path": "^1.1.2",
+ "@protobufjs/pool": "^1.1.0",
+ "@protobufjs/utf8": "^1.1.1",
+ "@types/node": ">=13.7.0",
+ "long": "^5.3.2"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/proxy-agent-negotiate": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-agent-negotiate/-/proxy-agent-negotiate-1.1.0.tgz",
+ "integrity": "sha512-N8IBcM3UgCVzz2L2Lqv8DVntDnnC8/hiV4nEDUPkqq72TPUgYWjQc+bdZlBPZK9LzPAvOY//gAt0S0DApoOXWQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20"
+ },
+ "peerDependencies": {
+ "kerberos": "^2.0.0"
+ },
+ "peerDependenciesMeta": {
+ "kerberos": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/retry": {
+ "version": "0.13.1",
+ "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
+ "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 4"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/standardwebhooks": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz",
+ "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@stablelib/base64": "^1.0.0",
+ "fast-sha256": "^1.3.0"
+ }
+ },
+ "node_modules/ts-algebra": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
+ "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
+ "license": "MIT"
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD"
+ },
+ "node_modules/typebox": {
+ "version": "1.3.27",
+ "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.3.27.tgz",
+ "integrity": "sha512-zu+jc1pcy4UiNThxikUr36f0Rybk9PEeCg/NE6adeWr/SKsdNO4EzZHYRDlv2YCVAfj3Odq3dESSo/jNyoBXzA==",
+ "license": "MIT"
+ },
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "license": "MIT"
+ },
+ "node_modules/web-streams-polyfill": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
+ "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/ws": {
+ "version": "8.22.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
+ "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/agents/pi/package.json b/agents/pi/package.json
new file mode 100644
index 0000000..4ea733b
--- /dev/null
+++ b/agents/pi/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "esf-pi-agent",
+ "private": true,
+ "version": "1.0.0",
+ "type": "module",
+ "engines": { "node": ">=22.19.0" },
+ "scripts": {
+ "build": "node build.mjs",
+ "test": "node --test test/*.test.mjs"
+ },
+ "dependencies": {
+ "@earendil-works/pi-durable": "1.0.3",
+ "@earendil-works/pi-ai": "1.0.3",
+ "@earendil-works/chord": "1.0.3"
+ },
+ "devDependencies": { "esbuild": "0.25.12" },
+ "overrides": {
+ "@earendil-works/pi-durable": "1.0.3",
+ "@earendil-works/pi-ai": "1.0.3",
+ "@earendil-works/chord": "1.0.3"
+ }
+}
diff --git a/agents/pi/src/engine.mjs b/agents/pi/src/engine.mjs
new file mode 100644
index 0000000..9f55a86
--- /dev/null
+++ b/agents/pi/src/engine.mjs
@@ -0,0 +1,105 @@
+import path from 'node:path';
+import { BACKGROUND_CONTEXT, withAbortSignal } from '@earendil-works/chord/context';
+import { createModels, createProvider } from '@earendil-works/pi-ai/models';
+import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';
+import { openAIResponsesApi } from '@earendil-works/pi-ai/api/openai-responses.lazy';
+import { AssistantMessageEventStream } from '@earendil-works/pi-ai/utils/event-stream';
+import { createRegistry, defineExtension, Harness, section, watchEvents } from '@earendil-works/pi-durable';
+import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';
+import { createReadTool, createWriteTool, createEditTool, createBashTool } from '@earendil-works/pi-durable/tools';
+import { openNodeJsonlStorage } from '@earendil-works/pi-durable/storage/jsonl/node';
+import { validateRequest } from './protocol.mjs';
+
+const instructions = `You are a coding agent inside one disposable ESF CubeSandbox microVM.
+Use the supplied repository and task. Read AGENTS.md and the factory inventory before editing.
+Do not alter factory metadata, verification commands, or installed agent/runtime files.
+The factory independently verifies your changes. Your final answer is not verification evidence.
+If blocked, write ../.factory/blocked.json beside the repository with a nonempty reason and optional detail, then stop.
+An interrupted tool may have partially changed files. Inspect the current tree before making more changes.
+Do not create background/daemon processes or access destinations outside operator policy.`;
+
+export async function engine(request, channel) {
+ const r = validateRequest(request);
+ const abort = new AbortController();
+ const context = withAbortSignal(abort.signal, BACKGROUND_CONTEXT);
+ let harness, root, events;
+ channel.onStop(async () => {
+ abort.abort();
+ if (root) await root.abort(BACKGROUND_CONTEXT).catch(() => {});
+ });
+ const models = createModels();
+ const api = r.api === 'openai-responses' ? openAIResponsesApi() : openAICompletionsApi();
+ // Every provider attempt (including compaction) is observed. Zero usage can
+ // mean missing provider metering; never turn that into a zero-cost invoice.
+ const tracked = method => (model, messages, options) => {
+ const outer = new AssistantMessageEventStream();
+ (async () => {
+ const source = api[method](model, messages, options);
+ for await (const event of source) {
+ if (event.type === 'done' || event.type === 'error') {
+ const message = event.message ?? event.error;
+ if (!message?.usage?.totalTokens || event.type === 'error') await channel.notify('usage-incomplete');
+ }
+ outer.push(event);
+ }
+ outer.end(await source.result());
+ })().catch(error => { outer.end(); channel.fatal(error); });
+ return outer;
+ };
+ const metadata = r.metadata;
+ models.setProvider(createProvider({
+ id: r.provider, name: r.provider, baseUrl: r.base_url,
+ auth: { apiKey: { name: 'ESF operator model connection', resolve: async () => ({ auth: { apiKey: process.env.ESF_PI_API_KEY ?? 'cube-egress-managed-placeholder' }, source: 'ESF' }) } },
+ models: [{ id: r.model, name: metadata.name, provider: r.provider, api: r.api, baseUrl: r.base_url,
+ reasoning: metadata.reasoning, input: metadata.input, contextWindow: metadata.contextWindow,
+ maxTokens: metadata.maxTokens, thinkingLevelMap: metadata.thinkingLevelMap, compat: metadata.compat,
+ cost: metadata.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }],
+ api: { [r.api]: { stream: tracked('stream'), streamSimple: tracked('streamSimple') } },
+ }));
+ const bash = createBashTool();
+ const guardedBash = { ...bash, replay: 'unsafe', execute: async (args, api, ctx) => {
+ // Wait for the supervisor acknowledgement before the tool can spawn.
+ await channel.notify('shell-start', { call_id: api.callId });
+ try { return await bash.execute(args, api, ctx); }
+ finally { await channel.notify('shell-end', { call_id: api.callId }); }
+ } };
+ const registry = createRegistry();
+ registry.install(defineExtension({ name: 'esf-coding', sections: [section('esf', () => instructions, { tag: false })],
+ tools: [createReadTool(), createWriteTool(), createEditTool(), guardedBash].map(tool => ({ ...tool, replay: 'unsafe' })) }));
+ try {
+ const storage = await openNodeJsonlStorage(path.join(r.state_dir, 'journal'), context, { fsync: true });
+ harness = await Harness.open(storage, { models, registry,
+ env: target => new NodeExecutionEnv({ cwd: target.cwd ?? r.repository_dir }),
+ settings: { toolExecution: 'sequential', retry: { enabled: false },
+ stream: { maxRetries: 0, maxTokens: metadata.maxTokens },
+ compaction: { enabled: true, reserveTokens: metadata.maxTokens,
+ keepRecentTokens: Math.min(20_000, Math.floor(metadata.contextWindow / 4)), backgroundTokens: 0 } },
+ }, context);
+ root = await harness.root(context, { agent: { model: { provider: r.provider, modelId: r.model },
+ thinkingLevel: r.thinking_level, cwd: r.repository_dir } });
+ events = await watchEvents(harness, root.id, context);
+ await channel.audit(events.snapshot);
+ await channel.usage(events.snapshot.usage);
+ events.start(async batch => {
+ for (const event of batch) {
+ await channel.audit(event);
+ if (event.type === 'usage_changed' || event.type === 'snapshot') await channel.usage(event.usage);
+ }
+ });
+ // submit() is idempotent by requestId. It also starts recovered pending
+ // work, so a committed answer is returned without another model request.
+ const submission = await root.submit({ type: 'input', content: r.prompt, requestId: r.request_id }, context);
+ const settled = await submission.wait(context);
+ // wait() returns the committed record. Watch shutdown can discard queued
+ // events, so explicitly acknowledge this final durable boundary.
+ await channel.audit({ type: 'submission', record: settled });
+ const ledger = await harness.usage(context);
+ await events.stop(); events = undefined;
+ await harness.close(BACKGROUND_CONTEXT); harness = undefined;
+ return { status: settled.status === 'done' ? 'completed' : 'failed',
+ error: settled.status === 'done' ? undefined : `Pi submission ${settled.reason ?? settled.status}`, ledger };
+ } finally {
+ await events?.stop().catch(() => {});
+ await harness?.close(BACKGROUND_CONTEXT).catch(() => {});
+ }
+}
diff --git a/agents/pi/src/protocol.mjs b/agents/pi/src/protocol.mjs
new file mode 100644
index 0000000..a7194d7
--- /dev/null
+++ b/agents/pi/src/protocol.mjs
@@ -0,0 +1,118 @@
+import { createHash } from 'node:crypto';
+import { constants } from 'node:fs';
+import * as fs from 'node:fs/promises';
+import path from 'node:path';
+
+export const CONTRACT = 'esf/pi/v1';
+export const SUMMARY_LIMIT = 128 * 1024;
+export const sha256 = value => createHash('sha256').update(value).digest('hex');
+
+export async function readJSON(file, maxBytes = SUMMARY_LIMIT) {
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size > maxBytes) throw new Error('invalid or oversized Pi state receipt');
+ return JSON.parse(await handle.readFile('utf8'));
+ } finally { await handle.close(); }
+}
+
+export function validateRequest(r) {
+ const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
+ if (!r || r.contract_version !== CONTRACT || !r.run_id || typeof r.prompt !== 'string' || !r.prompt.trim() ||
+ !digest(r.fingerprint) || !digest(r.runner_sha256) || !digest(r.runtime_sha256) ||
+ r.request_id !== sha256(`${r.run_id}\0${r.prompt}`) ||
+ !path.isAbsolute(r.repository_dir) || path.normalize(r.repository_dir) !== r.repository_dir ||
+ r.state_dir !== path.join(path.dirname(r.repository_dir), '.factory', 'pi', sha256(r.run_id)) ||
+ !Number.isSafeInteger(r.timeout_ms) || r.timeout_ms <= 0 || r.timeout_ms > 2_147_483_647 ||
+ ![0, 1].includes(r.max_process_restarts) ||
+ !['openai-completions', 'openai-responses'].includes(r.api)) throw new Error('invalid Pi request contract');
+ const endpoint = new URL(r.base_url);
+ if (!['http:', 'https:'].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) throw new Error('invalid Pi endpoint');
+ const m = r.metadata;
+ if (!m || m.id !== r.model || m.api !== r.api || !Number.isSafeInteger(m.contextWindow) ||
+ !Number.isSafeInteger(m.maxTokens) || m.maxTokens <= 0 || m.contextWindow <= m.maxTokens ||
+ m.input?.length !== 1 || m.input[0] !== 'text') throw new Error('invalid pinned model definition');
+ if (r.thinking_level !== 'off' && (!m.reasoning || !m.thinkingLevels?.includes(r.thinking_level))) throw new Error('unsupported model reasoning level');
+ if (m.pricingKnown && !m.cost) throw new Error('known pricing requires rates');
+ if (m.cost && ['input', 'output', 'cacheRead', 'cacheWrite'].some(k => !Number.isFinite(m.cost[k]) || m.cost[k] < 0)) throw new Error('invalid model cost');
+ return r;
+}
+
+// Sidecars are scratch. Atomic replacement and fsync prevent a process crash
+// from presenting a half-written receipt as a completed result.
+export async function writeJSON(file, value, maxBytes = SUMMARY_LIMIT) {
+ const bytes = JSON.stringify(value) + '\n';
+ if (Buffer.byteLength(bytes) > maxBytes) throw new Error('Pi summary exceeds size limit');
+ const temp = `${file}.${process.pid}.tmp`;
+ const handle = await fs.open(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
+ try { await handle.writeFile(bytes); await handle.sync(); } finally { await handle.close(); }
+ try { await fs.rename(temp, file); } finally { await fs.rm(temp, { force: true }); }
+ const directory = await fs.open(path.dirname(file), constants.O_RDONLY);
+ try { await directory.sync(); } finally { await directory.close(); }
+}
+
+export async function prepareState(r) {
+ await fs.mkdir(r.state_dir, { recursive: true, mode: 0o700 });
+ if (!(await fs.lstat(r.state_dir)).isDirectory() || (await fs.lstat(r.state_dir)).isSymbolicLink()) throw new Error('invalid Pi state directory');
+ // Never steal a stale lock. Supervisor death is handled by factory cleanup,
+ // not by guessing whether a previous process or its tools are still active.
+ const lock = await fs.open(path.join(r.state_dir, 'owner.lock'), 'wx', 0o600);
+ try {
+ await lock.writeFile(String(process.pid)); await lock.sync();
+ const identityPath = path.join(r.state_dir, 'identity.json');
+ const expected = { ...r };
+ let previous;
+ try { previous = await readJSON(identityPath, 4 * 1024 * 1024); } catch (error) { if (error.code !== 'ENOENT') throw error; }
+ if (previous) {
+ if (JSON.stringify(previous) !== JSON.stringify(expected)) throw new Error('Pi session fingerprint or configuration mismatch');
+ const stat = await fs.lstat(path.join(r.state_dir, 'journal', 'main.jsonl'));
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size === 0) throw new Error('Pi journal is missing or invalid');
+ } else {
+ // An orphan journal is not a new session. Never adopt state whose
+ // original request/configuration identity has been lost.
+ try { await fs.lstat(path.join(r.state_dir, 'journal')); throw new Error('Pi journal has no session identity'); }
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
+ await writeJSON(identityPath, expected, 4 * 1024 * 1024);
+ }
+ await fs.rm(path.join(r.state_dir, 'terminal.json'), { force: true });
+ return async () => { await lock.close(); await fs.unlink(path.join(r.state_dir, 'owner.lock')); };
+ } catch (error) {
+ await lock.close(); await fs.rm(path.join(r.state_dir, 'owner.lock'), { force: true }); throw error;
+ }
+}
+
+// Read-only, conservative process inspection. PID plus start time protects
+// against PID reuse. A disappearing/unreadable process is uncertain, not absent.
+export async function processInventory() {
+ const found = new Map();
+ for (const pid of (await fs.readdir('/proc')).filter(name => /^\d+$/.test(name))) {
+ const stat = await fs.readFile(`/proc/${pid}/stat`, 'utf8');
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
+ if (fields.length < 20) throw new Error('unreadable process inventory');
+ found.set(Number(pid), fields[19]); // proc stat field 22, after pid and comm
+ }
+ return found;
+}
+
+export function extraProcesses(baseline, current) {
+ return [...current].filter(([pid, start]) => baseline.get(pid) !== start).map(([pid]) => pid);
+}
+
+export function summarizeUsage(r, ledger, uncertain) {
+ const models = ledger?.models ?? {};
+ const tools = ledger?.tools ?? {};
+ const values = Object.values(models);
+ const valid = values.length > 0 && values.every(u =>
+ ['input', 'output', 'cacheRead', 'cacheWrite', 'totalTokens'].every(k => Number.isSafeInteger(u[k]) && u[k] >= 0) && u.totalTokens > 0);
+ const tokensIn = valid ? values.reduce((n, u) => n + u.input + u.cacheRead + u.cacheWrite, 0) : null;
+ const tokensOut = valid ? values.reduce((n, u) => n + u.output, 0) : null;
+ const complete = !uncertain && valid && Number.isSafeInteger(tokensIn) && Number.isSafeInteger(tokensOut);
+ const estimate = complete && r.metadata.pricingKnown && values.every(u => Number.isFinite(u.cost?.total) && u.cost.total >= 0)
+ ? values.reduce((n, u) => n + u.cost.total, 0) : null;
+ const cost = Number.isFinite(estimate) ? estimate : null;
+ return { contract_version: CONTRACT, run_id: r.run_id, fingerprint: r.fingerprint, complete,
+ tokens_in: complete ? tokensIn : null, tokens_out: complete ? tokensOut : null,
+ cost_usd: cost, cost_basis: cost === null ? 'unavailable' : 'estimated',
+ recorded_tokens_in: tokensIn, recorded_tokens_out: tokensOut,
+ uncertainty: uncertain ? 'interrupted or incomplete provider usage; recorded measurements are a known floor' : valid ? null : 'provider usage unavailable', models, tools };
+}
diff --git a/agents/pi/src/runner.mjs b/agents/pi/src/runner.mjs
new file mode 100644
index 0000000..a326db1
--- /dev/null
+++ b/agents/pi/src/runner.mjs
@@ -0,0 +1,49 @@
+import { fileURLToPath } from 'node:url';
+import { engine } from './engine.mjs';
+import { supervise } from './supervisor.mjs';
+import { SUMMARY_LIMIT } from './protocol.mjs';
+
+export async function readRequest() {
+ const chunks = []; let bytes = 0;
+ for await (const chunk of process.stdin) { bytes += chunk.length; if (bytes > 4 * 1024 * 1024) throw new Error('Pi request exceeds size limit'); chunks.push(chunk); }
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
+}
+
+function engineChannel() {
+ let sequence = 0, stopping;
+ const pending = new Map();
+ process.on('message', message => {
+ if (message.type === 'stop') { void stopping?.(); }
+ if (message.type === 'ack') { pending.get(message.id)?.(); pending.delete(message.id); }
+ });
+ process.on('disconnect', () => { void stopping?.(); });
+ const notify = (type, payload = {}) => new Promise((resolve, reject) => {
+ const id = ++sequence;
+ pending.set(id, resolve);
+ process.send({ type, id, ...payload }, error => { if (error) { pending.delete(id); reject(error); } });
+ });
+ return { notify, onStop: callback => { stopping = callback; },
+ audit: event => notify('audit', { event }), usage: ledger => notify('usage', { ledger }),
+ fatal: error => { process.send({ type: 'fatal', error: String(error.message ?? error).slice(0, SUMMARY_LIMIT) }); void stopping?.(); },
+ };
+}
+
+export async function main() {
+ const [major, minor] = process.versions.node.split('.').map(Number);
+ if (major < 22 || (major === 22 && minor < 19)) throw new Error('Pi requires Node >=22.19');
+ if (process.argv[2] === '--version') { console.log(`esf-pi/1 pi-durable/1.0.3 node/${process.versions.node}`); return 0; }
+ const request = await readRequest();
+ if (process.argv[2] === '--engine') {
+ if (!process.send) throw new Error('Pi engine must be owned by its supervisor');
+ const channel = engineChannel();
+ try { await channel.notify('terminal', { result: await engine(request, channel) }); return 0; }
+ catch (error) { await channel.notify('fatal', { error: String(error.message ?? error).slice(0, SUMMARY_LIMIT) }); return 1; }
+ finally { process.disconnect(); }
+ }
+ if (process.argv.length !== 2) throw new Error('Pi invocation is fixed');
+ return supervise(request, fileURLToPath(import.meta.url));
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
+ main().then(code => { process.exitCode = code; }).catch(error => { console.error(`pi: ${error.message}`); process.exitCode = 1; });
+}
diff --git a/agents/pi/src/supervisor.mjs b/agents/pi/src/supervisor.mjs
new file mode 100644
index 0000000..ad43218
--- /dev/null
+++ b/agents/pi/src/supervisor.mjs
@@ -0,0 +1,112 @@
+import { spawn } from 'node:child_process';
+import { createReadStream } from 'node:fs';
+import { createHash } from 'node:crypto';
+import * as fs from 'node:fs/promises';
+import path from 'node:path';
+import { performance } from 'node:perf_hooks';
+import { CONTRACT, extraProcesses, prepareState, processInventory, readJSON, summarizeUsage, validateRequest, writeJSON } from './protocol.mjs';
+
+export async function supervise(request, executable, options = {}) {
+ const r = validateRequest(request);
+ const release = await prepareState(r);
+ const started = performance.now();
+ const inspect = options.inventory ?? processInventory;
+ let ledger = { models: {}, tools: {} }, uncertain = false, restarts = 0, stopped;
+ const attempts = [];
+ let activeChild;
+ const stop = reason => {
+ stopped ??= reason;
+ activeChild?.send({ type: 'stop' }, () => {});
+ const child = activeChild;
+ const kill = setTimeout(() => { if (child?.exitCode === null && child?.signalCode === null) child.kill('SIGKILL'); }, 1_000);
+ kill.unref();
+ };
+ const cancel = () => stop('cancelled');
+ process.on('SIGTERM', cancel); process.on('SIGINT', cancel);
+ const timer = setTimeout(() => stop('timeout'), r.timeout_ms);
+ const log = options.log ?? (event => process.stdout.write(JSON.stringify(event) + '\n'));
+ const base = { contract_version: CONTRACT, run_id: r.run_id, request_id: r.request_id, fingerprint: r.fingerprint, model: r.model };
+ let result;
+ try {
+ try {
+ const previous = await readJSON(path.join(r.state_dir, 'usage.json'));
+ if (previous.contract_version !== CONTRACT || previous.run_id !== r.run_id || previous.fingerprint !== r.fingerprint) throw new Error('Pi usage identity mismatch');
+ uncertain = previous.complete !== true;
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ // A reused journal without its completeness receipt cannot establish
+ // whether earlier provider attempts had missing metering.
+ try { await fs.lstat(path.join(r.state_dir, 'journal')); uncertain = true; }
+ catch (missing) { if (missing.code !== 'ENOENT') throw missing; }
+ }
+ const baseline = await inspect();
+ for (;;) {
+ const remaining = r.timeout_ms - (performance.now() - started);
+ if (stopped || remaining <= 0) { stopped ??= 'timeout'; result = { status: stopped, error: stopped }; break; }
+ if (restarts > 0) {
+ const stat = await fs.lstat(path.join(r.state_dir, 'journal', 'main.jsonl'));
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size === 0) throw new Error('cannot recover missing Pi journal');
+ }
+ for (const [file, expected] of [[process.execPath, r.runtime_sha256], [executable, r.runner_sha256]]) {
+ const hash = createHash('sha256');
+ for await (const bytes of createReadStream(file)) hash.update(bytes);
+ if (hash.digest('hex') !== expected) throw new Error('Pi execution-chain digest mismatch');
+ }
+ // The deadline can expire during async file hashing, before a child
+ // exists to receive stop(). Never launch work after that notification.
+ if (stopped || performance.now() - started >= r.timeout_ms) {
+ stopped ??= 'timeout'; result = { status: stopped, error: stopped }; break;
+ }
+ let terminal, fatal, protocolError;
+ const activeShell = new Set();
+ const child = spawn(process.execPath, [...process.execArgv, executable, '--engine'], {
+ cwd: r.repository_dir, stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
+ env: { ...process.env },
+ });
+ activeChild = child;
+ log({ ...base, type: 'engine_started', pid: child.pid, attempt: restarts + 1 });
+ child.stdout.pipe(process.stdout, { end: false });
+ child.stderr.pipe(process.stderr, { end: false });
+ child.on('message', message => {
+ try {
+ if (!message || typeof message !== 'object') throw new Error('invalid engine message');
+ if (message.type === 'shell-start') { if (!message.call_id || activeShell.has(message.call_id)) throw new Error('invalid shell ownership'); activeShell.add(message.call_id); log({ ...base, type: 'shell_guard', phase: 'active', call_id: message.call_id }); }
+ else if (message.type === 'shell-end') { if (!activeShell.delete(message.call_id)) throw new Error('unknown shell ownership'); log({ ...base, type: 'shell_guard', phase: 'released', call_id: message.call_id }); }
+ else if (message.type === 'usage-incomplete') uncertain = true;
+ else if (message.type === 'usage') ledger = message.ledger;
+ else if (message.type === 'audit') log({ ...base, type: 'agent_event', attempt: restarts + 1, event: message.event });
+ else if (message.type === 'terminal') { if (terminal || !['completed', 'failed'].includes(message.result?.status)) throw new Error('invalid terminal result'); terminal = message.result; ledger = terminal.ledger; }
+ else if (message.type === 'fatal') fatal = String(message.error ?? 'Pi engine failed');
+ else throw new Error('unknown engine message');
+ if (message.id !== undefined) child.send({ type: 'ack', id: message.id }, () => {});
+ } catch (error) { protocolError = error.message; child.kill('SIGKILL'); }
+ });
+ const exited = new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', (code, signal) => resolve({ code, signal })); });
+ child.stdin.end(JSON.stringify(r));
+ const exit = await exited;
+ activeChild = undefined;
+ attempts.push({ attempt: restarts + 1, ...exit, active_shell: activeShell.size > 0 });
+ if (stopped) { uncertain = true; result = { status: stopped, error: stopped }; break; }
+ if (protocolError || fatal) { uncertain = true; result = { status: 'failed', error: protocolError ?? fatal }; break; }
+ if (terminal) { result = terminal; uncertain ||= terminal.status !== 'completed'; break; }
+ uncertain = true; // a provider may have billed a lost response
+ if (activeShell.size) { result = { status: 'failed', error: 'engine crashed during shell execution; recovery refused' }; break; }
+ const additional = extraProcesses(baseline, await inspect());
+ if (additional.length) { result = { status: 'failed', error: 'live additional processes remain; recovery refused' }; break; }
+ if (restarts >= r.max_process_restarts) { result = { status: 'failed', error: 'Pi process restart allowance exhausted' }; break; }
+ restarts++;
+ log({ ...base, type: 'process_recovery', restarts });
+ }
+ } catch (error) {
+ uncertain = true; result = { status: stopped ?? 'failed', error: error.message };
+ } finally {
+ clearTimeout(timer); process.off('SIGTERM', cancel); process.off('SIGINT', cancel);
+ }
+ try {
+ await writeJSON(path.join(r.state_dir, 'usage.json'), summarizeUsage(r, ledger, uncertain));
+ await writeJSON(path.join(r.state_dir, 'recovery.json'), { ...base, restarts, attempts, error: result.error });
+ await writeJSON(path.join(r.state_dir, 'terminal.json'), { ...base, status: result.status, error: result.error, restarts });
+ log({ ...base, type: 'terminal', status: result.status, restarts });
+ return result.status === 'completed' ? 0 : 1;
+ } finally { await release(); }
+}
diff --git a/agents/pi/test/factory-provider.mjs b/agents/pi/test/factory-provider.mjs
new file mode 100644
index 0000000..c871f15
--- /dev/null
+++ b/agents/pi/test/factory-provider.mjs
@@ -0,0 +1,24 @@
+// Test-only OpenAI-compatible provider. Start exclusively inside a Cube VM.
+import { createServer } from 'node:http';
+createServer(async (req, res) => {
+ if (req.method === 'GET' && req.url === '/v1/models') {
+ res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ object: 'list', data: [{ id: 'test-model', context_window: 32768, max_tokens: 1024 }] })); return;
+ }
+ if (req.method !== 'POST' || req.url !== '/v1/chat/completions') { res.writeHead(404); res.end(); return; }
+ const chunks = []; for await (const chunk of req) chunks.push(chunk);
+ const body = JSON.parse(Buffer.concat(chunks));
+ const prompt = JSON.stringify(body.messages.filter(m => m.role === 'user'));
+ const finished = body.messages.some(m => m.role === 'tool');
+ const write = body.tools.find(t => t.function.name === 'write');
+ const args = prompt.includes('PI_ACCEPTANCE_BLOCKED')
+ ? { path: '../.factory/blocked.json', content: JSON.stringify({ reason: 'deterministic acceptance blocked task' }) }
+ : { path: 'hello.txt', content: prompt.includes('PI_ACCEPTANCE_FAIL') ? 'wrong\n' : 'hello pi\n' };
+ const delta = finished ? { content: 'Completed the deterministic acceptance task.' }
+ : { tool_calls: [{ index: 0, id: 'write_1', type: 'function', function: { name: write.function.name, arguments: JSON.stringify(args) } }] };
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+ const chunk = (delta, finish_reason = null) => ({ id: 'fixture-chat', object: 'chat.completion.chunk', created: 1, model: 'test-model', choices: [{ index: 0, delta, finish_reason }] });
+ res.write(`data: ${JSON.stringify(chunk({ role: 'assistant', ...delta }))}\n\n`);
+ res.write(`data: ${JSON.stringify(chunk({}, finished ? 'stop' : 'tool_calls'))}\n\n`);
+ res.write(`data: ${JSON.stringify({ ...chunk({}), choices: [], usage: { prompt_tokens: 100, completion_tokens: 10 } })}\n\n`);
+ res.end('data: [DONE]\n\n');
+}).listen(18567, '127.0.0.1');
diff --git a/agents/pi/test/runner.test.mjs b/agents/pi/test/runner.test.mjs
new file mode 100644
index 0000000..59a9e86
--- /dev/null
+++ b/agents/pi/test/runner.test.mjs
@@ -0,0 +1,270 @@
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import * as fs from 'node:fs/promises';
+import { createServer } from 'node:http';
+import path from 'node:path';
+import os from 'node:os';
+import { once } from 'node:events';
+import { test } from 'node:test';
+import { CONTRACT, sha256 } from '../src/protocol.mjs';
+import { supervise } from '../src/supervisor.mjs';
+
+const runner = path.resolve('dist/pi-runner.mjs');
+const runnerDigest = sha256(await fs.readFile(runner));
+const runtimeDigest = sha256(await fs.readFile(process.execPath));
+const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
+async function until(predicate, timeout = 10_000) {
+ const end = Date.now() + timeout;
+ while (Date.now() < end) { if (predicate()) return; await delay(10); }
+ throw new Error('test condition timed out');
+}
+async function fixture(handler) {
+ const base = await fs.mkdtemp(path.join(os.tmpdir(), 'esf-pi-test-'));
+ const repo = path.join(base, 'repo'); await fs.mkdir(repo);
+ let calls = 0;
+ const server = createServer(async (req, res) => {
+ const chunks = []; for await (const chunk of req) chunks.push(chunk);
+ const body = JSON.parse(Buffer.concat(chunks));
+ calls++;
+ try { await handler({ req, res, body, calls, repo }); } catch (error) { res.destroy(error); }
+ });
+ server.listen(0, '127.0.0.1'); await once(server, 'listening');
+ const runID = path.basename(base);
+ const request = { contract_version: CONTRACT, run_id: runID, request_id: sha256(`${runID}\0Fix the code`),
+ prompt: 'Fix the code', repository_dir: repo, state_dir: path.join(base, '.factory', 'pi', sha256(runID)),
+ provider: 'local', base_url: `http://127.0.0.1:${server.address().port}/v1`, model: 'test-model',
+ api: 'openai-completions', thinking_level: 'off', timeout_ms: 10_000, max_process_restarts: 1,
+ runner_sha256: runnerDigest, runtime_sha256: runtimeDigest,
+ metadata: { id: 'test-model', name: 'Test model', api: 'openai-completions', reasoning: false,
+ input: ['text'], contextWindow: 32_768, maxTokens: 1_024, pricingKnown: true,
+ cost: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 1 }, thinkingLevels: ['off'] },
+ fingerprint: 'c'.repeat(64) };
+ return { request, repo, calls: () => calls, async close() { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await fs.rm(base, { recursive: true, force: true }); } };
+}
+function answer(res, content = 'Done', options = {}) {
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+ const chunk = (delta, finish_reason = null) => ({ id: 'chat-1', object: 'chat.completion.chunk', created: 1, model: 'test-model', choices: [{ index: 0, delta, finish_reason }] });
+ res.write(`data: ${JSON.stringify(chunk({ role: 'assistant', ...(options.tool ? { tool_calls: [{ index: 0, id: 'tool-1', type: 'function', function: { name: options.tool.name, arguments: JSON.stringify(options.tool.args) } }] } : { content }) }))}\n\n`);
+ res.write(`data: ${JSON.stringify(chunk({}, options.tool ? 'tool_calls' : 'stop'))}\n\n`);
+ if (!options.missingUsage) res.write(`data: ${JSON.stringify({ ...chunk({}), choices: [], usage: { prompt_tokens: 12, completion_tokens: 5, prompt_tokens_details: { cached_tokens: 2 } } })}\n\n`);
+ res.end('data: [DONE]\n\n');
+}
+function launch(request) {
+ const events = []; let stderr = '', pending = '';
+ const child = spawn(process.execPath, [runner], { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, ESF_PI_API_KEY: 'test-placeholder' } });
+ child.stdout.on('data', chunk => { pending += chunk; let newline; while ((newline = pending.indexOf('\n')) >= 0) { const line = pending.slice(0, newline); pending = pending.slice(newline + 1); try { events.push(JSON.parse(line)); } catch {} } });
+ child.stderr.on('data', chunk => { stderr += chunk; });
+ child.stdin.end(JSON.stringify(request));
+ const finished = once(child, 'exit').then(([code, signal]) => ({ code, signal, events, stderr }));
+ return { child, events, finished };
+}
+async function summary(f, name) { return JSON.parse(await fs.readFile(path.join(f.request.state_dir, name), 'utf8')); }
+
+test('explicit Responses protocol preserves committed usage', async () => {
+ const f = await fixture(({ req, res }) => {
+ assert.equal(req.url, '/v1/responses');
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+ const emit = event => res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
+ const part = { type: 'output_text', text: 'Done', annotations: [] };
+ const item = { id: 'msg_1', type: 'message', role: 'assistant', status: 'completed', content: [part] };
+ const response = { id: 'resp_1', object: 'response', created_at: 1, model: 'test-model', status: 'completed', output: [item], usage: { input_tokens: 12, output_tokens: 5, total_tokens: 17, input_tokens_details: { cached_tokens: 2 }, output_tokens_details: { reasoning_tokens: 1 } } };
+ emit({ type: 'response.created', response: { ...response, output: [], status: 'in_progress' } });
+ emit({ type: 'response.output_item.added', output_index: 0, item: { ...item, content: [], status: 'in_progress' } });
+ emit({ type: 'response.content_part.added', output_index: 0, content_index: 0, item_id: item.id, part: { ...part, text: '' } });
+ emit({ type: 'response.output_text.delta', output_index: 0, content_index: 0, item_id: item.id, delta: 'Done' });
+ emit({ type: 'response.output_text.done', output_index: 0, content_index: 0, item_id: item.id, text: 'Done' });
+ emit({ type: 'response.output_item.done', output_index: 0, item });
+ emit({ type: 'response.completed', response }); res.end();
+ });
+ f.request.api = f.request.metadata.api = 'openai-responses';
+ try {
+ const result = await launch(f.request).finished; assert.equal(result.code, 0, result.stderr);
+ const usage = await summary(f, 'usage.json'); assert.equal(usage.tokens_in, 12); assert.equal(usage.tokens_out, 5);
+ } finally { await f.close(); }
+});
+
+test('completion, commit audit, cached tokens, estimated cost, and submission deduplication', async () => {
+ const f = await fixture(({ res }) => answer(res));
+ try {
+ const first = await launch(f.request).finished;
+ assert.equal(first.code, 0, first.stderr);
+ assert.ok(first.events.some(e => e.type === 'agent_event' && e.event.type === 'message_end'));
+ const usage = await summary(f, 'usage.json');
+ assert.equal(usage.complete, true); assert.equal(usage.tokens_in, 12); assert.equal(usage.tokens_out, 5);
+ assert.equal(usage.cost_basis, 'estimated'); assert.ok(usage.cost_usd > 0);
+ const again = await launch(f.request).finished;
+ assert.equal(again.code, 0, again.stderr); assert.equal(f.calls(), 1);
+ } finally { await f.close(); }
+});
+
+test('confirmed engine death during a model request resumes the same submission with partial usage', async () => {
+ const f = await fixture(({ res, calls }) => { if (calls > 1) answer(res); });
+ try {
+ const run = launch(f.request);
+ await until(() => f.calls() === 1 && run.events.some(e => e.type === 'engine_started'));
+ process.kill(run.events.find(e => e.type === 'engine_started').pid, 'SIGKILL');
+ const result = await run.finished;
+ assert.equal(result.code, 0, result.stderr); assert.equal(f.calls(), 2);
+ assert.equal((await summary(f, 'terminal.json')).restarts, 1);
+ const usage = await summary(f, 'usage.json'); assert.equal(usage.complete, false); assert.equal(usage.cost_usd, null);
+ assert.equal(usage.tokens_in, null); assert.ok(usage.recorded_tokens_in > 0);
+ } finally { await f.close(); }
+});
+
+test('engine death during shell execution fails without replaying the command', async () => {
+ const f = await fixture(({ res }) => answer(res, '', { tool: { name: 'bash', args: { command: 'sleep 20' } } }));
+ try {
+ const run = launch(f.request);
+ await until(() => run.events.some(e => e.type === 'shell_guard' && e.phase === 'active'));
+ process.kill(run.events.find(e => e.type === 'engine_started').pid, 'SIGKILL');
+ const result = await run.finished;
+ assert.equal(result.code, 1); assert.equal(f.calls(), 1);
+ assert.match((await summary(f, 'terminal.json')).error, /shell execution/);
+ assert.equal((await summary(f, 'terminal.json')).restarts, 0);
+ } finally { await f.close(); }
+});
+
+test('normal provider failure is terminal and does not restart the engine', async () => {
+ const f = await fixture(({ res }) => { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message: 'test provider rejected request' } })); });
+ try {
+ const result = await launch(f.request).finished;
+ assert.equal(result.code, 1); assert.equal(f.calls(), 1); assert.equal((await summary(f, 'terminal.json')).restarts, 0);
+ } finally { await f.close(); }
+});
+
+test('missing provider usage stays unavailable rather than zero', async () => {
+ const f = await fixture(({ res }) => answer(res, 'Done', { missingUsage: true }));
+ try { const result = await launch(f.request).finished; assert.equal(result.code, 0, result.stderr); const usage = await summary(f, 'usage.json'); assert.equal(usage.complete, false); assert.equal(usage.cost_usd, null); assert.equal(usage.tokens_in, null); }
+ finally { await f.close(); }
+});
+
+test('missing usage in an earlier turn remains unavailable on a duplicate submission', async () => {
+ const f = await fixture(({ res, calls }) => calls === 1
+ ? answer(res, '', { missingUsage: true, tool: { name: 'write', args: { path: 'hello.txt', content: 'hello' } } })
+ : answer(res));
+ try {
+ assert.equal((await launch(f.request).finished).code, 0);
+ assert.equal((await summary(f, 'usage.json')).complete, false);
+ assert.equal((await launch(f.request).finished).code, 0); assert.equal(f.calls(), 2);
+ assert.equal((await summary(f, 'usage.json')).complete, false);
+ } finally { await f.close(); }
+});
+
+test('owner lock rejects concurrent invocations without stealing a live session', async () => {
+ const f = await fixture(() => {});
+ try {
+ const first = launch(f.request); await until(() => f.calls() === 1);
+ const second = await launch(f.request).finished; assert.equal(second.code, 1); assert.match(second.stderr, /EEXIST/); assert.equal(f.calls(), 1);
+ first.child.kill('SIGTERM'); const result = await first.finished; assert.equal(result.code, 1); assert.equal((await summary(f, 'terminal.json')).status, 'cancelled');
+ } finally { await f.close(); }
+});
+
+test('deadline remains bounded and never restarts on timeout', async () => {
+ const f = await fixture(() => {}); f.request.timeout_ms = 500;
+ try {
+ const start = Date.now(); const result = await launch(f.request).finished;
+ assert.equal(result.code, 1); assert.ok(Date.now() - start < 3000);
+ const terminal = await summary(f, 'terminal.json'); assert.equal(terminal.status, 'timeout'); assert.equal(terminal.restarts, 0);
+ } finally { await f.close(); }
+});
+
+test('a deadline expiring during digest verification never launches an engine', async () => {
+ const f = await fixture(() => {}); f.request.timeout_ms = 1;
+ try {
+ const result = await launch(f.request).finished; assert.equal(result.code, 1);
+ assert.equal(f.calls(), 0); assert.equal(result.events.filter(e => e.type === 'engine_started').length, 0);
+ assert.equal((await summary(f, 'terminal.json')).status, 'timeout');
+ } finally { await f.close(); }
+});
+
+test('session mismatch and missing journal fail without a fresh conversation', async () => {
+ const f = await fixture(({ res }) => answer(res));
+ try {
+ assert.equal((await launch(f.request).finished).code, 0);
+ const changed = { ...f.request, prompt: 'Different task' }; changed.request_id = sha256(`${changed.run_id}\0${changed.prompt}`);
+ const mismatch = await launch(changed).finished; assert.equal(mismatch.code, 1); assert.match(mismatch.stderr, /fingerprint/);
+ await fs.rm(path.join(f.request.state_dir, 'journal'), { recursive: true });
+ assert.equal((await launch(f.request).finished).code, 1); assert.equal(f.calls(), 1);
+ } finally { await f.close(); }
+});
+
+test('committed completion survives death before the supervisor terminal notification', async () => {
+ const f = await fixture(({ res }) => answer(res));
+ try {
+ let pid, killed = false;
+ const result = await supervise(f.request, runner, { log: event => {
+ if (event.type === 'engine_started') pid = event.pid;
+ if (!killed && event.type === 'agent_event' && event.event.type === 'submission' && event.event.record.status === 'done') {
+ killed = true; process.kill(pid, 'SIGKILL');
+ }
+ } });
+ assert.equal(result, 0); assert.equal(killed, true); assert.equal(f.calls(), 1);
+ assert.equal((await summary(f, 'terminal.json')).restarts, 1);
+ } finally { await f.close(); }
+});
+
+test('unsafe interrupted file tool is recorded instead of replayed', async () => {
+ const f = await fixture(({ res, calls, body }) => {
+ if (calls === 1) answer(res, '', { tool: { name: 'read', args: { path: 'waiting' } } });
+ else { assert.match(JSON.stringify(body.messages), /interrupted/i); answer(res); }
+ });
+ try {
+ const fifo = spawn('mkfifo', [path.join(f.repo, 'waiting')]); await once(fifo, 'exit');
+ const run = launch(f.request);
+ await until(() => run.events.some(e => e.type === 'agent_event' && e.event.type === 'tool_execution_start'));
+ process.kill(run.events.find(e => e.type === 'engine_started').pid, 'SIGKILL');
+ const result = await run.finished;
+ assert.equal(result.code, 0, result.stderr); assert.equal(f.calls(), 2);
+ assert.equal((await summary(f, 'terminal.json')).restarts, 1);
+ } finally { await f.close(); }
+});
+
+test('surviving processes and uncertain process inspection prevent recovery', async () => {
+ const f = await fixture(() => {}); let leftover;
+ try {
+ const run = launch(f.request); await until(() => f.calls() === 1);
+ leftover = spawn('sleep', ['20']); await once(leftover, 'spawn');
+ process.kill(run.events.find(e => e.type === 'engine_started').pid, 'SIGKILL');
+ assert.equal((await run.finished).code, 1);
+ assert.match((await summary(f, 'terminal.json')).error, /additional processes/);
+ assert.equal(f.calls(), 1);
+ } finally { leftover?.kill('SIGKILL'); if (leftover) await once(leftover, 'exit'); await f.close(); }
+ const uncertain = await fixture(() => {}); let inspected = 0;
+ try {
+ const result = supervise(uncertain.request, runner, { inventory: async () => {
+ if (++inspected > 1) throw new Error('process inspection uncertain'); return new Map();
+ }, log: event => { if (event.type === 'engine_started') until(() => uncertain.calls() === 1).then(() => process.kill(event.pid, 'SIGKILL')); } });
+ assert.equal(await result, 1);
+ assert.match((await summary(uncertain, 'terminal.json')).error, /inspection uncertain/);
+ assert.equal(uncertain.calls(), 1);
+ } finally { await uncertain.close(); }
+});
+
+test('corrupt journal and exhausted allowance never start a third engine', async () => {
+ const corrupt = await fixture(() => {});
+ try {
+ const run = launch(corrupt.request); await until(() => corrupt.calls() === 1);
+ await fs.writeFile(path.join(corrupt.request.state_dir, 'journal', 'main.jsonl'), 'not-json\nnot-json\n');
+ process.kill(run.events.find(e => e.type === 'engine_started').pid, 'SIGKILL');
+ assert.equal((await run.finished).code, 1); assert.equal(corrupt.calls(), 1);
+ } finally { await corrupt.close(); }
+ const f = await fixture(() => {});
+ try {
+ const run = launch(f.request); await until(() => f.calls() === 1);
+ process.kill(run.events.find(e => e.type === 'engine_started').pid, 'SIGKILL');
+ await until(() => f.calls() === 2 && run.events.filter(e => e.type === 'engine_started').length === 2);
+ process.kill(run.events.filter(e => e.type === 'engine_started')[1].pid, 'SIGKILL');
+ assert.equal((await run.finished).code, 1); assert.equal(f.calls(), 2);
+ assert.match((await summary(f, 'terminal.json')).error, /allowance exhausted/);
+ } finally { await f.close(); }
+});
+
+test('a restart consumes the original deadline', async () => {
+ const f = await fixture(() => {}); f.request.timeout_ms = 900;
+ try {
+ const start = Date.now(); const run = launch(f.request); await until(() => f.calls() === 1);
+ await delay(300); process.kill(run.events.find(e => e.type === 'engine_started').pid, 'SIGKILL');
+ assert.equal((await run.finished).code, 1); assert.ok(Date.now() - start < 1600);
+ const terminal = await summary(f, 'terminal.json'); assert.equal(terminal.status, 'timeout'); assert.equal(terminal.restarts, 1);
+ } finally { await f.close(); }
+});
diff --git a/cmd/factory/release.go b/cmd/factory/release.go
index e33011e..5b06487 100644
--- a/cmd/factory/release.go
+++ b/cmd/factory/release.go
@@ -230,6 +230,22 @@ func newAgentsCommand(configPath *string) *cobra.Command {
continue
}
fmt.Printf("[ok] %s: template sha256 %s\n", name, h.BinarySHA256)
+ if strings.EqualFold(h.Type, "pi") {
+ registry, err := cfg.BuildHarnesses()
+ if err != nil {
+ return err
+ }
+ harness, err := registry.Resolve(name)
+ if err != nil {
+ return err
+ }
+ if err := harness.Provision(cmd.Context(), templateSandbox); err != nil {
+ fmt.Printf("[FAIL] %s: execution chain: %v\n", name, err)
+ failures++
+ } else {
+ fmt.Printf("[ok] %s: runtime digest and runner self-check\n", name)
+ }
+ }
continue
}
file, err := os.Open(h.Binary)
@@ -307,7 +323,7 @@ func runStructuredDoctor(ctx context.Context, configPath, profile, output string
sort.Strings(names)
for _, name := range names {
h := cfg.Harnesses[name]
- if h.Type == "opencode" || h.Type == "unreal" {
+ if h.Type == "opencode" || h.Type == "unreal" || h.Type == "pi" {
var e error
if !h.Preinstalled || len(h.Packages) != 0 {
e = fmt.Errorf("use a digest-pinned agent in the versioned Cube template without per-run package installs")
diff --git a/deploy/cube/Dockerfile.pi-v1 b/deploy/cube/Dockerfile.pi-v1
new file mode 100644
index 0000000..75bb011
--- /dev/null
+++ b/deploy/cube/Dockerfile.pi-v1
@@ -0,0 +1,15 @@
+# Extend an operator-selected, digest-pinned ESF template; historical templates
+# and release inventories retain their original contents.
+ARG ESF_TEMPLATE_BASE
+ARG NODE_BASE=docker.io/library/node@sha256:0e0ff40c39bc087845bfb27465a0df4ea419520094bc35842ff83dd8cbe6f9b6
+FROM ${NODE_BASE} AS node-runtime
+FROM ${ESF_TEMPLATE_BASE} AS pi-template-v1
+COPY --from=node-runtime /usr/local/bin/node /opt/esf/agents/node
+COPY agents/pi/dist/pi-runner.mjs /opt/esf/agents/pi-runner.mjs
+COPY agents/pi/inventory.json /opt/esf/pi-inventory.json
+COPY agents/pi/dist/THIRD_PARTY_NOTICES.txt /opt/esf/pi-third-party-notices.txt
+RUN chmod 0755 /opt/esf/agents/node && \
+ echo '7fde7b8afa198da66257f42ee2001d874c7355631e6d1579a5fb5ef1f246df4c /opt/esf/agents/node' | sha256sum -c - && \
+ echo '9dab48151c793cf3265af4058ea7aac8671d1778b31873ee25ac3fc24afe0e2c /opt/esf/agents/pi-runner.mjs' | sha256sum -c -
+LABEL org.opencontainers.image.title="ESF Pi template v1 candidate" \
+ io.esf.pi.contract="esf/pi/v1" io.esf.pi.durable.version="1.0.3"
diff --git a/deploy/cube/README.md b/deploy/cube/README.md
index 2a0ddd0..b1f4747 100644
--- a/deploy/cube/README.md
+++ b/deploy/cube/README.md
@@ -1,5 +1,8 @@
# Versioned CubeSandbox template
+The opt-in Pi v1 candidate uses `Dockerfile.pi-v1` and a separate candidate
+inventory. See [Pi installation and qualification](../../docs/harness-pi.md).
+
`Dockerfile` builds the Linux/amd64 ESF v0.6.0 template from a pinned
CubeSandbox base. It includes Git, CA certificates, Python, the command-output
limiter tools, OpenCode 2.0.18, and Unreal 0.2.0. The Docker build verifies
diff --git a/docs/harness-pi.md b/docs/harness-pi.md
new file mode 100644
index 0000000..9ccfd72
--- /dev/null
+++ b/docs/harness-pi.md
@@ -0,0 +1,170 @@
+# Pi harness v1 candidate
+
+Select Pi explicitly with `factory run --agent pi`. OpenCode remains the
+automatic default. Pi 1.0.3 has an experimental API; this adapter pins its
+published packages, dependency graph, ESF bundle, and Node 24.21.0 runtime.
+The candidate is opt-in until the model-backed acceptance matrix passes.
+
+## Template and installation
+
+`agents/pi/inventory.json` describes the candidate separately from historical
+release records. `deploy/cube/Dockerfile.pi-v1` extends a qualified ESF template
+selected by immutable image digest:
+
+```sh
+docker build -f deploy/cube/Dockerfile.pi-v1 \
+ --build-arg ESF_TEMPLATE_BASE= \
+ -t .
+```
+
+Publish the candidate image to the operator's registry, then create a new Cube
+template from its immutable digest using the existing template runbook.
+Record the READY template ID in a development overlay. Keep the existing
+`factory.toml` and default template intact. No npm installation occurs in a
+factory run. For offline template staging,
+`scripts/install-pi-agent.sh `
+installs the verified Node binary and committed bundle.
+
+Rebuild the bundle and catalog in a Cube development microVM, using Node
+24.21.0 and the committed lockfile:
+
+```sh
+cd agents/pi
+npm ci --ignore-scripts
+npm run build
+node export-catalog.mjs
+npm test
+npm audit --audit-level=high
+```
+
+Refresh the candidate inventory and template hashes when the bundle changes.
+`scripts/verify-pi-inventory.py` checks the lock, upstream versions, bundle,
+and template pins. `scripts/generate-sbom.py` includes the complete locked Pi
+npm graph, the bundle digest, and Node runtime. Keep existing release SBOMs
+and inventories unchanged.
+The reproducible build collects license notices for the bundled modules and
+Node into `dist/THIRD_PARTY_NOTICES.txt`; the template and offline installer
+retain that file beside the execution chain.
+
+## Configuration
+
+Copy the operator configuration to a private overlay, select the new READY
+template in `[cube]`, and append:
+
+```toml
+[harnesses.pi]
+type = "pi"
+preinstalled = true
+binary = "/opt/esf/agents/pi-runner.mjs"
+binary_sha256 = "9dab48151c793cf3265af4058ea7aac8671d1778b31873ee25ac3fc24afe0e2c"
+runtime_binary = "/opt/esf/agents/node"
+runtime_sha256 = "7fde7b8afa198da66257f42ee2001d874c7355631e6d1579a5fb5ef1f246df4c"
+provider = "local"
+base_url = "http://192.168.0.14:8000/v1"
+model = ""
+api = "openai-completions"
+catalog_cache = "/absolute/path/to/validated-model.json"
+thinking_level = "off"
+max_process_restarts = 1
+timeout = "30m"
+```
+
+`api` supports `openai-completions` (default for the local gateway) and
+`openai-responses`. A model in the embedded Pi 1.0.3 catalog can omit
+`catalog_cache`; its provider, model ID, and API must match. Custom gateways
+must supply a strict offline JSON model definition with explicit context and
+output limits. Do not guess these limits from a model name.
+`agents/pi/models/deterministic.json` defines only the test provider.
+
+An offline model definition declares `id`, `name`, `api`, `reasoning`,
+`input: ["text"]`, `contextWindow`, `maxTokens`, `thinkingLevels`, and
+`pricingKnown`. Optional `cost` rates (`input`, `output`, `cacheRead`,
+`cacheWrite`) are USD per million tokens. Optional `compat` is Pi's
+OpenAI API compatibility object. `thinkingLevelMap` maps approved Pi levels
+to provider-specific values; `xhigh` and `max` require explicit mappings.
+Unknown fields, missing limits, API/model mismatches, and unsupported reasoning
+fail startup. Named model resources must agree with the harness's provider,
+model, endpoint, and credential source before a sandbox is allocated.
+
+For hosted providers use an HTTPS hostname and `credential_mode = "cube_egress"`,
+with exactly one `api_key_file` (absolute, regular, owner-only) or `api_key_env`.
+The key is sent only to Cube's scoped injection policy. Pi receives
+`ESF_PI_API_KEY=cube-egress-managed-placeholder`, and Node uses the template's
+system CA trust in both supervisor and engine. The same deny-by-default policy
+and endpoint checks apply as for Unreal and OpenCode. Legacy
+`credential_mode = "environment"` exposes only the configured key under the
+canonical name inside the VM and is for development. Pi accepts no `pass_env`,
+custom executable/argv, provider files, packages, or extensions.
+
+Run `factory --config config validate`, `factory --config
+agents verify`, then start a worker with that overlay and an isolated task
+queue. Submit through the same overlay using `--agent pi` and the existing
+verification/review flags. Check `factory sandboxes` after every acceptance run.
+
+## Recovery boundary
+
+The fixed invocation reads one versioned JSON request via `stdin_file`. It
+contains the run/task, repository, approved model settings, deadline, and
+execution-chain hashes. A stable request ID and configuration fingerprint bind
+the submission to `/workspace/.factory/pi/`. Pi retains its
+own conversation and session IDs in its fsync-enabled JSONL journal.
+
+One supervisor owns an exclusive session lock and the original deadline across
+engine restarts. It permits at most one restart after unexpected engine death
+without a terminal notification. Normal model/storage errors, cancellation,
+and timeout fail without restart. A shell tool must receive an acknowledged
+supervisor notification before spawning. Engine death with an active shell
+tool fails the run. Additional surviving processes or uncertain process
+inspection also prevent recovery. No process-containment infrastructure is
+added; factory teardown destroys the entire VM.
+
+Recovery reopens the same journal and reacquires the same submission. All
+coding tools retain unsafe replay policy and run sequentially. An interrupted
+file tool is recorded as interrupted; another model turn can inspect and act
+on the current tree. This does not guarantee exactly-once effects. Missing,
+corrupt, mismatched state, lost acknowledgements, or supervisor death remain
+failed runs. Temporal retains its existing single-attempt agent policy.
+Journal and sidecars remain untrusted agent-writable scratch, never factory
+verification or approval authority.
+
+## Evidence and acceptance
+
+The standard stdout artifact contains commit-derived JSONL audit events,
+including a final committed submission receipt. Standard stderr/result and
+prompt artifacts remain unchanged. Before teardown, the adapter validates and
+the factory redacts/stores `agent/pi-terminal.json`, `agent/usage.json`, and
+`agent/recovery.json`. Each sidecar is bounded to 128 KiB. Exit zero without a
+valid matching terminal receipt fails. Sidecars are transient harness output;
+they do not add workflow payloads or manifest fields. Factory gates, blocked
+signals, behavior monitoring, review suspend/resume, and cleanup remain in the
+existing lifecycle.
+
+Input tokens sum `input + cacheRead + cacheWrite`; output already includes
+reasoning tokens. Committed usage is aggregated once from the same ledger
+across restarts. Missing metering or interrupted requests makes totals
+unavailable and identifies retained measurements as a known floor. Unknown or
+tiered prices make cost unavailable. Known flat rates produce an explicitly
+estimated cost, never invoice evidence.
+
+Deterministic provider tests exercise both APIs, deduplication, owner locking,
+generation/file-tool recovery, final-commit recovery, unsafe shell refusal,
+surviving processes, uncertain inspection, corrupt/missing state, cancellation,
+original deadline, and exhausted allowance. Go suites cover digest rejection,
+fixed prompt transport, model policy, proxy credentials, and artifact redaction.
+Local validation runs these suites inside Cube microVMs.
+
+Promotion requires model-backed factory runs on the local gateway and an HTTPS
+CubeEgress profile: verified completion, verification failure, review
+suspend/resume, audit/usage retention, and zero leaked sandboxes. Compare the
+same task/model against OpenCode and Unreal, recording completion, latency,
+tokens, and recovery overhead. Cost comparisons require known pricing.
+
+The 2026-10-05 local candidate passed 16 runner regressions, the existing
+agentharness/factory/CLI Go suites with the race detector, and deterministic
+factory completion, verification-failure, blocked-task, and review
+suspend/resume scenarios inside Cube. All test VMs were destroyed. The pinned
+npm graph reported zero audit vulnerabilities. Real-model acceptance and
+harness comparisons remain pending: the configured local gateway was
+unreachable, and no HTTPS provider/model/credential profile was available.
+These results qualify the deterministic integration only; the inventory
+continues to mark Pi as a candidate.
diff --git a/internal/agentharness/harness.go b/internal/agentharness/harness.go
index 09ccf76..7229f47 100644
--- a/internal/agentharness/harness.go
+++ b/internal/agentharness/harness.go
@@ -87,6 +87,12 @@ type ModelEndpointConfigurer interface {
ConfigureModelEndpoint(ctx context.Context, sb sandbox.Sandbox, endpoint ModelEndpoint) error
}
+// ModelEndpointValidator checks a resolved endpoint before sandbox allocation.
+// This prevents credential/egress policy and the agent's provider from diverging.
+type ModelEndpointValidator interface {
+ ValidateModelEndpoint(endpoint ModelEndpoint) error
+}
+
// Result is the recorded outcome of an agent run.
//
// The optional cost/token fields exist so Phase 2 can compare harnesses and
@@ -110,6 +116,11 @@ type Result struct {
TokensIn *int64 `json:"tokens_in,omitempty"`
TokensOut *int64 `json:"tokens_out,omitempty"`
CostUSD *float64 `json:"cost_usd,omitempty"`
+
+ // Evidence is transient, bounded harness output. Activities redact and store
+ // these allowlisted relative paths before the sandbox is destroyed. It never
+ // travels through Temporal history or replaces factory verification.
+ Evidence map[string][]byte `json:"-"`
}
// Succeeded reports whether the agent exited zero and was not killed.
diff --git a/internal/agentharness/pi-catalog.json b/internal/agentharness/pi-catalog.json
new file mode 100644
index 0000000..5871719
--- /dev/null
+++ b/internal/agentharness/pi-catalog.json
@@ -0,0 +1,29146 @@
+{
+ "ant-ling": {
+ "Ling-2.6-1T": {
+ "id": "Ling-2.6-1T",
+ "name": "Ling 2.6 1T",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.25,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "ant-ling",
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false
+ }
+ },
+ "Ling-2.6-flash": {
+ "id": "Ling-2.6-flash",
+ "name": "Ling 2.6 Flash",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.01,
+ "output": 0.02,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "ant-ling",
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false
+ }
+ },
+ "Ring-2.6-1T": {
+ "id": "Ring-2.6-1T",
+ "name": "Ring 2.6 1T",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.25,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": "xhigh"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "ant-ling",
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false
+ }
+ }
+ },
+ "azure": {
+ "deepseek-v4-pro": {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.925,
+ "output": 3.828,
+ "cacheRead": 0.165,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "openai",
+ "supportsDeveloperRole": false,
+ "supportsMidConvoSystemMessages": true,
+ "supportsLongCacheRetention": false
+ }
+ }
+ },
+ "baseten": {
+ "deepseek-ai/DeepSeek-V4-Flash-0731": {
+ "id": "deepseek-ai/DeepSeek-V4-Flash-0731",
+ "name": "DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.13,
+ "output": 0.26,
+ "cacheRead": 0.028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "deepseek-ai/DeepSeek-V4-Pro": {
+ "id": "deepseek-ai/DeepSeek-V4-Pro",
+ "name": "DeepSeek V4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.74,
+ "output": 3.48,
+ "cacheRead": 0.145,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "deepseek-ai/DeepSeek-V4-Pro-0813": {
+ "id": "deepseek-ai/DeepSeek-V4-Pro-0813",
+ "name": "DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.32,
+ "output": 3.96,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "deepseek-ai/DeepSeek-V4.1-Flash": {
+ "id": "deepseek-ai/DeepSeek-V4.1-Flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "deepseek-ai/DeepSeek-V4.1-Flash-Fast": {
+ "id": "deepseek-ai/DeepSeek-V4.1-Flash-Fast",
+ "name": "deepseek-ai/DeepSeek-V4.1-Flash-Fast",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "moonshotai/Kimi-K2.5": {
+ "id": "moonshotai/Kimi-K2.5",
+ "name": "Kimi K2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262000,
+ "maxTokens": 262000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 3,
+ "cacheRead": 0.12,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "off",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "moonshotai/Kimi-K2.6": {
+ "id": "moonshotai/Kimi-K2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262000,
+ "maxTokens": 262000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "off",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "moonshotai/Kimi-K2.7-Code": {
+ "id": "moonshotai/Kimi-K2.7-Code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262000,
+ "maxTokens": 262000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "off",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "moonshotai/Kimi-K3": {
+ "id": "moonshotai/Kimi-K3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "nvidia/Nemotron-120B-A12B": {
+ "id": "nvidia/Nemotron-120B-A12B",
+ "name": "Nemotron Super",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202800,
+ "maxTokens": 202800,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 0.75,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "off",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B": {
+ "id": "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B",
+ "name": "Nemotron Ultra",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202800,
+ "maxTokens": 202800,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.4,
+ "cacheRead": 0.12,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "off",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "openai/gpt-oss-120b": {
+ "id": "openai/gpt-oss-120b",
+ "name": "OpenAI GPT 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128072,
+ "maxTokens": 128072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "thinkingmachines/inkling": {
+ "id": "thinkingmachines/inkling",
+ "name": "Inkling",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 4.05,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "thinkingmachines/inkling-small": {
+ "id": "thinkingmachines/inkling-small",
+ "name": "Inkling Small",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 1.2,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "zai-org/GLM-4.7": {
+ "id": "zai-org/GLM-4.7",
+ "name": "GLM 4.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 200000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.2,
+ "cacheRead": 0.12,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "off",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "zai-org/GLM-5": {
+ "id": "zai-org/GLM-5",
+ "name": "GLM 5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202800,
+ "maxTokens": 202800,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 3.15,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "off",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "zai-org/GLM-5.1": {
+ "id": "zai-org/GLM-5.1",
+ "name": "GLM 5.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202800,
+ "maxTokens": 202800,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.3,
+ "output": 4.3,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "off",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "zai-org/GLM-5.2": {
+ "id": "zai-org/GLM-5.2",
+ "name": "GLM 5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "zai-org/GLM-5.2-Fast": {
+ "id": "zai-org/GLM-5.2-Fast",
+ "name": "GLM 5.2 Fast",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.1,
+ "output": 6.6,
+ "cacheRead": 0.21,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "baseten",
+ "chatTemplateArgs": {
+ "enable_thinking": {
+ "$var": "thinking.enabled"
+ }
+ }
+ }
+ },
+ "zai-org/GLM-5.3": {
+ "id": "zai-org/GLM-5.3",
+ "name": "GLM 5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.14,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "zai-org/GLM-5.3-Fast": {
+ "id": "zai-org/GLM-5.3-Fast",
+ "name": "GLM 5.3 Fast",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.1,
+ "output": 6.6,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ },
+ "zai-org/GLM-5.3-Flash": {
+ "id": "zai-org/GLM-5.3-Flash",
+ "name": "GLM 5.3 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "supportsUsageInStreaming": true,
+ "maxTokensField": "max_tokens",
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "thinkingFormat": "openai"
+ }
+ }
+ },
+ "cerebras": {
+ "gpt-oss-120b": {
+ "id": "gpt-oss-120b",
+ "name": "GPT OSS 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 40960,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.35,
+ "output": 0.75,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false
+ }
+ },
+ "qwen-3.8-27b": {
+ "id": "qwen-3.8-27b",
+ "name": "Qwen3.8 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 40960,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.99,
+ "output": 1.49,
+ "cacheRead": 0.99,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false
+ }
+ }
+ },
+ "cloudflare-ai-gateway": {
+ "workers-ai/@cf/deepseek-ai/deepseek-v4-flash-0731": {
+ "id": "workers-ai/@cf/deepseek-ai/deepseek-v4-flash-0731",
+ "name": "DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.44,
+ "output": 1.32,
+ "cacheRead": 0.014,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "workers-ai/@cf/deepseek-ai/deepseek-v4-pro-0813": {
+ "id": "workers-ai/@cf/deepseek-ai/deepseek-v4-pro-0813",
+ "name": "DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.32,
+ "output": 3.96,
+ "cacheRead": 0.044,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "workers-ai/@cf/google/gemma-4-26b-a4b-it": {
+ "id": "workers-ai/@cf/google/gemma-4-26b-a4b-it",
+ "name": "Gemma 4 26B A4B IT",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.3,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/ibm-granite/granite-4.0-h-micro": {
+ "id": "workers-ai/@cf/ibm-granite/granite-4.0-h-micro",
+ "name": "Granite 4.0 H Micro",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131000,
+ "maxTokens": 131000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.017,
+ "output": 0.112,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast": {
+ "id": "workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast",
+ "name": "Llama 3.3 70B Instruct fp8 Fast",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 24000,
+ "maxTokens": 24000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.293,
+ "output": 2.253,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/meta/llama-4-scout-17b-16e-instruct": {
+ "id": "workers-ai/@cf/meta/llama-4-scout-17b-16e-instruct",
+ "name": "Llama 4 Scout 17B 16E Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.27,
+ "output": 0.85,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/mistralai/mistral-small-3.1-24b-instruct": {
+ "id": "workers-ai/@cf/mistralai/mistral-small-3.1-24b-instruct",
+ "name": "Mistral Small 3.1 24B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.351,
+ "output": 0.555,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/moonshotai/kimi-k2.6": {
+ "id": "workers-ai/@cf/moonshotai/kimi-k2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/moonshotai/kimi-k2.7-code": {
+ "id": "workers-ai/@cf/moonshotai/kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.19,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/nvidia/nemotron-3-120b-a12b": {
+ "id": "workers-ai/@cf/nvidia/nemotron-3-120b-a12b",
+ "name": "Nemotron 3 Super 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 1.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/openai/gpt-oss-120b": {
+ "id": "workers-ai/@cf/openai/gpt-oss-120b",
+ "name": "GPT OSS 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.35,
+ "output": 0.75,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/openai/gpt-oss-20b": {
+ "id": "workers-ai/@cf/openai/gpt-oss-20b",
+ "name": "GPT OSS 20B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/qwen/qwen3-30b-a3b-fp8": {
+ "id": "workers-ai/@cf/qwen/qwen3-30b-a3b-fp8",
+ "name": "Qwen3 30B A3b fp8",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 32768,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0509,
+ "output": 0.335,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/qwen/qwen3.8-27b": {
+ "id": "workers-ai/@cf/qwen/qwen3.8-27b",
+ "name": "Qwen3.8 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.45,
+ "output": 3.2,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/zai-org/glm-4.7-flash": {
+ "id": "workers-ai/@cf/zai-org/glm-4.7-flash",
+ "name": "GLM-4.7-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0605,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/zai-org/glm-5.2": {
+ "id": "workers-ai/@cf/zai-org/glm-5.2",
+ "name": "Glm 5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/zai-org/glm-5.3": {
+ "id": "workers-ai/@cf/zai-org/glm-5.3",
+ "name": "Glm 5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "workers-ai/@cf/zai-org/glm-5.3-flash": {
+ "id": "workers-ai/@cf/zai-org/glm-5.3-flash",
+ "name": "Glm 5.3 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "gpt-4.1": {
+ "id": "gpt-4.1",
+ "name": "GPT-4.1",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 8,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4.1-mini": {
+ "id": "gpt-4.1-mini",
+ "name": "GPT-4.1 mini",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 1.6,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4.1-nano": {
+ "id": "gpt-4.1-nano",
+ "name": "GPT-4.1 nano",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.4,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4o": {
+ "id": "gpt-4o",
+ "name": "GPT-4o",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 5,
+ "cacheRead": 0.625,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4o-mini": {
+ "id": "gpt-4o-mini",
+ "name": "GPT-4o mini",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.3,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-5": {
+ "id": "gpt-5",
+ "name": "GPT-5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5-mini": {
+ "id": "gpt-5-mini",
+ "name": "GPT-5 Mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5-nano": {
+ "id": "gpt-5-nano",
+ "name": "GPT-5 Nano",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.4,
+ "cacheRead": 0.005,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.1": {
+ "id": "gpt-5.1",
+ "name": "GPT-5.1",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4": {
+ "id": "gpt-5.4",
+ "name": "GPT-5.4",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 15,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4-mini": {
+ "id": "gpt-5.4-mini",
+ "name": "GPT-5.4 mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 4.5,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4-nano": {
+ "id": "gpt-5.4-nano",
+ "name": "GPT-5.4 nano",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.25,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4-pro": {
+ "id": "gpt-5.4-pro",
+ "name": "GPT-5.4 Pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 30,
+ "output": 180,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.5": {
+ "id": "gpt-5.5",
+ "name": "GPT-5.5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 30,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.5-pro": {
+ "id": "gpt-5.5-pro",
+ "name": "GPT-5.5 Pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 30,
+ "output": 180,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.6-luna": {
+ "id": "gpt-5.6-luna",
+ "name": "GPT-5.6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0.2,
+ "output": 1.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0.25
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.6-sol": {
+ "id": "gpt-5.6-sol",
+ "name": "GPT-5.6 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 4,
+ "output": 20,
+ "cacheRead": 0.4,
+ "cacheWrite": 5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.6-terra": {
+ "id": "gpt-5.6-terra",
+ "name": "GPT-5.6 Terra",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-6-astra": {
+ "id": "gpt-6-astra",
+ "name": "GPT-6 Astra",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-6-luna": {
+ "id": "gpt-6-luna",
+ "name": "GPT-6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-6-sol": {
+ "id": "gpt-6-sol",
+ "name": "GPT-6 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "o3": {
+ "id": "o3",
+ "name": "o3",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 8,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "o3-mini": {
+ "id": "o3-mini",
+ "name": "o3-mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.1,
+ "output": 4.4,
+ "cacheRead": 0.55,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "o4-mini": {
+ "id": "o4-mini",
+ "name": "o4-mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.1,
+ "output": 4.4,
+ "cacheRead": 0.275,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ }
+ },
+ "cloudflare-workers-ai": {
+ "@cf/deepseek-ai/deepseek-v4-flash-0731": {
+ "id": "@cf/deepseek-ai/deepseek-v4-flash-0731",
+ "name": "DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.44,
+ "output": 1.32,
+ "cacheRead": 0.014,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "@cf/deepseek-ai/deepseek-v4-pro-0813": {
+ "id": "@cf/deepseek-ai/deepseek-v4-pro-0813",
+ "name": "DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.32,
+ "output": 3.96,
+ "cacheRead": 0.044,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "@cf/google/gemma-4-26b-a4b-it": {
+ "id": "@cf/google/gemma-4-26b-a4b-it",
+ "name": "Gemma 4 26B A4B IT",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.3,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/ibm-granite/granite-4.0-h-micro": {
+ "id": "@cf/ibm-granite/granite-4.0-h-micro",
+ "name": "Granite 4.0 H Micro",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131000,
+ "maxTokens": 131000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.017,
+ "output": 0.112,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/meta/llama-3.3-70b-instruct-fp8-fast": {
+ "id": "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
+ "name": "Llama 3.3 70B Instruct fp8 Fast",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 24000,
+ "maxTokens": 24000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.293,
+ "output": 2.253,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/meta/llama-4-scout-17b-16e-instruct": {
+ "id": "@cf/meta/llama-4-scout-17b-16e-instruct",
+ "name": "Llama 4 Scout 17B 16E Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.27,
+ "output": 0.85,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/mistralai/mistral-small-3.1-24b-instruct": {
+ "id": "@cf/mistralai/mistral-small-3.1-24b-instruct",
+ "name": "Mistral Small 3.1 24B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.351,
+ "output": 0.555,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/moonshotai/kimi-k2.6": {
+ "id": "@cf/moonshotai/kimi-k2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/moonshotai/kimi-k2.7-code": {
+ "id": "@cf/moonshotai/kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.19,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/nvidia/nemotron-3-120b-a12b": {
+ "id": "@cf/nvidia/nemotron-3-120b-a12b",
+ "name": "Nemotron 3 Super 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 1.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/openai/gpt-oss-120b": {
+ "id": "@cf/openai/gpt-oss-120b",
+ "name": "GPT OSS 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.35,
+ "output": 0.75,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/openai/gpt-oss-20b": {
+ "id": "@cf/openai/gpt-oss-20b",
+ "name": "GPT OSS 20B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/qwen/qwen3-30b-a3b-fp8": {
+ "id": "@cf/qwen/qwen3-30b-a3b-fp8",
+ "name": "Qwen3 30B A3b fp8",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 32768,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0509,
+ "output": 0.335,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/qwen/qwen3.8-27b": {
+ "id": "@cf/qwen/qwen3.8-27b",
+ "name": "Qwen3.8 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.45,
+ "output": 3.2,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/zai-org/glm-4.7-flash": {
+ "id": "@cf/zai-org/glm-4.7-flash",
+ "name": "GLM-4.7-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0605,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/zai-org/glm-5.2": {
+ "id": "@cf/zai-org/glm-5.2",
+ "name": "Glm 5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/zai-org/glm-5.3": {
+ "id": "@cf/zai-org/glm-5.3",
+ "name": "Glm 5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "@cf/zai-org/glm-5.3-flash": {
+ "id": "@cf/zai-org/glm-5.3-flash",
+ "name": "Glm 5.3 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "supportsLongCacheRetention": false,
+ "sendSessionAffinityHeaders": true
+ }
+ }
+ },
+ "deepseek": {
+ "deepseek-flash": {
+ "id": "deepseek-flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.006,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "maxTokensField": "max_tokens",
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek",
+ "supportsStrictMode": true
+ }
+ },
+ "deepseek-v4-pro": {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.32,
+ "output": 3.96,
+ "cacheRead": 0.044,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "maxTokensField": "max_tokens",
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek",
+ "supportsStrictMode": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ }
+ },
+ "fireworks": {
+ "accounts/fireworks/models/glm-5p3": {
+ "id": "accounts/fireworks/models/glm-5p3",
+ "name": "GLM 5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048573,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false
+ }
+ },
+ "accounts/fireworks/models/glm-5p3-flash": {
+ "id": "accounts/fireworks/models/glm-5p3-flash",
+ "name": "GLM 5.3 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048573,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false
+ }
+ },
+ "accounts/fireworks/models/kimi-k3": {
+ "id": "accounts/fireworks/models/kimi-k3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "openai",
+ "supportsMidConvoSystemMessages": true,
+ "supportsMidConvoToolAdditions": true
+ }
+ },
+ "accounts/fireworks/routers/glm-5p3-fast": {
+ "id": "accounts/fireworks/routers/glm-5p3-fast",
+ "name": "GLM 5.3 Fast",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048572,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.1,
+ "output": 6.6,
+ "cacheRead": 0.39,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false
+ }
+ },
+ "accounts/fireworks/routers/glm-fast-latest": {
+ "id": "accounts/fireworks/routers/glm-fast-latest",
+ "name": "GLM 5.3 Fast (Latest)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048572,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.1,
+ "output": 6.6,
+ "cacheRead": 0.39,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false
+ }
+ },
+ "accounts/fireworks/routers/glm-flash-latest": {
+ "id": "accounts/fireworks/routers/glm-flash-latest",
+ "name": "GLM Flash Latest (GLM 5.3 Flash)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048573,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false
+ }
+ },
+ "accounts/fireworks/routers/glm-latest": {
+ "id": "accounts/fireworks/routers/glm-latest",
+ "name": "GLM Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048573,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false
+ }
+ },
+ "accounts/fireworks/routers/kimi-k3-fast": {
+ "id": "accounts/fireworks/routers/kimi-k3-fast",
+ "name": "Kimi K3 Fast",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 4.5,
+ "output": 22.5,
+ "cacheRead": 0.45,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "sendSessionAffinityHeaders": true,
+ "supportsLongCacheRetention": false,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "openai",
+ "supportsMidConvoSystemMessages": true,
+ "supportsMidConvoToolAdditions": true
+ }
+ }
+ },
+ "github-copilot": {
+ "gemini-3.5-flash": {
+ "id": "gemini-3.5-flash",
+ "name": "Gemini 3.5 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.5,
+ "output": 9,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "gemini-3.6-flash": {
+ "id": "gemini-3.6-flash",
+ "name": "Gemini 3.6 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 3.75,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "gemini-3.7-flash": {
+ "id": "gemini-3.7-flash",
+ "name": "Gemini 3.7 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 3.75,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "gemini-3.8-flash": {
+ "id": "gemini-3.8-flash",
+ "name": "Gemini 3.8 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 3.75,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "kimi-k2.7-code": {
+ "id": "kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 32000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.19,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "kimi-k3": {
+ "id": "kimi-k3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "gpt-5-mini": {
+ "id": "gpt-5-mini",
+ "name": "GPT-5 Mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 264000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.3-codex": {
+ "id": "gpt-5.3-codex",
+ "name": "GPT-5.3 Codex",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4": {
+ "id": "gpt-5.4",
+ "name": "GPT-5.4",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2.5,
+ "output": 15,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.4-mini": {
+ "id": "gpt-5.4-mini",
+ "name": "GPT-5.4 mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 4.5,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.4-nano": {
+ "id": "gpt-5.4-nano",
+ "name": "GPT-5.4 nano",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.25,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "xhigh": "xhigh"
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.5": {
+ "id": "gpt-5.5",
+ "name": "GPT-5.5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 5,
+ "output": 30,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.6-luna": {
+ "id": "gpt-5.6-luna",
+ "name": "GPT-5.6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0.2,
+ "output": 1.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0.25
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.6-sol": {
+ "id": "gpt-5.6-sol",
+ "name": "GPT-5.6 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 4,
+ "output": 20,
+ "cacheRead": 0.4,
+ "cacheWrite": 5
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.6-terra": {
+ "id": "gpt-5.6-terra",
+ "name": "GPT-5.6 Terra",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "low",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6-astra": {
+ "id": "gpt-6-astra",
+ "name": "GPT-6 Astra",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6-luna": {
+ "id": "gpt-6-luna",
+ "name": "GPT-6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6-sol": {
+ "id": "gpt-6-sol",
+ "name": "GPT-6 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6.1-sol": {
+ "id": "gpt-6.1-sol",
+ "name": "GPT-6.1 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.1,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "grok-4.5": {
+ "id": "grok-4.5",
+ "name": "Grok 4.5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ }
+ },
+ "grok-4.6": {
+ "id": "grok-4.6",
+ "name": "Grok 4.6",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ }
+ },
+ "grok-4.7": {
+ "id": "grok-4.7",
+ "name": "Grok 4.7",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ }
+ },
+ "mai-code-1-flash-picker": {
+ "id": "mai-code-1-flash-picker",
+ "name": "MAI-Code-1-Flash",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 4.5,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ }
+ },
+ "mai-code-1.1-flash": {
+ "id": "mai-code-1.1-flash",
+ "name": "MAI-Code-1.1-Flash",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ }
+ }
+ },
+ "groq": {
+ "llama-3.1-8b-instant": {
+ "id": "llama-3.1-8b-instant",
+ "name": "Llama 3.1 8B",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.08,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "llama-3.3-70b-versatile": {
+ "id": "llama-3.3-70b-versatile",
+ "name": "Llama 3.3 70B",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.59,
+ "output": 0.79,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "openai/gpt-oss-120b": {
+ "id": "openai/gpt-oss-120b",
+ "name": "GPT OSS 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "openai/gpt-oss-20b": {
+ "id": "openai/gpt-oss-20b",
+ "name": "GPT OSS 20B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.3,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "openai/gpt-oss-safeguard-20b": {
+ "id": "openai/gpt-oss-safeguard-20b",
+ "name": "Safety GPT OSS 20B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "qwen/qwen3.6-27b": {
+ "id": "qwen/qwen3.6-27b",
+ "name": "Qwen3.6 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 3,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "default",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "qwen/qwen3.8-27b": {
+ "id": "qwen/qwen3.8-27b",
+ "name": "Qwen3.8 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131042,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.8,
+ "output": 4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ }
+ },
+ "huggingface": {
+ "deepseek-ai/DeepSeek-R1": {
+ "id": "deepseek-ai/DeepSeek-R1",
+ "name": "DeepSeek-R1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 64000,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.7,
+ "output": 2.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-R1-0528": {
+ "id": "deepseek-ai/DeepSeek-R1-0528",
+ "name": "DeepSeek-R1-0528",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 163840,
+ "maxTokens": 163840,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V3": {
+ "id": "deepseek-ai/DeepSeek-V3",
+ "name": "DeepSeek-V3",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 64000,
+ "maxTokens": 8192,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 1.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V3-0324": {
+ "id": "deepseek-ai/DeepSeek-V3-0324",
+ "name": "DeepSeek V3 0324",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 163840,
+ "maxTokens": 163840,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.27,
+ "output": 1.12,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V3.1": {
+ "id": "deepseek-ai/DeepSeek-V3.1",
+ "name": "DeepSeek-V3.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 8192,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.27,
+ "output": 1,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V3.2": {
+ "id": "deepseek-ai/DeepSeek-V3.2",
+ "name": "DeepSeek-V3.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 163840,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.28,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V4-Flash": {
+ "id": "deepseek-ai/DeepSeek-V4-Flash",
+ "name": "DeepSeek V4 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V4-Flash-0731": {
+ "id": "deepseek-ai/DeepSeek-V4-Flash-0731",
+ "name": "DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V4-Flash-Vision-Exp": {
+ "id": "deepseek-ai/DeepSeek-V4-Flash-Vision-Exp",
+ "name": "DeepSeek V4 Flash Vision Exp",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.44,
+ "output": 1.32,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V4-Pro": {
+ "id": "deepseek-ai/DeepSeek-V4-Pro",
+ "name": "DeepSeek V4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 393216,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.435,
+ "output": 0.87,
+ "cacheRead": 0.003625,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V4-Pro-0813": {
+ "id": "deepseek-ai/DeepSeek-V4-Pro-0813",
+ "name": "DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.32,
+ "output": 3.96,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V4.1-Flash": {
+ "id": "deepseek-ai/DeepSeek-V4.1-Flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "google/gemma-3-12b-it": {
+ "id": "google/gemma-3-12b-it",
+ "name": "Gemma 3 12B IT",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "google/gemma-3-27b-it": {
+ "id": "google/gemma-3-27b-it",
+ "name": "Gemma 3 27B IT",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.08,
+ "output": 0.16,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "google/gemma-3-4b-it": {
+ "id": "google/gemma-3-4b-it",
+ "name": "Gemma 3 4B IT",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.1,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "google/gemma-4-26B-A4B-it": {
+ "id": "google/gemma-4-26B-A4B-it",
+ "name": "Gemma 4 26B A4B IT",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.13,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "google/gemma-4-31B-it": {
+ "id": "google/gemma-4-31B-it",
+ "name": "Gemma 4 31B IT",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "meta-llama/Llama-3.1-8B-Instruct": {
+ "id": "meta-llama/Llama-3.1-8B-Instruct",
+ "name": "Llama-3.1-8B-Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.06,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "meta-llama/Llama-3.3-70B-Instruct": {
+ "id": "meta-llama/Llama-3.3-70B-Instruct",
+ "name": "Llama-3.3-70B-Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.59,
+ "output": 0.79,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "MiniMaxAI/MiniMax-M2": {
+ "id": "MiniMaxAI/MiniMax-M2",
+ "name": "MiniMax-M2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "MiniMaxAI/MiniMax-M2.1": {
+ "id": "MiniMaxAI/MiniMax-M2.1",
+ "name": "MiniMax-M2.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "MiniMaxAI/MiniMax-M2.5": {
+ "id": "MiniMaxAI/MiniMax-M2.5",
+ "name": "MiniMax-M2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "MiniMaxAI/MiniMax-M2.7": {
+ "id": "MiniMaxAI/MiniMax-M2.7",
+ "name": "MiniMax-M2.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "MiniMaxAI/MiniMax-M3": {
+ "id": "MiniMaxAI/MiniMax-M3",
+ "name": "MiniMax-M3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 512000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "moonshotai/Kimi-K2-Instruct": {
+ "id": "moonshotai/Kimi-K2-Instruct",
+ "name": "Kimi-K2-Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "moonshotai/Kimi-K2-Instruct-0905": {
+ "id": "moonshotai/Kimi-K2-Instruct-0905",
+ "name": "Kimi-K2-Instruct-0905",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "moonshotai/Kimi-K2-Thinking": {
+ "id": "moonshotai/Kimi-K2-Thinking",
+ "name": "Kimi-K2-Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.5,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "moonshotai/Kimi-K2.5": {
+ "id": "moonshotai/Kimi-K2.5",
+ "name": "Kimi-K2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 3,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "moonshotai/Kimi-K2.6": {
+ "id": "moonshotai/Kimi-K2.6",
+ "name": "Kimi-K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "moonshotai/Kimi-K2.7-Code": {
+ "id": "moonshotai/Kimi-K2.7-Code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "moonshotai/Kimi-K3": {
+ "id": "moonshotai/Kimi-K3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "openai/gpt-oss-120b": {
+ "id": "openai/gpt-oss-120b",
+ "name": "GPT OSS 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 0.69,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "openai/gpt-oss-20b": {
+ "id": "openai/gpt-oss-20b",
+ "name": "GPT OSS 20B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen2.5-Coder-32B-Instruct": {
+ "id": "Qwen/Qwen2.5-Coder-32B-Instruct",
+ "name": "Qwen2.5-Coder-32B-Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 8192,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-235B-A22B": {
+ "id": "Qwen/Qwen3-235B-A22B",
+ "name": "Qwen3 235B-A22B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 40960,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 0.8,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-235B-A22B-Instruct-2507": {
+ "id": "Qwen/Qwen3-235B-A22B-Instruct-2507",
+ "name": "Qwen3 235B-A22B Instruct 2507",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.855,
+ "output": 2.565,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-235B-A22B-Thinking-2507": {
+ "id": "Qwen/Qwen3-235B-A22B-Thinking-2507",
+ "name": "Qwen3-235B-A22B-Thinking-2507",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-30B-A3B": {
+ "id": "Qwen/Qwen3-30B-A3B",
+ "name": "Qwen3 30B A3B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 40960,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.12,
+ "output": 0.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-32B": {
+ "id": "Qwen/Qwen3-32B",
+ "name": "Qwen3 32B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.29,
+ "output": 0.59,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-Coder-30B-A3B-Instruct": {
+ "id": "Qwen/Qwen3-Coder-30B-A3B-Instruct",
+ "name": "Qwen3-Coder 30B-A3B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.07,
+ "output": 0.26,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-Coder-480B-A35B-Instruct": {
+ "id": "Qwen/Qwen3-Coder-480B-A35B-Instruct",
+ "name": "Qwen3-Coder-480B-A35B-Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 66536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-Coder-Next": {
+ "id": "Qwen/Qwen3-Coder-Next",
+ "name": "Qwen3-Coder-Next",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-Next-80B-A3B-Instruct": {
+ "id": "Qwen/Qwen3-Next-80B-A3B-Instruct",
+ "name": "Qwen3-Next-80B-A3B-Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 66536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 1,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-Next-80B-A3B-Thinking": {
+ "id": "Qwen/Qwen3-Next-80B-A3B-Thinking",
+ "name": "Qwen3-Next-80B-A3B-Thinking",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-VL-235B-A22B-Instruct": {
+ "id": "Qwen/Qwen3-VL-235B-A22B-Instruct",
+ "name": "Qwen3 VL 235B A22B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3-VL-235B-A22B-Thinking": {
+ "id": "Qwen/Qwen3-VL-235B-A22B-Thinking",
+ "name": "Qwen3 VL 235B A22B Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.98,
+ "output": 3.95,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.5-122B-A10B": {
+ "id": "Qwen/Qwen3.5-122B-A10B",
+ "name": "Qwen3.5 122B-A10B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 3.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.5-27B": {
+ "id": "Qwen/Qwen3.5-27B",
+ "name": "Qwen3.5 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 2.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.5-35B-A3B": {
+ "id": "Qwen/Qwen3.5-35B-A3B",
+ "name": "Qwen3.5 35B-A3B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.5-397B-A17B": {
+ "id": "Qwen/Qwen3.5-397B-A17B",
+ "name": "Qwen3.5-397B-A17B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 3.6,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.5-9B": {
+ "id": "Qwen/Qwen3.5-9B",
+ "name": "Qwen3.5 9B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.17,
+ "output": 0.25,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.6-27B": {
+ "id": "Qwen/Qwen3.6-27B",
+ "name": "Qwen3.6 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.47,
+ "output": 3.19,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.6-35B-A3B": {
+ "id": "Qwen/Qwen3.6-35B-A3B",
+ "name": "Qwen3.6 35B-A3B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.95,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.8-2.4T-A95B": {
+ "id": "Qwen/Qwen3.8-2.4T-A95B",
+ "name": "Qwen3.8 2.4T A95B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 6.25,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "Qwen/Qwen3.8-27B": {
+ "id": "Qwen/Qwen3.8-27B",
+ "name": "Qwen3.8 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "stepfun-ai/Step-3.5-Flash": {
+ "id": "stepfun-ai/Step-3.5-Flash",
+ "name": "Step 3.5 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "stepfun-ai/Step-3.7-Flash": {
+ "id": "stepfun-ai/Step-3.7-Flash",
+ "name": "Step 3.7 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "tencent/Hy3": {
+ "id": "tencent/Hy3",
+ "name": "Hy3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.58,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "tencent/Hy4-preview": {
+ "id": "tencent/Hy4-preview",
+ "name": "Hy4 preview",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.834,
+ "output": 2.501,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "thinkingmachines/Inkling": {
+ "id": "thinkingmachines/Inkling",
+ "name": "Inkling",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 4.05,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "thinkingmachines/Inkling-Small": {
+ "id": "thinkingmachines/Inkling-Small",
+ "name": "Inkling Small",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 1.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "XiaomiMiMo/MiMo-V2-Flash": {
+ "id": "XiaomiMiMo/MiMo-V2-Flash",
+ "name": "MiMo-V2-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "XiaomiMiMo/MiMo-V2.5": {
+ "id": "XiaomiMiMo/MiMo-V2.5",
+ "name": "MiMo-V2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "XiaomiMiMo/MiMo-V2.5-Pro": {
+ "id": "XiaomiMiMo/MiMo-V2.5-Pro",
+ "name": "MiMo-V2.5-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-4.5": {
+ "id": "zai-org/GLM-4.5",
+ "name": "GLM-4.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 98304,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-4.5-Air": {
+ "id": "zai-org/GLM-4.5-Air",
+ "name": "GLM-4.5-Air",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 98304,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.13,
+ "output": 0.85,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-4.5V": {
+ "id": "zai-org/GLM-4.5V",
+ "name": "GLM-4.5V",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 65536,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 1.8,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-4.6": {
+ "id": "zai-org/GLM-4.6",
+ "name": "GLM-4.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.55,
+ "output": 2.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-4.6V-Flash": {
+ "id": "zai-org/GLM-4.6V-Flash",
+ "name": "GLM-4.6V-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 0.9,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-4.7": {
+ "id": "zai-org/GLM-4.7",
+ "name": "GLM-4.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.2,
+ "cacheRead": 0.11,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-4.7-Flash": {
+ "id": "zai-org/GLM-4.7-Flash",
+ "name": "GLM-4.7-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-5": {
+ "id": "zai-org/GLM-5",
+ "name": "GLM-5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 3.2,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-5.1": {
+ "id": "zai-org/GLM-5.1",
+ "name": "GLM-5.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 3.2,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-5.2": {
+ "id": "zai-org/GLM-5.2",
+ "name": "GLM-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-5.3": {
+ "id": "zai-org/GLM-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ },
+ "zai-org/GLM-5.3-Flash": {
+ "id": "zai-org/GLM-5.3-Flash",
+ "name": "GLM-5.3-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsDeveloperRole": false
+ }
+ }
+ },
+ "meta": {
+ "muse-spark-1.1": {
+ "id": "muse-spark-1.1",
+ "name": "Muse Spark 1.1",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 4.25,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ }
+ },
+ "muse-spark-1.2": {
+ "id": "muse-spark-1.2",
+ "name": "Muse Spark 1.2",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 4.25,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ }
+ },
+ "muse-spark-1.2-contributor": {
+ "id": "muse-spark-1.2-contributor",
+ "name": "Muse Spark 1.2 Contributor",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.2,
+ "cacheRead": 0.002,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ }
+ },
+ "muse-spark-1.3": {
+ "id": "muse-spark-1.3",
+ "name": "Muse Spark 1.3",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 4.25,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ }
+ },
+ "muse-spark-1.3-contributor": {
+ "id": "muse-spark-1.3-contributor",
+ "name": "Muse Spark 1.3 Contributor",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.2,
+ "cacheRead": 0.002,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ }
+ }
+ },
+ "moonshotai": {
+ "kimi-k2.6": {
+ "id": "kimi-k2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsStrictMode": false,
+ "thinkingFormat": "deepseek",
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "kimi-k2.7-code": {
+ "id": "kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.19,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsStrictMode": false,
+ "thinkingFormat": "deepseek",
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "kimi-k2.7-code-highspeed": {
+ "id": "kimi-k2.7-code-highspeed",
+ "name": "Kimi K2.7 Code HighSpeed",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.9,
+ "output": 8,
+ "cacheRead": 0.38,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsStrictMode": false,
+ "thinkingFormat": "deepseek",
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "kimi-k3": {
+ "id": "kimi-k3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "supportsStrictMode": false,
+ "thinkingFormat": "openai",
+ "requiresReasoningContentOnAssistantMessages": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsMidConvoToolAdditions": true
+ }
+ }
+ },
+ "moonshotai-cn": {
+ "kimi-k2.6": {
+ "id": "kimi-k2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsStrictMode": false,
+ "thinkingFormat": "deepseek",
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "kimi-k2.7-code": {
+ "id": "kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.19,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsStrictMode": false,
+ "thinkingFormat": "deepseek",
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "kimi-k2.7-code-highspeed": {
+ "id": "kimi-k2.7-code-highspeed",
+ "name": "Kimi K2.7 Code HighSpeed",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.9,
+ "output": 8,
+ "cacheRead": 0.38,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsStrictMode": false,
+ "thinkingFormat": "deepseek",
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "kimi-k3": {
+ "id": "kimi-k3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 1048576,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "supportsStrictMode": false,
+ "thinkingFormat": "openai",
+ "requiresReasoningContentOnAssistantMessages": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsMidConvoToolAdditions": true
+ }
+ }
+ },
+ "nvidia": {
+ "deepseek-ai/deepseek-v4.1-flash": {
+ "id": "deepseek-ai/deepseek-v4.1-flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "google/diffusiongemma-26b-a4b-it": {
+ "id": "google/diffusiongemma-26b-a4b-it",
+ "name": "DiffusionGemma 26B A4B IT",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 250000,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "google/gemma-3-12b-it": {
+ "id": "google/gemma-3-12b-it",
+ "name": "Gemma 3 12B IT",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "google/gemma-3-4b-it": {
+ "id": "google/gemma-3-4b-it",
+ "name": "Gemma 3 4B IT",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "meta/llama-3.2-11b-vision-instruct": {
+ "id": "meta/llama-3.2-11b-vision-instruct",
+ "name": "Llama 3.2 11b Vision Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 4096,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "meta/llama-3.2-90b-vision-instruct": {
+ "id": "meta/llama-3.2-90b-vision-instruct",
+ "name": "Llama-3.2-90B-Vision-Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 8192,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "meta/muse-glimmer-30b": {
+ "id": "meta/muse-glimmer-30b",
+ "name": "Muse Glimmer 30B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "mistralai/mistral-7b-instruct-v0.3": {
+ "id": "mistralai/mistral-7b-instruct-v0.3",
+ "name": "Mistral-7B-Instruct-v0.3",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 65536,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "moonshotai/kimi-k2.6": {
+ "id": "moonshotai/kimi-k2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "moonshotai/kimi-k3": {
+ "id": "moonshotai/kimi-k3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "nvidia/cosmos-reason2-8b": {
+ "id": "nvidia/cosmos-reason2-8b",
+ "name": "Cosmos Reason2 8B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "nvidia/llama-3.1-nemotron-70b-instruct": {
+ "id": "nvidia/llama-3.1-nemotron-70b-instruct",
+ "name": "Llama 3.1 Nemotron 70B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 8192,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "nvidia/llama-3.1-nemotron-ultra-253b-v1": {
+ "id": "nvidia/llama-3.1-nemotron-ultra-253b-v1",
+ "name": "Llama 3.1 Nemotron Ultra 253B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning": {
+ "id": "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning",
+ "name": "Nemotron 3 Nano Omni",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "nvidia/nemotron-3-super-120b-a12b": {
+ "id": "nvidia/nemotron-3-super-120b-a12b",
+ "name": "Nemotron 3 Super",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 0.8,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "nvidia/nemotron-3-ultra-550b-a55b": {
+ "id": "nvidia/nemotron-3-ultra-550b-a55b",
+ "name": "Nemotron 3 Ultra 550B A55B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 2.5,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "nvidia/nemotron-3.5-lightning-30b-a3b": {
+ "id": "nvidia/nemotron-3.5-lightning-30b-a3b",
+ "name": "Nemotron 3.5 Lightning 30B A3B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "openai/gpt-oss-20b": {
+ "id": "openai/gpt-oss-20b",
+ "name": "GPT OSS 20B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "poolside/laguna-xs-2.1": {
+ "id": "poolside/laguna-xs-2.1",
+ "name": "Laguna XS 2.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 16384,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "z-ai/glm-5.3": {
+ "id": "z-ai/glm-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "z-ai/glm-5.3-flash": {
+ "id": "z-ai/glm-5.3-flash",
+ "name": "GLM-5.3-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ }
+ },
+ "openai": {
+ "gpt-4": {
+ "id": "gpt-4",
+ "name": "GPT-4",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 8192,
+ "maxTokens": 8192,
+ "pricingKnown": true,
+ "cost": {
+ "input": 30,
+ "output": 60,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4-turbo": {
+ "id": "gpt-4-turbo",
+ "name": "GPT-4 Turbo",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 10,
+ "output": 30,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4.1": {
+ "id": "gpt-4.1",
+ "name": "GPT-4.1",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 8,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4.1-mini": {
+ "id": "gpt-4.1-mini",
+ "name": "GPT-4.1 mini",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 1.6,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4.1-nano": {
+ "id": "gpt-4.1-nano",
+ "name": "GPT-4.1 nano",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.4,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4o": {
+ "id": "gpt-4o",
+ "name": "GPT-4o",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 10,
+ "cacheRead": 1.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4o-2024-05-13": {
+ "id": "gpt-4o-2024-05-13",
+ "name": "GPT-4o (2024-05-13)",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4o-2024-08-06": {
+ "id": "gpt-4o-2024-08-06",
+ "name": "GPT-4o (2024-08-06)",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 10,
+ "cacheRead": 1.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4o-2024-11-20": {
+ "id": "gpt-4o-2024-11-20",
+ "name": "GPT-4o (2024-11-20)",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 10,
+ "cacheRead": 1.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-4o-mini": {
+ "id": "gpt-4o-mini",
+ "name": "GPT-4o mini",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "gpt-5": {
+ "id": "gpt-5",
+ "name": "GPT-5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5-chat-latest": {
+ "id": "gpt-5-chat-latest",
+ "name": "GPT-5 Chat Latest",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5-mini": {
+ "id": "gpt-5-mini",
+ "name": "GPT-5 Mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5-nano": {
+ "id": "gpt-5-nano",
+ "name": "GPT-5 Nano",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.4,
+ "cacheRead": 0.005,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5-pro": {
+ "id": "gpt-5-pro",
+ "name": "GPT-5 Pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 15,
+ "output": 120,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.1": {
+ "id": "gpt-5.1",
+ "name": "GPT-5.1",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.2": {
+ "id": "gpt-5.2",
+ "name": "GPT-5.2",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.2-chat-latest": {
+ "id": "gpt-5.2-chat-latest",
+ "name": "GPT-5.2 Chat",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.2-pro": {
+ "id": "gpt-5.2-pro",
+ "name": "GPT-5.2 Pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 21,
+ "output": 168,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.3-chat-latest": {
+ "id": "gpt-5.3-chat-latest",
+ "name": "GPT-5.3 Chat (latest)",
+ "api": "openai-responses",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "xhigh": "xhigh"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.3-codex": {
+ "id": "gpt-5.3-codex",
+ "name": "GPT-5.3 Codex",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.3-codex-spark": {
+ "id": "gpt-5.3-codex-spark",
+ "name": "GPT-5.3 Codex Spark",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 32000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4": {
+ "id": "gpt-5.4",
+ "name": "GPT-5.4",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2.5,
+ "output": 15,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "gpt-5.4-mini": {
+ "id": "gpt-5.4-mini",
+ "name": "GPT-5.4 mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 4.5,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "gpt-5.4-nano": {
+ "id": "gpt-5.4-nano",
+ "name": "GPT-5.4 nano",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.25,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4-pro": {
+ "id": "gpt-5.4-pro",
+ "name": "GPT-5.4 Pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 30,
+ "output": 180,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "gpt-5.5": {
+ "id": "gpt-5.5",
+ "name": "GPT-5.5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 5,
+ "output": 30,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "gpt-5.5-pro": {
+ "id": "gpt-5.5-pro",
+ "name": "GPT-5.5 Pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 30,
+ "output": 180,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.6-luna": {
+ "id": "gpt-5.6-luna",
+ "name": "GPT-5.6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0.2,
+ "output": 1.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0.25
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-5.6-sol": {
+ "id": "gpt-5.6-sol",
+ "name": "GPT-5.6 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 4,
+ "output": 20,
+ "cacheRead": 0.4,
+ "cacheWrite": 5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-5.6-terra": {
+ "id": "gpt-5.6-terra",
+ "name": "GPT-5.6 Terra",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-6-astra": {
+ "id": "gpt-6-astra",
+ "name": "GPT-6 Astra",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-6-luna": {
+ "id": "gpt-6-luna",
+ "name": "GPT-6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-6-sol": {
+ "id": "gpt-6-sol",
+ "name": "GPT-6 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-6.1-sol": {
+ "id": "gpt-6.1-sol",
+ "name": "GPT-6.1 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.1,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsOpenAIGrammarTools": true,
+ "supportsAdditionalTools": true,
+ "supportsToolSearch": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-daybreak-blue-latest": {
+ "id": "gpt-daybreak-blue-latest",
+ "name": "Daybreak Blue",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 4,
+ "output": 20,
+ "cacheRead": 0.4,
+ "cacheWrite": 5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-daybreak-red-latest": {
+ "id": "gpt-daybreak-red-latest",
+ "name": "Daybreak Red",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 12.5,
+ "output": 75,
+ "cacheRead": 1.25,
+ "cacheWrite": 15.625
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "supportsExplicitPromptCacheMode": true
+ }
+ },
+ "gpt-realtime-2.1": {
+ "id": "gpt-realtime-2.1",
+ "name": "GPT-Realtime-2.1",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 32000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 4,
+ "output": 24,
+ "cacheRead": 0.4,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "o1": {
+ "id": "o1",
+ "name": "o1",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 15,
+ "output": 60,
+ "cacheRead": 7.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "o1-pro": {
+ "id": "o1-pro",
+ "name": "o1-pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 150,
+ "output": 600,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "o3": {
+ "id": "o3",
+ "name": "o3",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 8,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "o3-mini": {
+ "id": "o3-mini",
+ "name": "o3-mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.1,
+ "output": 4.4,
+ "cacheRead": 0.55,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "o3-pro": {
+ "id": "o3-pro",
+ "name": "o3-pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 20,
+ "output": 80,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ },
+ "o4-mini": {
+ "id": "o4-mini",
+ "name": "o4-mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.1,
+ "output": 4.4,
+ "cacheRead": 0.275,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true
+ }
+ }
+ },
+ "opencode": {
+ "big-pickle": {
+ "id": "big-pickle",
+ "name": "Big Pickle",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 32000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "deepseek-v4-flash": {
+ "id": "deepseek-v4-flash",
+ "name": "DeepSeek V4 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek-v4-flash-vision-exp": {
+ "id": "deepseek-v4-flash-vision-exp",
+ "name": "DeepSeek V4 Flash Vision Exp",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek-v4-pro": {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.74,
+ "output": 3.84,
+ "cacheRead": 0.145,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek-v4.1-flash": {
+ "id": "deepseek-v4.1-flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.006,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "fledge-alpha-free": {
+ "id": "fledge-alpha-free",
+ "name": "Fledge Alpha Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "glm-5": {
+ "id": "glm-5",
+ "name": "GLM-5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 3.2,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "glm-5.1": {
+ "id": "glm-5.1",
+ "name": "GLM-5.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "glm-5.2": {
+ "id": "glm-5.2",
+ "name": "GLM-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "glm-5.3": {
+ "id": "glm-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "glm-5.3-flash": {
+ "id": "glm-5.3-flash",
+ "name": "GLM-5.3-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "kimi-k2.5": {
+ "id": "kimi-k2.5",
+ "name": "Kimi K2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 3,
+ "cacheRead": 0.08,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false
+ }
+ },
+ "kimi-k2.6": {
+ "id": "kimi-k2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "thinkingFormat": "deepseek",
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false
+ }
+ },
+ "kimi-k2.7-code": {
+ "id": "kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.19,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "kimi-k3": {
+ "id": "kimi-k3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": null,
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "supportsMidConvoSystemMessages": true,
+ "supportsMidConvoToolAdditions": true
+ }
+ },
+ "ling-3.0-flash-fin-free": {
+ "id": "ling-3.0-flash-fin-free",
+ "name": "Ling 3.0 Flash Fin Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "ling-3.1-flash-free": {
+ "id": "ling-3.1-flash-free",
+ "name": "Ling 3.1 Flash Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "longcat-2.5-preview-free": {
+ "id": "longcat-2.5-preview-free",
+ "name": "LongCat 2.5 Preview Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "mimo-v2.6-flash-free": {
+ "id": "mimo-v2.6-flash-free",
+ "name": "MiMo-V2.6-Flash Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 32000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "minimax-m2.5": {
+ "id": "minimax-m2.5",
+ "name": "MiniMax-M2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "minimax-m2.7": {
+ "id": "minimax-m2.7",
+ "name": "MiniMax-M2.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false
+ }
+ },
+ "minimax-m3": {
+ "id": "minimax-m3",
+ "name": "MiniMax-M3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 512000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "nemotron-3-ultra-free": {
+ "id": "nemotron-3-ultra-free",
+ "name": "Nemotron 3 Ultra Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "nemotron-3.5-lightning-free": {
+ "id": "nemotron-3.5-lightning-free",
+ "name": "Nemotron 3.5 Lightning Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "qwen3.8-max": {
+ "id": "qwen3.8-max",
+ "name": "Qwen3.8 Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.25,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "space-bunny-free": {
+ "id": "space-bunny-free",
+ "name": "Space Bunny Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 524288,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "gpt-5": {
+ "id": "gpt-5",
+ "name": "GPT-5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.07,
+ "output": 8.5,
+ "cacheRead": 0.107,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5-codex": {
+ "id": "gpt-5-codex",
+ "name": "GPT-5 Codex",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.07,
+ "output": 8.5,
+ "cacheRead": 0.107,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5-nano": {
+ "id": "gpt-5-nano",
+ "name": "GPT-5 Nano",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.4,
+ "cacheRead": 0.005,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.1": {
+ "id": "gpt-5.1",
+ "name": "GPT-5.1",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.07,
+ "output": 8.5,
+ "cacheRead": 0.107,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.1-codex": {
+ "id": "gpt-5.1-codex",
+ "name": "GPT-5.1 Codex",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.07,
+ "output": 8.5,
+ "cacheRead": 0.107,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.1-codex-max": {
+ "id": "gpt-5.1-codex-max",
+ "name": "GPT-5.1 Codex Max",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.1-codex-mini": {
+ "id": "gpt-5.1-codex-mini",
+ "name": "GPT-5.1 Codex Mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.2": {
+ "id": "gpt-5.2",
+ "name": "GPT-5.2",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.2-codex": {
+ "id": "gpt-5.2-codex",
+ "name": "GPT-5.2 Codex",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.3-codex": {
+ "id": "gpt-5.3-codex",
+ "name": "GPT-5.3 Codex",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4": {
+ "id": "gpt-5.4",
+ "name": "GPT-5.4",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 272000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 15,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.4-mini": {
+ "id": "gpt-5.4-mini",
+ "name": "GPT-5.4 Mini",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 4.5,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.4-nano": {
+ "id": "gpt-5.4-nano",
+ "name": "GPT-5.4 Nano",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.25,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.4-pro": {
+ "id": "gpt-5.4-pro",
+ "name": "GPT-5.4 Pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 30,
+ "output": 180,
+ "cacheRead": 30,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.5": {
+ "id": "gpt-5.5",
+ "name": "GPT-5.5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 30,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.5-pro": {
+ "id": "gpt-5.5-pro",
+ "name": "GPT-5.5 Pro",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 30,
+ "output": 180,
+ "cacheRead": 30,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true
+ }
+ },
+ "gpt-5.6-luna": {
+ "id": "gpt-5.6-luna",
+ "name": "GPT-5.6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0.25
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.6-sol": {
+ "id": "gpt-5.6-sol",
+ "name": "GPT-5.6 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 4,
+ "output": 20,
+ "cacheRead": 0.4,
+ "cacheWrite": 5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-5.6-terra": {
+ "id": "gpt-5.6-terra",
+ "name": "GPT-5.6 Terra",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 15,
+ "cacheRead": 0.25,
+ "cacheWrite": 3.125
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6-astra": {
+ "id": "gpt-6-astra",
+ "name": "GPT-6 Astra",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6-luna": {
+ "id": "gpt-6-luna",
+ "name": "GPT-6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6-sol": {
+ "id": "gpt-6-sol",
+ "name": "GPT-6 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6.1-sol": {
+ "id": "gpt-6.1-sol",
+ "name": "GPT-6.1 Sol",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.1,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsOpenAIGrammarTools": true,
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "grok-4.5": {
+ "id": "grok-4.5",
+ "name": "Grok 4.5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 500000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ },
+ "grok-4.6": {
+ "id": "grok-4.6",
+ "name": "Grok 4.6",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 500000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ },
+ "grok-4.7": {
+ "id": "grok-4.7",
+ "name": "Grok 4.7",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 500000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ },
+ "grok-build-0.1": {
+ "id": "grok-build-0.1",
+ "name": "Grok Build 0.1",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 256000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 2,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsReasoningEffort": false
+ }
+ },
+ "muse-spark-1.2": {
+ "id": "muse-spark-1.2",
+ "name": "Muse Spark 1.2",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 4.25,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ },
+ "muse-spark-1.3": {
+ "id": "muse-spark-1.3",
+ "name": "Muse Spark 1.3",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 4.25,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ },
+ "muse-spark-1.3-contributor-free": {
+ "id": "muse-spark-1.3-contributor-free",
+ "name": "Muse Spark 1.3 Free",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ }
+ },
+ "opencode-go": {
+ "deepseek-v4-flash": {
+ "id": "deepseek-v4-flash",
+ "name": "DeepSeek V4 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.003,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "deepseek-v4-flash-vision-exp": {
+ "id": "deepseek-v4-flash-vision-exp",
+ "name": "DeepSeek V4 Flash Vision Exp",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.003,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "deepseek-v4-pro": {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro (New)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.66,
+ "output": 1.98,
+ "cacheRead": 0.022,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "deepseek-v4.1-flash": {
+ "id": "deepseek-v4.1-flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.003,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "glm-5.2": {
+ "id": "glm-5.2",
+ "name": "GLM-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "glm-5.3": {
+ "id": "glm-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "glm-5.3-flash": {
+ "id": "glm-5.3-flash",
+ "name": "GLM-5.3-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "hy3": {
+ "id": "hy3",
+ "name": "Hy3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.58,
+ "cacheRead": 0.035,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "hy4-preview": {
+ "id": "hy4-preview",
+ "name": "Hy4 preview",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1024000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.834,
+ "output": 2.501,
+ "cacheRead": 0.042,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "kimi-k2.7-code": {
+ "id": "kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.19,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "kimi-k3": {
+ "id": "kimi-k3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": null,
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens",
+ "supportsMidConvoSystemMessages": true,
+ "supportsMidConvoToolAdditions": true
+ }
+ },
+ "longcat-2.0": {
+ "id": "longcat-2.0",
+ "name": "LongCat-2.0",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.006,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "longcat-2.5-preview-free": {
+ "id": "longcat-2.5-preview-free",
+ "name": "LongCat 2.5 Preview Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "mimo-v2.5": {
+ "id": "mimo-v2.5",
+ "name": "MiMo V2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.0028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "mimo-v2.5-pro": {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo V2.5 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.435,
+ "output": 0.87,
+ "cacheRead": 0.003625,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "mimo-v2.6-flash": {
+ "id": "mimo-v2.6-flash",
+ "name": "MiMo-V2.6-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.0028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "mimo-v2.6-pro": {
+ "id": "mimo-v2.6-pro",
+ "name": "MiMo-V2.6-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.435,
+ "output": 0.87,
+ "cacheRead": 0.003625,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "minimax-m2.7": {
+ "id": "minimax-m2.7",
+ "name": "MiniMax-M2.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.06,
+ "cacheWrite": 0.375
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "space-bunny-free": {
+ "id": "space-bunny-free",
+ "name": "Space Bunny Free",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 524288,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsStrictMode": true,
+ "maxTokensField": "max_tokens"
+ }
+ },
+ "gpt-5.6-luna": {
+ "id": "gpt-5.6-luna",
+ "name": "GPT-5.6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0.25
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "gpt-6-luna": {
+ "id": "gpt-6-luna",
+ "name": "GPT-6 Luna",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession",
+ "supportsMidConvoSystemMessages": true,
+ "supportsAdditionalTools": true
+ }
+ },
+ "grok-4.6": {
+ "id": "grok-4.6",
+ "name": "Grok 4.6",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 500000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ },
+ "grok-4.7": {
+ "id": "grok-4.7",
+ "name": "Grok 4.7",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 500000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ },
+ "muse-spark-1.2-contributor": {
+ "id": "muse-spark-1.2-contributor",
+ "name": "Muse Spark 1.2 Contributor",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.2,
+ "cacheRead": 0.002,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ },
+ "muse-spark-1.3-contributor": {
+ "id": "muse-spark-1.3-contributor",
+ "name": "Muse Spark 1.3 Contributor",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.2,
+ "cacheRead": 0.002,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "sessionAffinityFormat": "openai-nosession"
+ }
+ }
+ },
+ "openrouter": {
+ "~anthropic/claude-fable-latest": {
+ "id": "~anthropic/claude-fable-latest",
+ "name": "Anthropic: Claude Fable Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 0.25,
+ "cacheWrite": 12.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~anthropic/claude-haiku-latest": {
+ "id": "~anthropic/claude-haiku-latest",
+ "name": "Anthropic: Claude Haiku Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 5,
+ "cacheRead": 0.1,
+ "cacheWrite": 1.25
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~anthropic/claude-opus-latest": {
+ "id": "~anthropic/claude-opus-latest",
+ "name": "Anthropic: Claude Opus Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 4,
+ "output": 20,
+ "cacheRead": 0.2,
+ "cacheWrite": 5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~anthropic/claude-sonnet-latest": {
+ "id": "~anthropic/claude-sonnet-latest",
+ "name": "Anthropic: Claude Sonnet Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~deepseek/deepseek-flash-latest": {
+ "id": "~deepseek/deepseek-flash-latest",
+ "name": "DeepSeek: DeepSeek Flash Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.003,
+ "output": 2.4,
+ "cacheRead": 0.003,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~deepseek/deepseek-pro-latest": {
+ "id": "~deepseek/deepseek-pro-latest",
+ "name": "DeepSeek: DeepSeek Pro Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 393216,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1901,
+ "output": 4.2,
+ "cacheRead": 0.19,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~deepseek/deepseek-v4-flash-latest": {
+ "id": "~deepseek/deepseek-v4-flash-latest",
+ "name": "DeepSeek: DeepSeek V4 Flash Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0152,
+ "output": 1.28,
+ "cacheRead": 0.0152,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "~google/gemini-flash-latest": {
+ "id": "~google/gemini-flash-latest",
+ "name": "Google: Gemini Flash Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 3.75,
+ "cacheRead": 0.075,
+ "cacheWrite": 0.041667
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~google/gemini-pro-latest": {
+ "id": "~google/gemini-pro-latest",
+ "name": "Google: Gemini Pro Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 0.375
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~moonshotai/kimi-latest": {
+ "id": "~moonshotai/kimi-latest",
+ "name": "MoonshotAI: Kimi Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.66,
+ "output": 13,
+ "cacheRead": 0.45,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~openai/gpt-astra-latest": {
+ "id": "~openai/gpt-astra-latest",
+ "name": "OpenAI: GPT Astra Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~openai/gpt-luna-latest": {
+ "id": "~openai/gpt-luna-latest",
+ "name": "OpenAI: GPT Luna Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~openai/gpt-mini-latest": {
+ "id": "~openai/gpt-mini-latest",
+ "name": "OpenAI: GPT Mini Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 4.5,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~openai/gpt-sol-latest": {
+ "id": "~openai/gpt-sol-latest",
+ "name": "OpenAI: GPT Sol Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.1,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~openai/gpt-terra-latest": {
+ "id": "~openai/gpt-terra-latest",
+ "name": "OpenAI: GPT Terra Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~x-ai/grok-latest": {
+ "id": "~x-ai/grok-latest",
+ "name": "xAI: Grok Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 450000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~z-ai/glm-flash-latest": {
+ "id": "~z-ai/glm-flash-latest",
+ "name": "Z.ai: GLM Flash Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0352,
+ "output": 0.5,
+ "cacheRead": 0.0232,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "~z-ai/glm-latest": {
+ "id": "~z-ai/glm-latest",
+ "name": "Z.ai: GLM Latest",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.03,
+ "output": 12,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "aion-labs/aion-2.0": {
+ "id": "aion-labs/aion-2.0",
+ "name": "AionLabs: Aion-2.0",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.8,
+ "output": 1.6,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "aion-labs/aion-3.0": {
+ "id": "aion-labs/aion-3.0",
+ "name": "AionLabs: Aion-3.0",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 6,
+ "cacheRead": 0.75,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "aion-labs/aion-3.0-mini": {
+ "id": "aion-labs/aion-3.0-mini",
+ "name": "AionLabs: Aion-3.0-Mini",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.7,
+ "output": 1.4,
+ "cacheRead": 0.18,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "aion-labs/aion-3.5": {
+ "id": "aion-labs/aion-3.5",
+ "name": "AionLabs: Aion 3.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 6,
+ "cacheRead": 0.75,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "aion-labs/aion-3.5-mini": {
+ "id": "aion-labs/aion-3.5-mini",
+ "name": "AionLabs: Aion 3.5 Mini",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.7,
+ "output": 1.4,
+ "cacheRead": 0.18,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "amazon/nova-2-lite-v1": {
+ "id": "amazon/nova-2-lite-v1",
+ "name": "Amazon: Nova 2 Lite",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65535,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 2.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "amazon/nova-lite-v1": {
+ "id": "amazon/nova-lite-v1",
+ "name": "Amazon: Nova Lite 1.0",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 300000,
+ "maxTokens": 5120,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.24,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "amazon/nova-micro-v1": {
+ "id": "amazon/nova-micro-v1",
+ "name": "Amazon: Nova Micro 1.0",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 5120,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.035,
+ "output": 0.14,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "amazon/nova-premier-v1": {
+ "id": "amazon/nova-premier-v1",
+ "name": "Amazon: Nova Premier 1.0",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 32000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 12.5,
+ "cacheRead": 0.625,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "amazon/nova-pro-v1": {
+ "id": "amazon/nova-pro-v1",
+ "name": "Amazon: Nova Pro 1.0",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 300000,
+ "maxTokens": 5120,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.8,
+ "output": 3.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-fable-5:batch": {
+ "id": "anthropic/claude-fable-5:batch",
+ "name": "Anthropic: Claude Fable 5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 25,
+ "cacheRead": 0.5,
+ "cacheWrite": 6.25
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-fable-5.1:batch": {
+ "id": "anthropic/claude-fable-5.1:batch",
+ "name": "Anthropic: Claude Fable 5.1 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 25,
+ "cacheRead": 0.125,
+ "cacheWrite": 6.25
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-haiku-4.5:batch": {
+ "id": "anthropic/claude-haiku-4.5:batch",
+ "name": "Anthropic: Claude Haiku 4.5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 2.5,
+ "cacheRead": 0.05,
+ "cacheWrite": 0.625
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-opus-4.1:batch": {
+ "id": "anthropic/claude-opus-4.1:batch",
+ "name": "Anthropic: Claude Opus 4.1 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 32000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 7.5,
+ "output": 37.5,
+ "cacheRead": 0.75,
+ "cacheWrite": 9.375
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-opus-4.5:batch": {
+ "id": "anthropic/claude-opus-4.5:batch",
+ "name": "Anthropic: Claude Opus 4.5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 12.5,
+ "cacheRead": 0.25,
+ "cacheWrite": 3.125
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-opus-4.6:batch": {
+ "id": "anthropic/claude-opus-4.6:batch",
+ "name": "Anthropic: Claude Opus 4.6 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 12.5,
+ "cacheRead": 0.25,
+ "cacheWrite": 3.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-opus-4.7:batch": {
+ "id": "anthropic/claude-opus-4.7:batch",
+ "name": "Anthropic: Claude Opus 4.7 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 12.5,
+ "cacheRead": 0.25,
+ "cacheWrite": 3.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-opus-4.8:batch": {
+ "id": "anthropic/claude-opus-4.8:batch",
+ "name": "Anthropic: Claude Opus 4.8 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 12.5,
+ "cacheRead": 0.25,
+ "cacheWrite": 3.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-opus-5:batch": {
+ "id": "anthropic/claude-opus-5:batch",
+ "name": "Anthropic: Claude Opus 5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 12.5,
+ "cacheRead": 0.25,
+ "cacheWrite": 3.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-opus-5.5:batch": {
+ "id": "anthropic/claude-opus-5.5:batch",
+ "name": "Anthropic: Claude Opus 5.5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.1,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-sonnet-4.5:batch": {
+ "id": "anthropic/claude-sonnet-4.5:batch",
+ "name": "Anthropic: Claude Sonnet 4.5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.5,
+ "output": 7.5,
+ "cacheRead": 0.15,
+ "cacheWrite": 1.875
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-sonnet-4.6:batch": {
+ "id": "anthropic/claude-sonnet-4.6:batch",
+ "name": "Anthropic: Claude Sonnet 4.6 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.5,
+ "output": 7.5,
+ "cacheRead": 0.15,
+ "cacheWrite": 1.875
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-sonnet-5:batch": {
+ "id": "anthropic/claude-sonnet-5:batch",
+ "name": "Anthropic: Claude Sonnet 5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 5,
+ "cacheRead": 0.1,
+ "cacheWrite": 1.25
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "anthropic/claude-sonnet-5.5:batch": {
+ "id": "anthropic/claude-sonnet-5.5:batch",
+ "name": "Anthropic: Claude Sonnet 5.5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 5,
+ "cacheRead": 0.1,
+ "cacheWrite": 1.25
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "cacheControlFormat": "anthropic",
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "apodex/apodex-1.1-mini:free": {
+ "id": "apodex/apodex-1.1-mini:free",
+ "name": "Apodex: Apodex 1.1 Mini (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "arcee-ai/trinity-large-thinking": {
+ "id": "arcee-ai/trinity-large-thinking",
+ "name": "Arcee AI: Trinity Large Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 80000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 0.8,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "auto": {
+ "id": "auto",
+ "name": "Auto",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 2000000,
+ "maxTokens": 30000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "bytedance-seed/seed-1.6": {
+ "id": "bytedance-seed/seed-1.6",
+ "name": "ByteDance Seed: Seed 1.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "bytedance-seed/seed-1.6-flash": {
+ "id": "bytedance-seed/seed-1.6-flash",
+ "name": "ByteDance Seed: Seed 1.6 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "bytedance-seed/seed-2-1-turbo": {
+ "id": "bytedance-seed/seed-2-1-turbo",
+ "name": "ByteDance Seed: Seed 2.1 Turbo",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 2.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "bytedance-seed/seed-2.0-code": {
+ "id": "bytedance-seed/seed-2.0-code",
+ "name": "ByteDance Seed: Seed-2.0-Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "bytedance-seed/seed-2.0-lite": {
+ "id": "bytedance-seed/seed-2.0-lite",
+ "name": "ByteDance Seed: Seed-2.0-Lite",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "bytedance-seed/seed-2.0-mini": {
+ "id": "bytedance-seed/seed-2.0-mini",
+ "name": "ByteDance Seed: Seed-2.0-Mini",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "cohere/command-a-plus": {
+ "id": "cohere/command-a-plus",
+ "name": "Cohere: Command A+",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 192000,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.5,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "cohere/command-r-08-2024": {
+ "id": "cohere/command-r-08-2024",
+ "name": "Cohere: Command R (08-2024)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 4000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "cohere/command-r-plus-08-2024": {
+ "id": "cohere/command-r-plus-08-2024",
+ "name": "Cohere: Command R+ (08-2024)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 4000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 10,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "cohere/north-mini-code:free": {
+ "id": "cohere/north-mini-code:free",
+ "name": "Cohere: North Mini Code (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 64000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-chat": {
+ "id": "deepseek/deepseek-chat",
+ "name": "DeepSeek: DeepSeek V3",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2574,
+ "output": 1.0287,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-chat-v3-0324": {
+ "id": "deepseek/deepseek-chat-v3-0324",
+ "name": "DeepSeek: DeepSeek V3 0324",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 115200,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.29,
+ "output": 1.14,
+ "cacheRead": 0.11,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-chat-v3.1": {
+ "id": "deepseek/deepseek-chat-v3.1",
+ "name": "DeepSeek: DeepSeek V3.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 163840,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 0.95,
+ "cacheRead": 0.13,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-r1": {
+ "id": "deepseek/deepseek-r1",
+ "name": "DeepSeek: R1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 64000,
+ "maxTokens": 16000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.7,
+ "output": 2.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-r1-0528": {
+ "id": "deepseek/deepseek-r1-0528",
+ "name": "DeepSeek: R1 0528",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 163840,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 2.15,
+ "cacheRead": 0.35,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-v3.1-terminus": {
+ "id": "deepseek/deepseek-v3.1-terminus",
+ "name": "DeepSeek: DeepSeek V3.1 Terminus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 163840,
+ "maxTokens": 147456,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.27,
+ "output": 1,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-v3.2": {
+ "id": "deepseek/deepseek-v3.2",
+ "name": "DeepSeek: DeepSeek V3.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.28,
+ "output": 0.42,
+ "cacheRead": 0.028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-v3.2-exp": {
+ "id": "deepseek/deepseek-v3.2-exp",
+ "name": "DeepSeek: DeepSeek V3.2 Exp",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 163840,
+ "maxTokens": 147456,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.27,
+ "output": 0.41,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "deepseek/deepseek-v4-flash": {
+ "id": "deepseek/deepseek-v4-flash",
+ "name": "DeepSeek: DeepSeek V4 Flash 0423",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.03,
+ "output": 1.28,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek/deepseek-v4-flash-0731": {
+ "id": "deepseek/deepseek-v4-flash-0731",
+ "name": "DeepSeek: DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0152,
+ "output": 1.28,
+ "cacheRead": 0.0152,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek/deepseek-v4-flash-vision-exp": {
+ "id": "deepseek/deepseek-v4-flash-vision-exp",
+ "name": "DeepSeek: DeepSeek V4 Flash Vision Exp",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2156,
+ "output": 0.6468,
+ "cacheRead": 0.00686,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek/deepseek-v4-pro": {
+ "id": "deepseek/deepseek-v4-pro",
+ "name": "DeepSeek: DeepSeek V4 Pro 0423",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1024000,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2088,
+ "output": 0.4176,
+ "cacheRead": 0.0174,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek/deepseek-v4-pro-0813": {
+ "id": "deepseek/deepseek-v4-pro-0813",
+ "name": "DeepSeek: DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.45,
+ "output": 5,
+ "cacheRead": 0.4,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek/deepseek-v4.1-flash": {
+ "id": "deepseek/deepseek-v4.1-flash",
+ "name": "DeepSeek: DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.006,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "deepseek/deepseek-v4.1-flash:batch": {
+ "id": "deepseek/deepseek-v4.1-flash:batch",
+ "name": "DeepSeek: DeepSeek V4.1 Flash (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.112,
+ "output": 0.336,
+ "cacheRead": 0.00336,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "dots-studio/dots-3-note-preview:free": {
+ "id": "dots-studio/dots-3-note-preview:free",
+ "name": "Dots Studio: Dots3-Note Preview (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 512000,
+ "maxTokens": 460800,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "fireworks/ember-1": {
+ "id": "fireworks/ember-1",
+ "name": "Fireworks: Ember-1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-2.5-flash": {
+ "id": "google/gemini-2.5-flash",
+ "name": "Google: Gemini 2.5 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65535,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 2.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0.083333
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-2.5-flash-lite": {
+ "id": "google/gemini-2.5-flash-lite",
+ "name": "Google: Gemini 2.5 Flash Lite",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65535,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.4,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.083333
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-2.5-flash-lite:batch": {
+ "id": "google/gemini-2.5-flash-lite:batch",
+ "name": "Google: Gemini 2.5 Flash Lite (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65535,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.2,
+ "cacheRead": 0.01,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-2.5-flash:batch": {
+ "id": "google/gemini-2.5-flash:batch",
+ "name": "Google: Gemini 2.5 Flash (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65535,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 1.25,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-2.5-pro": {
+ "id": "google/gemini-2.5-pro",
+ "name": "Google: Gemini 2.5 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0.375
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-2.5-pro-preview": {
+ "id": "google/gemini-2.5-pro-preview",
+ "name": "Google: Gemini 2.5 Pro Preview 06-05",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0.375
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-2.5-pro:batch": {
+ "id": "google/gemini-2.5-pro:batch",
+ "name": "Google: Gemini 2.5 Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.625,
+ "output": 5,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3-flash-preview": {
+ "id": "google/gemini-3-flash-preview",
+ "name": "Google: Gemini 3 Flash Preview",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 3,
+ "cacheRead": 0.05,
+ "cacheWrite": 0.083333
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3-flash-preview:batch": {
+ "id": "google/gemini-3-flash-preview:batch",
+ "name": "Google: Gemini 3 Flash Preview (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 1.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3-pro-image": {
+ "id": "google/gemini-3-pro-image",
+ "name": "Google: Nano Banana Pro (Gemini 3 Pro Image)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 65536,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 0.375
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.1-flash-lite": {
+ "id": "google/gemini-3.1-flash-lite",
+ "name": "Google: Gemini 3.1 Flash Lite",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 1.5,
+ "cacheRead": 0.025,
+ "cacheWrite": 0.083333
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.1-flash-lite-preview": {
+ "id": "google/gemini-3.1-flash-lite-preview",
+ "name": "Google: Gemini 3.1 Flash Lite Preview",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 1.5,
+ "cacheRead": 0.025,
+ "cacheWrite": 0.083333
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.1-flash-lite:batch": {
+ "id": "google/gemini-3.1-flash-lite:batch",
+ "name": "Google: Gemini 3.1 Flash Lite (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.125,
+ "output": 0.75,
+ "cacheRead": 0.0125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.1-pro-preview": {
+ "id": "google/gemini-3.1-pro-preview",
+ "name": "Google: Gemini 3.1 Pro Preview",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 0.375
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.1-pro-preview-customtools": {
+ "id": "google/gemini-3.1-pro-preview-customtools",
+ "name": "Google: Gemini 3.1 Pro Preview Custom Tools",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 0.375
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.1-pro-preview:batch": {
+ "id": "google/gemini-3.1-pro-preview:batch",
+ "name": "Google: Gemini 3.1 Pro Preview (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 6,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.5-flash": {
+ "id": "google/gemini-3.5-flash",
+ "name": "Google: Gemini 3.5 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.5,
+ "output": 9,
+ "cacheRead": 0.15,
+ "cacheWrite": 0.083333
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.5-flash-lite": {
+ "id": "google/gemini-3.5-flash-lite",
+ "name": "Google: Gemini 3.5 Flash Lite",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 2.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0.083333
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.5-flash-lite:batch": {
+ "id": "google/gemini-3.5-flash-lite:batch",
+ "name": "Google: Gemini 3.5 Flash Lite (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 1.25,
+ "cacheRead": 0.015,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.5-flash:batch": {
+ "id": "google/gemini-3.5-flash:batch",
+ "name": "Google: Gemini 3.5 Flash (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 4.5,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.6-flash": {
+ "id": "google/gemini-3.6-flash",
+ "name": "Google: Gemini 3.6 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 3.75,
+ "cacheRead": 0.075,
+ "cacheWrite": 0.041667
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.6-flash:batch": {
+ "id": "google/gemini-3.6-flash:batch",
+ "name": "Google: Gemini 3.6 Flash (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.375,
+ "output": 1.875,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0.041667
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.7-flash": {
+ "id": "google/gemini-3.7-flash",
+ "name": "Google: Gemini 3.7 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 3.75,
+ "cacheRead": 0.075,
+ "cacheWrite": 0.041667
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.7-flash:batch": {
+ "id": "google/gemini-3.7-flash:batch",
+ "name": "Google: Gemini 3.7 Flash (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.375,
+ "output": 1.875,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0.041667
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.8-flash": {
+ "id": "google/gemini-3.8-flash",
+ "name": "Google: Gemini 3.8 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 3.75,
+ "cacheRead": 0.075,
+ "cacheWrite": 0.041667
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemini-3.8-flash:batch": {
+ "id": "google/gemini-3.8-flash:batch",
+ "name": "Google: Gemini 3.8 Flash (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.375,
+ "output": 1.875,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0.041667
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemma-3-12b-it": {
+ "id": "google/gemma-3-12b-it",
+ "name": "Google: Gemma 3 12B",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemma-3-27b-it": {
+ "id": "google/gemma-3-27b-it",
+ "name": "Google: Gemma 3 27B",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.08,
+ "output": 0.45,
+ "cacheRead": 0.04,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemma-4-26b-a4b-it": {
+ "id": "google/gemma-4-26b-a4b-it",
+ "name": "Google: Gemma 4 26B A4B ",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.09,
+ "output": 0.3,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemma-4-26b-a4b-it:free": {
+ "id": "google/gemma-4-26b-a4b-it:free",
+ "name": "Google: Gemma 4 26B A4B (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemma-4-31b-it": {
+ "id": "google/gemma-4-31b-it",
+ "name": "Google: Gemma 4 31B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.09,
+ "output": 0.34,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "google/gemma-4-31b-it:free": {
+ "id": "google/gemma-4-31b-it:free",
+ "name": "Google: Gemma 4 31B (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "ibm-granite/granite-4.2-8b": {
+ "id": "ibm-granite/granite-4.2-8b",
+ "name": "IBM: Granite 4.2 8B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.25,
+ "cacheRead": 0.015,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "inception/mercury-2": {
+ "id": "inception/mercury-2",
+ "name": "Inception: Mercury 2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 50000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 0.75,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "inception/mercury-2.5": {
+ "id": "inception/mercury-2.5",
+ "name": "Inception: Mercury 2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 260000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.04,
+ "output": 0.15,
+ "cacheRead": 0.004,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "inclusionai/ling-3.0-flash": {
+ "id": "inclusionai/ling-3.0-flash",
+ "name": "inclusionAI: Ling 3.0 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.021,
+ "output": 0.063,
+ "cacheRead": 0.0042,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "inclusionai/ling-3.0-flash-fin": {
+ "id": "inclusionai/ling-3.0-flash-fin",
+ "name": "inclusionAI: Ling 3.0 Flash Fin",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.042,
+ "output": 0.1232,
+ "cacheRead": 0.0084,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "inclusionai/ling-3.0-flash-sante:free": {
+ "id": "inclusionai/ling-3.0-flash-sante:free",
+ "name": "inclusionAI: Ling 3.0 Flash Sante (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "inclusionai/ling-3.0-flash-vl": {
+ "id": "inclusionai/ling-3.0-flash-vl",
+ "name": "inclusionAI: Ling 3.0 Flash VL",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.021,
+ "output": 0.0616,
+ "cacheRead": 0.0042,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "inclusionai/ling-3.1-flash": {
+ "id": "inclusionai/ling-3.1-flash",
+ "name": "inclusionAI: Ling 3.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "kwaipilot/kat-coder-pro-v2.5": {
+ "id": "kwaipilot/kat-coder-pro-v2.5",
+ "name": "Kwaipilot: KAT-Coder-Pro V2.5",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.74,
+ "output": 2.96,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "liquid/lfm-2.5-2.6b:free": {
+ "id": "liquid/lfm-2.5-2.6b:free",
+ "name": "LiquidAI: LFM2.5-2.6B (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 65536,
+ "maxTokens": 8192,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meituan/longcat-2.0": {
+ "id": "meituan/longcat-2.0",
+ "name": "Meituan: LongCat 2.0",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048756,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.006,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta-llama/llama-3.1-70b-instruct": {
+ "id": "meta-llama/llama-3.1-70b-instruct",
+ "name": "Meta: Llama 3.1 70B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta-llama/llama-3.1-8b-instruct": {
+ "id": "meta-llama/llama-3.1-8b-instruct",
+ "name": "Meta: Llama 3.1 8B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.08,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta-llama/llama-3.3-70b-instruct": {
+ "id": "meta-llama/llama-3.3-70b-instruct",
+ "name": "Meta: Llama 3.3 70B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.32,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta-llama/llama-4-maverick": {
+ "id": "meta-llama/llama-4-maverick",
+ "name": "Meta: Llama 4 Maverick",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1875,
+ "output": 0.6525,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta-llama/llama-4-scout": {
+ "id": "meta-llama/llama-4-scout",
+ "name": "Meta: Llama 4 Scout",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 327680,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta/muse-glimmer-30b": {
+ "id": "meta/muse-glimmer-30b",
+ "name": "Meta: Muse Glimmer 30B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.35,
+ "output": 1.5,
+ "cacheRead": 0.04,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta/muse-spark-1.1": {
+ "id": "meta/muse-spark-1.1",
+ "name": "Meta: Muse Spark 1.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 4.25,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta/muse-spark-1.2": {
+ "id": "meta/muse-spark-1.2",
+ "name": "Meta: Muse Spark 1.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 4.25,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta/muse-spark-1.2-contributor": {
+ "id": "meta/muse-spark-1.2-contributor",
+ "name": "Meta: Muse Spark 1.2 Contributor",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.2,
+ "cacheRead": 0.002,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta/muse-spark-1.3": {
+ "id": "meta/muse-spark-1.3",
+ "name": "Meta: Muse Spark 1.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 4.25,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "meta/muse-spark-1.3-contributor": {
+ "id": "meta/muse-spark-1.3-contributor",
+ "name": "Meta: Muse Spark 1.3 Contributor",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 943718,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.2,
+ "cacheRead": 0.002,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "minimax/minimax-m1": {
+ "id": "minimax/minimax-m1",
+ "name": "MiniMax: MiniMax M1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 40000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.55,
+ "output": 2.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "minimax/minimax-m2": {
+ "id": "minimax/minimax-m2",
+ "name": "MiniMax: MiniMax M2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 196608,
+ "maxTokens": 176947,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "minimax/minimax-m2.1": {
+ "id": "minimax/minimax-m2.1",
+ "name": "MiniMax: MiniMax M2.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "minimax/minimax-m2.5": {
+ "id": "minimax/minimax-m2.5",
+ "name": "MiniMax: MiniMax M2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.27,
+ "output": 1.08,
+ "cacheRead": 0.027,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "minimax/minimax-m2.7": {
+ "id": "minimax/minimax-m2.7",
+ "name": "MiniMax: MiniMax M2.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 196608,
+ "maxTokens": 176947,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.21,
+ "output": 0.84,
+ "cacheRead": 0.042,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "minimax/minimax-m3": {
+ "id": "minimax/minimax-m3",
+ "name": "MiniMax: MiniMax M3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 512000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/codestral-2508": {
+ "id": "mistralai/codestral-2508",
+ "name": "Mistral: Codestral 2508",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 204800,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 0.9,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/codestral-2508:batch": {
+ "id": "mistralai/codestral-2508:batch",
+ "name": "Mistral: Codestral 2508 (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 204800,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.45,
+ "cacheRead": 0.015,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/devstral-2512": {
+ "id": "mistralai/devstral-2512",
+ "name": "Mistral: Devstral 2 2512",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 2,
+ "cacheRead": 0.04,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/ministral-14b-2512": {
+ "id": "mistralai/ministral-14b-2512",
+ "name": "Mistral: Ministral 3 14B 2512",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 0.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/ministral-3b-2512": {
+ "id": "mistralai/ministral-3b-2512",
+ "name": "Mistral: Ministral 3 3B 2512",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 104857,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.1,
+ "cacheRead": 0.01,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/ministral-8b-2512": {
+ "id": "mistralai/ministral-8b-2512",
+ "name": "Mistral: Ministral 3 8B 2512",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.15,
+ "cacheRead": 0.015,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/ministral-8b-2512:batch": {
+ "id": "mistralai/ministral-8b-2512:batch",
+ "name": "Mistral: Ministral 3 8B 2512 (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.075,
+ "cacheRead": 0.0075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-large": {
+ "id": "mistralai/mistral-large",
+ "name": "Mistral Large",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 102400,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-large-2407": {
+ "id": "mistralai/mistral-large-2407",
+ "name": "Mistral Large 2407",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 104857,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-large-2512": {
+ "id": "mistralai/mistral-large-2512",
+ "name": "Mistral: Mistral Large 3 2512",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 1.5,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-large-2512:batch": {
+ "id": "mistralai/mistral-large-2512:batch",
+ "name": "Mistral: Mistral Large 3 2512 (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 0.75,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-medium-3": {
+ "id": "mistralai/mistral-medium-3",
+ "name": "Mistral: Mistral Medium 3",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 104857,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 2,
+ "cacheRead": 0.04,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-medium-3-5": {
+ "id": "mistralai/mistral-medium-3-5",
+ "name": "Mistral: Mistral Medium 3.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.5,
+ "output": 7.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-medium-3-5:batch": {
+ "id": "mistralai/mistral-medium-3-5:batch",
+ "name": "Mistral: Mistral Medium 3.5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 3.75,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-medium-3.1": {
+ "id": "mistralai/mistral-medium-3.1",
+ "name": "Mistral: Mistral Medium 3.1",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 104857,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 2,
+ "cacheRead": 0.04,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-medium-3.1:batch": {
+ "id": "mistralai/mistral-medium-3.1:batch",
+ "name": "Mistral: Mistral Medium 3.1 (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 104857,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-nemo": {
+ "id": "mistralai/mistral-nemo",
+ "name": "Mistral: Mistral Nemo",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.019,
+ "output": 0.03,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-saba": {
+ "id": "mistralai/mistral-saba",
+ "name": "Mistral: Saba",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 32768,
+ "maxTokens": 26214,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 0.6,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-small-2603": {
+ "id": "mistralai/mistral-small-2603",
+ "name": "Mistral: Mistral Small 4",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.015,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-small-2603:batch": {
+ "id": "mistralai/mistral-small-2603:batch",
+ "name": "Mistral: Mistral Small 4 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 209715,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.3,
+ "cacheRead": 0.0075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-small-3.1-24b-instruct": {
+ "id": "mistralai/mistral-small-3.1-24b-instruct",
+ "name": "Mistral: Mistral Small 3.1 24B",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 102400,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.351,
+ "output": 0.555,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mistral-small-3.2-24b-instruct": {
+ "id": "mistralai/mistral-small-3.2-24b-instruct",
+ "name": "Mistral: Mistral Small 3.2 24B",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.09375,
+ "output": 0.25,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/mixtral-8x22b-instruct": {
+ "id": "mistralai/mixtral-8x22b-instruct",
+ "name": "Mistral: Mixtral 8x22B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 65536,
+ "maxTokens": 52428,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "mistralai/voxtral-small-24b-2507": {
+ "id": "mistralai/voxtral-small-24b-2507",
+ "name": "Mistral: Voxtral Small 24B 2507",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 32768,
+ "maxTokens": 26214,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.3,
+ "cacheRead": 0.01,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "moonshotai/kimi-k2": {
+ "id": "moonshotai/kimi-k2",
+ "name": "MoonshotAI: Kimi K2 0711",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 98304,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.57,
+ "output": 2.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "moonshotai/kimi-k2-0905": {
+ "id": "moonshotai/kimi-k2-0905",
+ "name": "MoonshotAI: Kimi K2 0905",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 98304,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "moonshotai/kimi-k2-thinking": {
+ "id": "moonshotai/kimi-k2-thinking",
+ "name": "MoonshotAI: Kimi K2 Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "moonshotai/kimi-k2.5": {
+ "id": "moonshotai/kimi-k2.5",
+ "name": "MoonshotAI: Kimi K2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.41,
+ "output": 2.06,
+ "cacheRead": 0.07,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "moonshotai/kimi-k2.6": {
+ "id": "moonshotai/kimi-k2.6",
+ "name": "MoonshotAI: Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "requiresReasoningContentOnAssistantMessages": true
+ }
+ },
+ "moonshotai/kimi-k2.7-code": {
+ "id": "moonshotai/kimi-k2.7-code",
+ "name": "MoonshotAI: Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6712,
+ "output": 3.35,
+ "cacheRead": 0.18,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "moonshotai/kimi-k3": {
+ "id": "moonshotai/kimi-k3",
+ "name": "MoonshotAI: Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.67,
+ "output": 14,
+ "cacheRead": 0.22,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "moonshotai/kimi-k3:batch": {
+ "id": "moonshotai/kimi-k3:batch",
+ "name": "MoonshotAI: Kimi K3 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.28,
+ "output": 11.4,
+ "cacheRead": 0.228,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nex-agi/nex-n2.5-pro": {
+ "id": "nex-agi/nex-n2.5-pro",
+ "name": "Nex AGI: Nex-N2.5-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.25,
+ "cacheRead": 0.015,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nvidia/nemotron-3-nano-30b-a3b": {
+ "id": "nvidia/nemotron-3-nano-30b-a3b",
+ "name": "NVIDIA: Nemotron 3 Nano 30B A3B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.2,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free": {
+ "id": "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free",
+ "name": "NVIDIA: Nemotron 3 Nano Omni (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nvidia/nemotron-3-super-120b-a12b": {
+ "id": "nvidia/nemotron-3-super-120b-a12b",
+ "name": "NVIDIA: Nemotron 3 Super",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.08,
+ "output": 0.45,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nvidia/nemotron-3-super-120b-a12b:free": {
+ "id": "nvidia/nemotron-3-super-120b-a12b:free",
+ "name": "NVIDIA: Nemotron 3 Super (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nvidia/nemotron-3-ultra-550b-a55b": {
+ "id": "nvidia/nemotron-3-ultra-550b-a55b",
+ "name": "NVIDIA: Nemotron 3 Ultra",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 2.2,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nvidia/nemotron-3-ultra-550b-a55b:free": {
+ "id": "nvidia/nemotron-3-ultra-550b-a55b:free",
+ "name": "NVIDIA: Nemotron 3 Ultra (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nvidia/nemotron-3.5-lightning": {
+ "id": "nvidia/nemotron-3.5-lightning",
+ "name": "NVIDIA: Nemotron 3.5 Lightning",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.16,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "nvidia/nemotron-3.5-lightning:free": {
+ "id": "nvidia/nemotron-3.5-lightning:free",
+ "name": "NVIDIA: Nemotron 3.5 Lightning (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-3.5-turbo": {
+ "id": "openai/gpt-3.5-turbo",
+ "name": "OpenAI: GPT-3.5 Turbo",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 16385,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 1.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-3.5-turbo-0613": {
+ "id": "openai/gpt-3.5-turbo-0613",
+ "name": "OpenAI: GPT-3.5 Turbo (older v0613)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 4095,
+ "maxTokens": 3685,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-3.5-turbo-16k": {
+ "id": "openai/gpt-3.5-turbo-16k",
+ "name": "OpenAI: GPT-3.5 Turbo 16k",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 16385,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-3.5-turbo:batch": {
+ "id": "openai/gpt-3.5-turbo:batch",
+ "name": "OpenAI: GPT-3.5 Turbo (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 16385,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 0.75,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4": {
+ "id": "openai/gpt-4",
+ "name": "OpenAI: GPT-4",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 8191,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 30,
+ "output": 60,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4-turbo": {
+ "id": "openai/gpt-4-turbo",
+ "name": "OpenAI: GPT-4 Turbo",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 10,
+ "output": 30,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4-turbo:batch": {
+ "id": "openai/gpt-4-turbo:batch",
+ "name": "OpenAI: GPT-4 Turbo (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4.1": {
+ "id": "openai/gpt-4.1",
+ "name": "OpenAI: GPT-4.1",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 8,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4.1-mini": {
+ "id": "openai/gpt-4.1-mini",
+ "name": "OpenAI: GPT-4.1 Mini",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 1.6,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4.1-mini:batch": {
+ "id": "openai/gpt-4.1-mini:batch",
+ "name": "OpenAI: GPT-4.1 Mini (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 0.8,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4.1-nano": {
+ "id": "openai/gpt-4.1-nano",
+ "name": "OpenAI: GPT-4.1 Nano",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.4,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4.1-nano:batch": {
+ "id": "openai/gpt-4.1-nano:batch",
+ "name": "OpenAI: GPT-4.1 Nano (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.2,
+ "cacheRead": 0.0125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4.1:batch": {
+ "id": "openai/gpt-4.1:batch",
+ "name": "OpenAI: GPT-4.1 (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1047576,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 4,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4o": {
+ "id": "openai/gpt-4o",
+ "name": "OpenAI: GPT-4o",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 10,
+ "cacheRead": 1.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4o-2024-05-13": {
+ "id": "openai/gpt-4o-2024-05-13",
+ "name": "OpenAI: GPT-4o (2024-05-13)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 4096,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4o-2024-08-06": {
+ "id": "openai/gpt-4o-2024-08-06",
+ "name": "OpenAI: GPT-4o (2024-08-06)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 10,
+ "cacheRead": 1.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4o-2024-11-20": {
+ "id": "openai/gpt-4o-2024-11-20",
+ "name": "OpenAI: GPT-4o (2024-11-20)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 10,
+ "cacheRead": 1.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4o-mini": {
+ "id": "openai/gpt-4o-mini",
+ "name": "OpenAI: GPT-4o-mini",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4o-mini-2024-07-18": {
+ "id": "openai/gpt-4o-mini-2024-07-18",
+ "name": "OpenAI: GPT-4o-mini (2024-07-18)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4o-mini:batch": {
+ "id": "openai/gpt-4o-mini:batch",
+ "name": "OpenAI: GPT-4o-mini (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.3,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-4o:batch": {
+ "id": "openai/gpt-4o:batch",
+ "name": "OpenAI: GPT-4o (batch)",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 5,
+ "cacheRead": 0.625,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5": {
+ "id": "openai/gpt-5",
+ "name": "OpenAI: GPT-5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5-mini": {
+ "id": "openai/gpt-5-mini",
+ "name": "OpenAI: GPT-5 Mini",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5-mini:batch": {
+ "id": "openai/gpt-5-mini:batch",
+ "name": "OpenAI: GPT-5 Mini (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.125,
+ "output": 1,
+ "cacheRead": 0.0125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5-nano": {
+ "id": "openai/gpt-5-nano",
+ "name": "OpenAI: GPT-5 Nano",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.4,
+ "cacheRead": 0.005,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5-nano:batch": {
+ "id": "openai/gpt-5-nano:batch",
+ "name": "OpenAI: GPT-5 Nano (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.025,
+ "output": 0.2,
+ "cacheRead": 0.0025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5-pro": {
+ "id": "openai/gpt-5-pro",
+ "name": "OpenAI: GPT-5 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 15,
+ "output": 120,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5-pro:batch": {
+ "id": "openai/gpt-5-pro:batch",
+ "name": "OpenAI: GPT-5 Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 7.5,
+ "output": 60,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5:batch": {
+ "id": "openai/gpt-5:batch",
+ "name": "OpenAI: GPT-5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.625,
+ "output": 5,
+ "cacheRead": 0.0625,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.1": {
+ "id": "openai/gpt-5.1",
+ "name": "OpenAI: GPT-5.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.1-codex": {
+ "id": "openai/gpt-5.1-codex",
+ "name": "OpenAI: GPT-5.1-Codex",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.13,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.1-codex-max": {
+ "id": "openai/gpt-5.1-codex-max",
+ "name": "OpenAI: GPT-5.1-Codex-Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 10,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.1-codex-mini": {
+ "id": "openai/gpt-5.1-codex-mini",
+ "name": "OpenAI: GPT-5.1-Codex-Mini",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.25,
+ "output": 2,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.1:batch": {
+ "id": "openai/gpt-5.1:batch",
+ "name": "OpenAI: GPT-5.1 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.625,
+ "output": 5,
+ "cacheRead": 0.0625,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.2": {
+ "id": "openai/gpt-5.2",
+ "name": "OpenAI: GPT-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.2-chat": {
+ "id": "openai/gpt-5.2-chat",
+ "name": "OpenAI: GPT-5.2 Chat",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 32000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "thinkingLevelMap": {
+ "xhigh": "xhigh"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.2-codex": {
+ "id": "openai/gpt-5.2-codex",
+ "name": "OpenAI: GPT-5.2-Codex",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.2-pro": {
+ "id": "openai/gpt-5.2-pro",
+ "name": "OpenAI: GPT-5.2 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 21,
+ "output": 168,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.2-pro:batch": {
+ "id": "openai/gpt-5.2-pro:batch",
+ "name": "OpenAI: GPT-5.2 Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 10.5,
+ "output": 84,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.2:batch": {
+ "id": "openai/gpt-5.2:batch",
+ "name": "OpenAI: GPT-5.2 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.875,
+ "output": 7,
+ "cacheRead": 0.0875,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.3-codex": {
+ "id": "openai/gpt-5.3-codex",
+ "name": "OpenAI: GPT-5.3-Codex",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.75,
+ "output": 14,
+ "cacheRead": 0.175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.4": {
+ "id": "openai/gpt-5.4",
+ "name": "OpenAI: GPT-5.4",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 15,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-5.4-mini": {
+ "id": "openai/gpt-5.4-mini",
+ "name": "OpenAI: GPT-5.4 Mini",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.75,
+ "output": 4.5,
+ "cacheRead": 0.075,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-5.4-mini:batch": {
+ "id": "openai/gpt-5.4-mini:batch",
+ "name": "OpenAI: GPT-5.4 Mini (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.375,
+ "output": 2.25,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.4-nano": {
+ "id": "openai/gpt-5.4-nano",
+ "name": "OpenAI: GPT-5.4 Nano",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.25,
+ "cacheRead": 0.02,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.4-nano:batch": {
+ "id": "openai/gpt-5.4-nano:batch",
+ "name": "OpenAI: GPT-5.4 Nano (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.625,
+ "cacheRead": 0.01,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.4-pro": {
+ "id": "openai/gpt-5.4-pro",
+ "name": "OpenAI: GPT-5.4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 30,
+ "output": 180,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-5.4-pro:batch": {
+ "id": "openai/gpt-5.4-pro:batch",
+ "name": "OpenAI: GPT-5.4 Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 15,
+ "output": 90,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.4:batch": {
+ "id": "openai/gpt-5.4:batch",
+ "name": "OpenAI: GPT-5.4 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 7.5,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.5": {
+ "id": "openai/gpt-5.5",
+ "name": "OpenAI: GPT-5.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 30,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-5.5-pro": {
+ "id": "openai/gpt-5.5-pro",
+ "name": "OpenAI: GPT-5.5 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 30,
+ "output": 180,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.5-pro:batch": {
+ "id": "openai/gpt-5.5-pro:batch",
+ "name": "OpenAI: GPT-5.5 Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 15,
+ "output": 90,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.5:batch": {
+ "id": "openai/gpt-5.5:batch",
+ "name": "OpenAI: GPT-5.5 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 15,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-luna": {
+ "id": "openai/gpt-5.6-luna",
+ "name": "OpenAI: GPT-5.6 Luna",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0.25
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-5.6-luna-pro": {
+ "id": "openai/gpt-5.6-luna-pro",
+ "name": "OpenAI: GPT-5.6 Luna Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.2,
+ "cacheRead": 0.02,
+ "cacheWrite": 0.25
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-luna-pro:batch": {
+ "id": "openai/gpt-5.6-luna-pro:batch",
+ "name": "OpenAI: GPT-5.6 Luna Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.6,
+ "cacheRead": 0.01,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-luna:batch": {
+ "id": "openai/gpt-5.6-luna:batch",
+ "name": "OpenAI: GPT-5.6 Luna (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.6,
+ "cacheRead": 0.01,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-sol": {
+ "id": "openai/gpt-5.6-sol",
+ "name": "OpenAI: GPT-5.6 Sol",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-5.6-sol-pro": {
+ "id": "openai/gpt-5.6-sol-pro",
+ "name": "OpenAI: GPT-5.6 Sol Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-sol-pro:batch": {
+ "id": "openai/gpt-5.6-sol-pro:batch",
+ "name": "OpenAI: GPT-5.6 Sol Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 5,
+ "cacheRead": 0.1,
+ "cacheWrite": 1.25
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-sol:batch": {
+ "id": "openai/gpt-5.6-sol:batch",
+ "name": "OpenAI: GPT-5.6 Sol (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 5,
+ "cacheRead": 0.1,
+ "cacheWrite": 1.25
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-terra": {
+ "id": "openai/gpt-5.6-terra",
+ "name": "OpenAI: GPT-5.6 Terra",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-5.6-terra-pro": {
+ "id": "openai/gpt-5.6-terra-pro",
+ "name": "OpenAI: GPT-5.6 Terra Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 12,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-terra-pro:batch": {
+ "id": "openai/gpt-5.6-terra-pro:batch",
+ "name": "OpenAI: GPT-5.6 Terra Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 6,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-5.6-terra:batch": {
+ "id": "openai/gpt-5.6-terra:batch",
+ "name": "OpenAI: GPT-5.6 Terra (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 6,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-astra": {
+ "id": "openai/gpt-6-astra",
+ "name": "OpenAI: GPT-6 Astra",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-6-astra-pro": {
+ "id": "openai/gpt-6-astra-pro",
+ "name": "OpenAI: GPT-6 Astra Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 10,
+ "output": 50,
+ "cacheRead": 1,
+ "cacheWrite": 12.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-astra-pro:batch": {
+ "id": "openai/gpt-6-astra-pro:batch",
+ "name": "OpenAI: GPT-6 Astra Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 25,
+ "cacheRead": 0.5,
+ "cacheWrite": 6.25
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-astra:batch": {
+ "id": "openai/gpt-6-astra:batch",
+ "name": "OpenAI: GPT-6 Astra (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 25,
+ "cacheRead": 0.5,
+ "cacheWrite": 6.25
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-luna": {
+ "id": "openai/gpt-6-luna",
+ "name": "OpenAI: GPT-6 Luna",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-6-luna-pro": {
+ "id": "openai/gpt-6-luna-pro",
+ "name": "OpenAI: GPT-6 Luna Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.5,
+ "cacheRead": 0.01,
+ "cacheWrite": 0.125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-luna-pro:batch": {
+ "id": "openai/gpt-6-luna-pro:batch",
+ "name": "OpenAI: GPT-6 Luna Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.25,
+ "cacheRead": 0.005,
+ "cacheWrite": 0.0625
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-luna:batch": {
+ "id": "openai/gpt-6-luna:batch",
+ "name": "OpenAI: GPT-6 Luna (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.25,
+ "cacheRead": 0.005,
+ "cacheWrite": 0.0625
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-sol": {
+ "id": "openai/gpt-6-sol",
+ "name": "OpenAI: GPT-6 Sol",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-6-sol-pro": {
+ "id": "openai/gpt-6-sol-pro",
+ "name": "OpenAI: GPT-6 Sol Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.2,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-sol-pro:batch": {
+ "id": "openai/gpt-6-sol-pro:batch",
+ "name": "OpenAI: GPT-6 Sol Pro (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 5,
+ "cacheRead": 0.1,
+ "cacheWrite": 1.25
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6-sol:batch": {
+ "id": "openai/gpt-6-sol:batch",
+ "name": "OpenAI: GPT-6 Sol (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 5,
+ "cacheRead": 0.1,
+ "cacheWrite": 1.25
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-6.1-sol": {
+ "id": "openai/gpt-6.1-sol",
+ "name": "OpenAI: GPT-6.1 Sol",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.1,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true,
+ "supportsMidConvoSystemMessages": true
+ }
+ },
+ "openai/gpt-6.1-sol-pro": {
+ "id": "openai/gpt-6.1-sol-pro",
+ "name": "OpenAI: GPT-6.1 Sol Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1050000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 10,
+ "cacheRead": 0.1,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-audio": {
+ "id": "openai/gpt-audio",
+ "name": "OpenAI: GPT Audio",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 10,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-audio-mini": {
+ "id": "openai/gpt-audio-mini",
+ "name": "OpenAI: GPT Audio Mini",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-chat-latest": {
+ "id": "openai/gpt-chat-latest",
+ "name": "OpenAI: GPT Chat Latest",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 400000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 30,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-oss-120b": {
+ "id": "openai/gpt-oss-120b",
+ "name": "OpenAI: gpt-oss-120b",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.037,
+ "output": 0.17,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-oss-120b:batch": {
+ "id": "openai/gpt-oss-120b:batch",
+ "name": "OpenAI: gpt-oss-120b (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0296,
+ "output": 0.136,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-oss-20b": {
+ "id": "openai/gpt-oss-20b",
+ "name": "OpenAI: gpt-oss-20b",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.018,
+ "output": 0.09,
+ "cacheRead": 0.009,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-oss-20b:batch": {
+ "id": "openai/gpt-oss-20b:batch",
+ "name": "OpenAI: gpt-oss-20b (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.024,
+ "output": 0.112,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/gpt-oss-safeguard-20b": {
+ "id": "openai/gpt-oss-safeguard-20b",
+ "name": "OpenAI: gpt-oss-safeguard-20b",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.3,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o1": {
+ "id": "openai/o1",
+ "name": "OpenAI: o1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 15,
+ "output": 60,
+ "cacheRead": 7.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o3": {
+ "id": "openai/o3",
+ "name": "OpenAI: o3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 8,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o3-mini": {
+ "id": "openai/o3-mini",
+ "name": "OpenAI: o3 Mini",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.1,
+ "output": 4.4,
+ "cacheRead": 0.55,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o3-mini-high": {
+ "id": "openai/o3-mini-high",
+ "name": "OpenAI: o3 Mini High",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.1,
+ "output": 4.4,
+ "cacheRead": 0.55,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o3-mini:batch": {
+ "id": "openai/o3-mini:batch",
+ "name": "OpenAI: o3 Mini (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.55,
+ "output": 2.2,
+ "cacheRead": 0.275,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o3-pro": {
+ "id": "openai/o3-pro",
+ "name": "OpenAI: o3 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 20,
+ "output": 80,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o3:batch": {
+ "id": "openai/o3:batch",
+ "name": "OpenAI: o3 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 4,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o4-mini": {
+ "id": "openai/o4-mini",
+ "name": "OpenAI: o4 Mini",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.1,
+ "output": 4.4,
+ "cacheRead": 0.275,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o4-mini-high": {
+ "id": "openai/o4-mini-high",
+ "name": "OpenAI: o4 Mini High",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.1,
+ "output": 4.4,
+ "cacheRead": 0.275,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openai/o4-mini:batch": {
+ "id": "openai/o4-mini:batch",
+ "name": "OpenAI: o4 Mini (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 100000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.55,
+ "output": 2.2,
+ "cacheRead": 0.1375,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openrouter/auto": {
+ "id": "openrouter/auto",
+ "name": "Auto Router",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 2000000,
+ "maxTokens": 4096,
+ "pricingKnown": false,
+ "cost": {
+ "input": -1000000,
+ "output": -1000000,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openrouter/auto-beta": {
+ "id": "openrouter/auto-beta",
+ "name": "Auto Router (Beta)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 2000000,
+ "maxTokens": 4096,
+ "pricingKnown": false,
+ "cost": {
+ "input": -1000000,
+ "output": -1000000,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openrouter/free": {
+ "id": "openrouter/free",
+ "name": "Free Models Router",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 4096,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "openrouter/fusion": {
+ "id": "openrouter/fusion",
+ "name": "OpenRouter: Fusion",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 30000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "perceptron/perceptron-mk1.5": {
+ "id": "perceptron/perceptron-mk1.5",
+ "name": "Perceptron: Perceptron Mk1.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 36864,
+ "maxTokens": 8192,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 1.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "poolside/laguna-s-2.1": {
+ "id": "poolside/laguna-s-2.1",
+ "name": "Poolside: Laguna S 2.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.09,
+ "output": 0.18,
+ "cacheRead": 0.009,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "poolside/laguna-s-2.1:free": {
+ "id": "poolside/laguna-s-2.1:free",
+ "name": "Poolside: Laguna S 2.1 (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "poolside/laguna-xs-2.1": {
+ "id": "poolside/laguna-xs-2.1",
+ "name": "Poolside: Laguna XS 2.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.12,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "poolside/laguna-xs-2.1:free": {
+ "id": "poolside/laguna-xs-2.1:free",
+ "name": "Poolside: Laguna XS 2.1 (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "prism-ml/ternary-bonsai-2-27b": {
+ "id": "prism-ml/ternary-bonsai-2-27b",
+ "name": "PrismML: Ternary Bonsai 2 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.075,
+ "output": 0.5,
+ "cacheRead": 0.0375,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen-2.5-72b-instruct": {
+ "id": "qwen/qwen-2.5-72b-instruct",
+ "name": "Qwen2.5 72B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 32768,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.36,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen-2.5-7b-instruct": {
+ "id": "qwen/qwen-2.5-7b-instruct",
+ "name": "Qwen: Qwen2.5 7B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 32768,
+ "maxTokens": 29491,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen-plus": {
+ "id": "qwen/qwen-plus",
+ "name": "Qwen: Qwen-Plus",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.26,
+ "output": 0.78,
+ "cacheRead": 0.052,
+ "cacheWrite": 0.325
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen-plus-2025-07-28": {
+ "id": "qwen/qwen-plus-2025-07-28",
+ "name": "Qwen: Qwen Plus 0728",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.26,
+ "output": 0.78,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-14b": {
+ "id": "qwen/qwen3-14b",
+ "name": "Qwen: Qwen3 14B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 40960,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.12,
+ "output": 0.24,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-235b-a22b": {
+ "id": "qwen/qwen3-235b-a22b",
+ "name": "Qwen: Qwen3 235B A22B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 8192,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.455,
+ "output": 1.82,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-235b-a22b-2507": {
+ "id": "qwen/qwen3-235b-a22b-2507",
+ "name": "Qwen: Qwen3 235B A22B Instruct 2507",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0875,
+ "output": 0.35,
+ "cacheRead": 0.0175,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-235b-a22b-thinking-2507": {
+ "id": "qwen/qwen3-235b-a22b-thinking-2507",
+ "name": "Qwen: Qwen3 235B A22B Thinking 2507",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.23,
+ "output": 2.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-30b-a3b": {
+ "id": "qwen/qwen3-30b-a3b",
+ "name": "Qwen: Qwen3 30B A3B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 40960,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.12,
+ "output": 0.5,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-30b-a3b-instruct-2507": {
+ "id": "qwen/qwen3-30b-a3b-instruct-2507",
+ "name": "Qwen: Qwen3 30B A3B Instruct 2507",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 32000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.04815,
+ "output": 0.19305,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-30b-a3b-thinking-2507": {
+ "id": "qwen/qwen3-30b-a3b-thinking-2507",
+ "name": "Qwen: Qwen3 30B A3B Thinking 2507",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 81920,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 2.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-32b": {
+ "id": "qwen/qwen3-32b",
+ "name": "Qwen: Qwen3 32B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 40960,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.08,
+ "output": 0.28,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-8b": {
+ "id": "qwen/qwen3-8b",
+ "name": "Qwen: Qwen3 8B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 8192,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.117,
+ "output": 0.455,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-coder": {
+ "id": "qwen/qwen3-coder",
+ "name": "Qwen: Qwen3 Coder 480B A35B",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-coder-30b-a3b-instruct": {
+ "id": "qwen/qwen3-coder-30b-a3b-instruct",
+ "name": "Qwen: Qwen3 Coder 30B A3B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.07,
+ "output": 0.28,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-coder-flash": {
+ "id": "qwen/qwen3-coder-flash",
+ "name": "Qwen: Qwen3 Coder Flash",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.195,
+ "output": 0.975,
+ "cacheRead": 0.039,
+ "cacheWrite": 0.24375
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-coder-next": {
+ "id": "qwen/qwen3-coder-next",
+ "name": "Qwen: Qwen3 Coder Next",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.12,
+ "output": 0.8,
+ "cacheRead": 0.07,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-coder-plus": {
+ "id": "qwen/qwen3-coder-plus",
+ "name": "Qwen: Qwen3 Coder Plus",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.65,
+ "output": 3.25,
+ "cacheRead": 0.13,
+ "cacheWrite": 0.8125
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-max": {
+ "id": "qwen/qwen3-max",
+ "name": "Qwen: Qwen3 Max",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.78,
+ "output": 3.9,
+ "cacheRead": 0.156,
+ "cacheWrite": 0.975
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-max-thinking": {
+ "id": "qwen/qwen3-max-thinking",
+ "name": "Qwen: Qwen3 Max Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.78,
+ "output": 3.9,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-next-80b-a3b-instruct": {
+ "id": "qwen/qwen3-next-80b-a3b-instruct",
+ "name": "Qwen: Qwen3 Next 80B A3B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 1.1,
+ "cacheRead": 0.07,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-next-80b-a3b-thinking": {
+ "id": "qwen/qwen3-next-80b-a3b-thinking",
+ "name": "Qwen: Qwen3 Next 80B A3B Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 1.2,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-vl-235b-a22b-instruct": {
+ "id": "qwen/qwen3-vl-235b-a22b-instruct",
+ "name": "Qwen: Qwen3 VL 235B A22B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.21,
+ "output": 1.9,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-vl-235b-a22b-thinking": {
+ "id": "qwen/qwen3-vl-235b-a22b-thinking",
+ "name": "Qwen: Qwen3 VL 235B A22B Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.4,
+ "output": 4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-vl-30b-a3b-instruct": {
+ "id": "qwen/qwen3-vl-30b-a3b-instruct",
+ "name": "Qwen: Qwen3 VL 30B A3B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-vl-30b-a3b-thinking": {
+ "id": "qwen/qwen3-vl-30b-a3b-thinking",
+ "name": "Qwen: Qwen3 VL 30B A3B Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 2.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-vl-32b-instruct": {
+ "id": "qwen/qwen3-vl-32b-instruct",
+ "name": "Qwen: Qwen3 VL 32B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.104,
+ "output": 0.416,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-vl-8b-instruct": {
+ "id": "qwen/qwen3-vl-8b-instruct",
+ "name": "Qwen: Qwen3 VL 8B Instruct",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.117,
+ "output": 0.455,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3-vl-8b-thinking": {
+ "id": "qwen/qwen3-vl-8b-thinking",
+ "name": "Qwen: Qwen3 VL 8B Thinking",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.18,
+ "output": 2.1,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.5-122b-a10b": {
+ "id": "qwen/qwen3.5-122b-a10b",
+ "name": "Qwen: Qwen3.5-122B-A10B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.26,
+ "output": 2.08,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.5-27b": {
+ "id": "qwen/qwen3.5-27b",
+ "name": "Qwen: Qwen3.5-27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.195,
+ "output": 1.56,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.5-35b-a3b": {
+ "id": "qwen/qwen3.5-35b-a3b",
+ "name": "Qwen: Qwen3.5-35B-A3B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 1,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.5-397b-a17b": {
+ "id": "qwen/qwen3.5-397b-a17b",
+ "name": "Qwen: Qwen3.5 397B A17B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.55,
+ "output": 3.5,
+ "cacheRead": 0.225,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.5-9b": {
+ "id": "qwen/qwen3.5-9b",
+ "name": "Qwen: Qwen3.5-9B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.15,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.5-flash-02-23": {
+ "id": "qwen/qwen3.5-flash-02-23",
+ "name": "Qwen: Qwen3.5-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.065,
+ "output": 0.26,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.5-plus-02-15": {
+ "id": "qwen/qwen3.5-plus-02-15",
+ "name": "Qwen: Qwen3.5 Plus 2026-02-15",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.26,
+ "output": 1.56,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.5-plus-20260420": {
+ "id": "qwen/qwen3.5-plus-20260420",
+ "name": "Qwen: Qwen3.5 Plus 2026-04-20",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.8,
+ "cacheRead": 0,
+ "cacheWrite": 0.375
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.6-27b": {
+ "id": "qwen/qwen3.6-27b",
+ "name": "Qwen: Qwen3.6 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262140,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.32,
+ "output": 2.7,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.6-35b-a3b": {
+ "id": "qwen/qwen3.6-35b-a3b",
+ "name": "Qwen: Qwen3.6 35B A3B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 1,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.6-flash": {
+ "id": "qwen/qwen3.6-flash",
+ "name": "Qwen: Qwen3.6 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1875,
+ "output": 1.125,
+ "cacheRead": 0,
+ "cacheWrite": 0.234375
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.6-max-preview": {
+ "id": "qwen/qwen3.6-max-preview",
+ "name": "Qwen: Qwen3.6 Max Preview",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.027,
+ "output": 6.162,
+ "cacheRead": 0,
+ "cacheWrite": 1.28375
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.6-plus": {
+ "id": "qwen/qwen3.6-plus",
+ "name": "Qwen: Qwen3.6 Plus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.325,
+ "output": 1.95,
+ "cacheRead": 0,
+ "cacheWrite": 0.40625
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.7-flash": {
+ "id": "qwen/qwen3.7-flash",
+ "name": "Qwen: Qwen3.7 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.03,
+ "output": 0.13,
+ "cacheRead": 0.006,
+ "cacheWrite": 0.038
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.7-max": {
+ "id": "qwen/qwen3.7-max",
+ "name": "Qwen: Qwen3.7 Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.475,
+ "output": 4.425,
+ "cacheRead": 0.295,
+ "cacheWrite": 1.84375
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.7-plus": {
+ "id": "qwen/qwen3.7-plus",
+ "name": "Qwen: Qwen3.7 Plus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.32,
+ "output": 1.28,
+ "cacheRead": 0.064,
+ "cacheWrite": 0.4
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.8-2.4t-a95b": {
+ "id": "qwen/qwen3.8-2.4t-a95b",
+ "name": "Qwen: Qwen3.8 2.4T A95B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.8-27b": {
+ "id": "qwen/qwen3.8-27b",
+ "name": "Qwen: Qwen3.8 27B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.425,
+ "output": 2.55,
+ "cacheRead": 0.085,
+ "cacheWrite": 0.53125
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.8-27b:free": {
+ "id": "qwen/qwen3.8-27b:free",
+ "name": "Qwen: Qwen3.8 27B (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.8-flash": {
+ "id": "qwen/qwen3.8-flash",
+ "name": "Qwen: Qwen3.8 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.47,
+ "cacheRead": 0.016,
+ "cacheWrite": 0.2
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.8-max-0902": {
+ "id": "qwen/qwen3.8-max-0902",
+ "name": "Qwen: Qwen3.8 Max (0902)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.25,
+ "cacheWrite": 2.5
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.8-max-prime": {
+ "id": "qwen/qwen3.8-max-prime",
+ "name": "Qwen: Qwen3.8 Max Prime",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 4,
+ "output": 12,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "qwen/qwen3.8-omni-flash": {
+ "id": "qwen/qwen3.8-omni-flash",
+ "name": "Qwen: Qwen3.8 Omni Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.47,
+ "cacheRead": 0.016,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "rekaai/reka-edge": {
+ "id": "rekaai/reka-edge",
+ "name": "Reka Edge",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 16384,
+ "maxTokens": 14745,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.1,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "relace/relace-search": {
+ "id": "relace/relace-search",
+ "name": "Relace: Relace Search",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "sakana/fugu-max": {
+ "id": "sakana/fugu-max",
+ "name": "Sakana: Fugu Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "sakana/fugu-ultra": {
+ "id": "sakana/fugu-ultra",
+ "name": "Sakana: Fugu Ultra",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 30,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "sakana/fugu-ultra-v2": {
+ "id": "sakana/fugu-ultra-v2",
+ "name": "Sakana: Fugu Ultra v2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 5,
+ "output": 30,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "sakana/sakana-namazu": {
+ "id": "sakana/sakana-namazu",
+ "name": "Sakana: Sakana Namazu",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4,
+ "cacheRead": 0.15,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "sao10k/l3.1-euryale-70b": {
+ "id": "sao10k/l3.1-euryale-70b",
+ "name": "Sao10K: Llama 3.1 Euryale 70B v2.2",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.85,
+ "output": 0.85,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "stealth/space-bunny-alpha": {
+ "id": "stealth/space-bunny-alpha",
+ "name": "Space Bunny Alpha",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 524288,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "stepfun/step-3.5-flash": {
+ "id": "stepfun/step-3.5-flash",
+ "name": "StepFun: Step 3.5 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.1,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "stepfun/step-3.7-flash": {
+ "id": "stepfun/step-3.7-flash",
+ "name": "StepFun: Step 3.7 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 230400,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.2,
+ "output": 1.15,
+ "cacheRead": 0.04,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "tencent/hy3": {
+ "id": "tencent/hy3",
+ "name": "Tencent: Hy3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.132,
+ "output": 0.528,
+ "cacheRead": 0.033,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "tencent/hy3-preview": {
+ "id": "tencent/hy3-preview",
+ "name": "Tencent: Hy3 preview",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 235929,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.18,
+ "output": 0.6,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "tencent/hy4-preview": {
+ "id": "tencent/hy4-preview",
+ "name": "Tencent: Hy4 preview",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 64000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.834,
+ "output": 2.501,
+ "cacheRead": 0.042,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "thinkingmachines/inkling": {
+ "id": "thinkingmachines/inkling",
+ "name": "Thinking Machines: Inkling",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.95,
+ "output": 4.05,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "thinkingmachines/inkling-small": {
+ "id": "thinkingmachines/inkling-small",
+ "name": "Thinking Machines: Inkling Small",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.45,
+ "output": 1.2,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "thinkingmachines/inkling-small:free": {
+ "id": "thinkingmachines/inkling-small:free",
+ "name": "Thinking Machines: Inkling Small (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "thinkingmachines/inkling:free": {
+ "id": "thinkingmachines/inkling:free",
+ "name": "Thinking Machines: Inkling (free)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "typesafe/jev-router": {
+ "id": "typesafe/jev-router",
+ "name": "TypeSafe: Jev Router",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 4096,
+ "pricingKnown": false,
+ "cost": {
+ "input": -1000000,
+ "output": -1000000,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "unbiased/pareto": {
+ "id": "unbiased/pareto",
+ "name": "Pareto",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.5,
+ "output": 7.5,
+ "cacheRead": 0.25,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "unbiased/pareto-26.10-preview": {
+ "id": "unbiased/pareto-26.10-preview",
+ "name": "Pareto 26.10 Preview",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.8,
+ "output": 3.2,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "upstage/solar-mini4": {
+ "id": "upstage/solar-mini4",
+ "name": "Upstage: Solar Mini 4",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.05,
+ "output": 0.2,
+ "cacheRead": 0.005,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "upstage/solar-pro-3": {
+ "id": "upstage/solar-pro-3",
+ "name": "Upstage: Solar Pro 3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0.015,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "upstage/solar-pro4": {
+ "id": "upstage/solar-pro4",
+ "name": "Upstage: Solar Pro 4",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.09,
+ "output": 0.36,
+ "cacheRead": 0.018,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": "minimal",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "x-ai/grok-4.20": {
+ "id": "x-ai/grok-4.20",
+ "name": "SpaceXAI: Grok 4.20",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 2000000,
+ "maxTokens": 1800000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 2.5,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "x-ai/grok-4.3": {
+ "id": "x-ai/grok-4.3",
+ "name": "SpaceXAI: Grok 4.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 900000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 2.5,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "x-ai/grok-4.3:batch": {
+ "id": "x-ai/grok-4.3:batch",
+ "name": "SpaceXAI: Grok 4.3 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 900000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 2,
+ "cacheRead": 0.16,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "x-ai/grok-4.5": {
+ "id": "x-ai/grok-4.5",
+ "name": "SpaceXAI: Grok 4.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 450000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "x-ai/grok-4.6": {
+ "id": "x-ai/grok-4.6",
+ "name": "SpaceXAI: Grok 4.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 450000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "x-ai/grok-4.7": {
+ "id": "x-ai/grok-4.7",
+ "name": "SpaceXAI: Grok 4.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 450000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "x-ai/grok-build-0.1": {
+ "id": "x-ai/grok-build-0.1",
+ "name": "SpaceXAI: Grok Build 0.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 256000,
+ "maxTokens": 230400,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 2,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "xiaomi/mimo-v2.5": {
+ "id": "xiaomi/mimo-v2.5",
+ "name": "Xiaomi: MiMo-V2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.0028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "xiaomi/mimo-v2.5-pro": {
+ "id": "xiaomi/mimo-v2.5-pro",
+ "name": "Xiaomi: MiMo-V2.5-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.435,
+ "output": 0.87,
+ "cacheRead": 0.0036,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "xiaomi/mimo-v2.6-flash": {
+ "id": "xiaomi/mimo-v2.6-flash",
+ "name": "Xiaomi: MiMo-V2.6-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.0028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "xiaomi/mimo-v2.6-pro": {
+ "id": "xiaomi/mimo-v2.6-pro",
+ "name": "Xiaomi: MiMo-V2.6-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.435,
+ "output": 0.87,
+ "cacheRead": 0.0036,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "xiaomi/mimo-v2.6-pro-ultraspeed": {
+ "id": "xiaomi/mimo-v2.6-pro-ultraspeed",
+ "name": "Xiaomi: MiMo-V2.6-Pro-UltraSpeed",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 4.35,
+ "output": 8.7,
+ "cacheRead": 0.036,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-4.5": {
+ "id": "z-ai/glm-4.5",
+ "name": "Z.ai: GLM 4.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 98304,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.2,
+ "cacheRead": 0.11,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-4.5-air": {
+ "id": "z-ai/glm-4.5-air",
+ "name": "Z.ai: GLM 4.5 Air",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 98304,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.13,
+ "output": 0.85,
+ "cacheRead": 0.025,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-4.5v": {
+ "id": "z-ai/glm-4.5v",
+ "name": "Z.ai: GLM 4.5V",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 65536,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 1.8,
+ "cacheRead": 0.11,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-4.6": {
+ "id": "z-ai/glm-4.6",
+ "name": "Z.ai: GLM 4.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 198000,
+ "maxTokens": 16384,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.43,
+ "output": 1.75,
+ "cacheRead": 0.08,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-4.6v": {
+ "id": "z-ai/glm-4.6v",
+ "name": "Z.ai: GLM 4.6V",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 0.9,
+ "cacheRead": 0.05,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-4.7": {
+ "id": "z-ai/glm-4.7",
+ "name": "Z.ai: GLM 4.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.2,
+ "cacheRead": 0.11,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-4.7-flash": {
+ "id": "z-ai/glm-4.7-flash",
+ "name": "Z.ai: GLM 4.7 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 117964,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0605,
+ "output": 0.4,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5": {
+ "id": "z-ai/glm-5",
+ "name": "Z.ai: GLM 5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 198000,
+ "maxTokens": 128000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 1.9,
+ "cacheRead": 0.119,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5-turbo": {
+ "id": "z-ai/glm-5-turbo",
+ "name": "Z.ai: GLM 5 Turbo",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.2,
+ "output": 4,
+ "cacheRead": 0.24,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5.1": {
+ "id": "z-ai/glm-5.1",
+ "name": "Z.ai: GLM 5.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5.2": {
+ "id": "z-ai/glm-5.2",
+ "name": "Z.ai: GLM 5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.0224,
+ "output": 16,
+ "cacheRead": 0.0224,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5.3": {
+ "id": "z-ai/glm-5.3",
+ "name": "Z.ai: GLM 5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.14,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5.3-flash": {
+ "id": "z-ai/glm-5.3-flash",
+ "name": "Z.ai: GLM 5.3 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048575,
+ "maxTokens": 943717,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5.3-flash:batch": {
+ "id": "z-ai/glm-5.3-flash:batch",
+ "name": "Z.ai: GLM 5.3 Flash (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.06,
+ "output": 0.2,
+ "cacheRead": 0.012,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5.3-flashx": {
+ "id": "z-ai/glm-5.3-flashx",
+ "name": "Z.ai: GLM 5.3 FlashX",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.37,
+ "output": 1.25,
+ "cacheRead": 0.09,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5.3-prime": {
+ "id": "z-ai/glm-5.3-prime",
+ "name": "Z.ai: GLM 5.3 Prime",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 2.8,
+ "output": 8.8,
+ "cacheRead": 0.56,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5.3:batch": {
+ "id": "z-ai/glm-5.3:batch",
+ "name": "Z.ai: GLM 5.3 (batch)",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.45,
+ "output": 2,
+ "cacheRead": 0.1,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ },
+ "z-ai/glm-5v-turbo": {
+ "id": "z-ai/glm-5v-turbo",
+ "name": "Z.ai: GLM 5V Turbo",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.2,
+ "output": 4,
+ "cacheRead": 0.24,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsDeveloperRole": false,
+ "thinkingFormat": "openrouter",
+ "supportsStrictMode": true,
+ "sendSessionAffinityHeaders": true
+ }
+ }
+ },
+ "qwen-token-plan": {
+ "deepseek-v3.2": {
+ "id": "deepseek-v3.2",
+ "name": "DeepSeek V3.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "deepseek-v4-flash": {
+ "id": "deepseek-v4-flash",
+ "name": "DeepSeek V4 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4-flash-0731": {
+ "id": "deepseek-v4-flash-0731",
+ "name": "DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4-pro": {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4-pro-0813": {
+ "id": "deepseek-v4-pro-0813",
+ "name": "DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4.1-flash": {
+ "id": "deepseek-v4.1-flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5": {
+ "id": "glm-5",
+ "name": "GLM-5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 16384,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5.1": {
+ "id": "glm-5.1",
+ "name": "GLM-5.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5.2": {
+ "id": "glm-5.2",
+ "name": "GLM-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5.3": {
+ "id": "glm-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "kimi-k2.5": {
+ "id": "kimi-k2.5",
+ "name": "Kimi K2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 98304,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "kimi-k2.6": {
+ "id": "kimi-k2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "kimi-k2.7-code": {
+ "id": "kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "MiniMax-M2.5": {
+ "id": "MiniMax-M2.5",
+ "name": "MiniMax-M2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 196608,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.6-flash": {
+ "id": "qwen3.6-flash",
+ "name": "Qwen3.6 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.6-plus": {
+ "id": "qwen3.6-plus",
+ "name": "Qwen3.6 Plus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.7-max": {
+ "id": "qwen3.7-max",
+ "name": "Qwen3.7 Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.7-plus": {
+ "id": "qwen3.7-plus",
+ "name": "Qwen3.7 Plus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.8-flash": {
+ "id": "qwen3.8-flash",
+ "name": "Qwen3.8 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "qwen3.8-max": {
+ "id": "qwen3.8-max",
+ "name": "Qwen3.8 Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ }
+ },
+ "qwen-token-plan-cn": {
+ "deepseek-v3.2": {
+ "id": "deepseek-v3.2",
+ "name": "DeepSeek V3.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "deepseek-v4-flash": {
+ "id": "deepseek-v4-flash",
+ "name": "DeepSeek V4 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4-flash-0731": {
+ "id": "deepseek-v4-flash-0731",
+ "name": "DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4-pro": {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4-pro-0813": {
+ "id": "deepseek-v4-pro-0813",
+ "name": "DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4.1-flash": {
+ "id": "deepseek-v4.1-flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5": {
+ "id": "glm-5",
+ "name": "GLM-5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 16384,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5.1": {
+ "id": "glm-5.1",
+ "name": "GLM-5.1",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 202752,
+ "maxTokens": 128000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5.2": {
+ "id": "glm-5.2",
+ "name": "GLM-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5.3": {
+ "id": "glm-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "kimi-k2.5": {
+ "id": "kimi-k2.5",
+ "name": "Kimi K2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 98304,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "kimi-k2.6": {
+ "id": "kimi-k2.6",
+ "name": "Kimi K2.6",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "kimi-k2.7-code": {
+ "id": "kimi-k2.7-code",
+ "name": "Kimi K2.7 Code",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 262144,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "MiniMax-M2.5": {
+ "id": "MiniMax-M2.5",
+ "name": "MiniMax-M2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 196608,
+ "maxTokens": 32768,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.6-flash": {
+ "id": "qwen3.6-flash",
+ "name": "Qwen3.6 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.6-plus": {
+ "id": "qwen3.6-plus",
+ "name": "Qwen3.6 Plus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.7-max": {
+ "id": "qwen3.7-max",
+ "name": "Qwen3.7 Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.7-plus": {
+ "id": "qwen3.7-plus",
+ "name": "Qwen3.7 Plus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.8-flash": {
+ "id": "qwen3.8-flash",
+ "name": "Qwen3.8 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "qwen3.8-max": {
+ "id": "qwen3.8-max",
+ "name": "Qwen3.8 Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ }
+ },
+ "qwen-token-plan-individual": {
+ "deepseek-v4-flash-0731": {
+ "id": "deepseek-v4-flash-0731",
+ "name": "DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4-pro": {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "deepseek-v4-pro-0813": {
+ "id": "deepseek-v4-pro-0813",
+ "name": "DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 384000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "glm-5.2": {
+ "id": "glm-5.2",
+ "name": "GLM-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "qwen3.6-flash": {
+ "id": "qwen3.6-flash",
+ "name": "Qwen3.6 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.7-max": {
+ "id": "qwen3.7-max",
+ "name": "Qwen3.7 Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.7-plus": {
+ "id": "qwen3.7-plus",
+ "name": "Qwen3.7 Plus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 65536,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": false
+ }
+ },
+ "qwen3.8-flash": {
+ "id": "qwen3.8-flash",
+ "name": "Qwen3.8 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ },
+ "qwen3.8-max": {
+ "id": "qwen3.8-max",
+ "name": "Qwen3.8 Max",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": null,
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsStrictMode": true,
+ "thinkingFormat": "qwen",
+ "supportsDeveloperRole": false,
+ "supportsStore": false,
+ "supportsReasoningEffort": true
+ }
+ }
+ },
+ "together": {
+ "deepseek-ai/DeepSeek-V4-Flash-0731": {
+ "id": "deepseek-ai/DeepSeek-V4-Flash-0731",
+ "name": "DeepSeek V4 Flash 0731",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V4-Pro-0813": {
+ "id": "deepseek-ai/DeepSeek-V4-Pro-0813",
+ "name": "DeepSeek V4 Pro 0813",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.32,
+ "output": 3.96,
+ "cacheRead": 0.13,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "deepseek-ai/DeepSeek-V4.1-Flash": {
+ "id": "deepseek-ai/DeepSeek-V4.1-Flash",
+ "name": "DeepSeek V4.1 Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 384000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.006,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "meta-llama/Llama-3.3-70B-Instruct-Turbo": {
+ "id": "meta-llama/Llama-3.3-70B-Instruct-Turbo",
+ "name": "Llama 3.3 70B",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.04,
+ "output": 1.04,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "MiniMaxAI/MiniMax-M2.7": {
+ "id": "MiniMaxAI/MiniMax-M2.7",
+ "name": "MiniMax-M2.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 196608,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "MiniMaxAI/MiniMax-M3": {
+ "id": "MiniMaxAI/MiniMax-M3",
+ "name": "MiniMax-M3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 250000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 1.2,
+ "cacheRead": 0.06,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "moonshotai/Kimi-K3": {
+ "id": "moonshotai/Kimi-K3",
+ "name": "Kimi K3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 3,
+ "output": 15,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "nvidia/nemotron-3-ultra-550b-a55b": {
+ "id": "nvidia/nemotron-3-ultra-550b-a55b",
+ "name": "Nemotron 3 Ultra 550B A55B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 512300,
+ "maxTokens": 512300,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 3.6,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "openai/gpt-oss-120b": {
+ "id": "openai/gpt-oss-120b",
+ "name": "GPT OSS 120B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 131072,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.6,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "openai",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "Qwen/Qwen2.5-7B-Instruct-Turbo": {
+ "id": "Qwen/Qwen2.5-7B-Instruct-Turbo",
+ "name": "Qwen 2.5 7B Instruct Turbo",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 32768,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 0.3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "Qwen/Qwen3.5-9B": {
+ "id": "Qwen/Qwen3.5-9B",
+ "name": "Qwen3.5 9B",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 262144,
+ "maxTokens": 65536,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.17,
+ "output": 0.25,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "Qwen/Qwen3.6-Plus": {
+ "id": "Qwen/Qwen3.6-Plus",
+ "name": "Qwen3.6 Plus",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 500000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.5,
+ "output": 3,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "Qwen/Qwen3.7-Max": {
+ "id": "Qwen/Qwen3.7-Max",
+ "name": "Qwen3.7 Max",
+ "api": "openai-completions",
+ "reasoning": false,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 500000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.25,
+ "output": 3.75,
+ "cacheRead": 0.125,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "thinkingmachines/Inkling": {
+ "id": "thinkingmachines/Inkling",
+ "name": "Inkling",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 524288,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1,
+ "output": 4.05,
+ "cacheRead": 0.17,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "zai-org/GLM-5.2": {
+ "id": "zai-org/GLM-5.2",
+ "name": "GLM-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048575,
+ "maxTokens": 164000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "zai-org/GLM-5.3": {
+ "id": "zai-org/GLM-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 262144,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ },
+ "zai-org/GLM-5.3-Flash": {
+ "id": "zai-org/GLM-5.3-Flash",
+ "name": "GLM-5.3-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048575,
+ "maxTokens": 400000,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "minimal": null,
+ "low": null,
+ "medium": null
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "together",
+ "supportsLongCacheRetention": false,
+ "supportsStrictMode": false
+ }
+ }
+ },
+ "xai": {
+ "grok-4.3": {
+ "id": "grok-4.3",
+ "name": "Grok 4.3",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 30000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 1.25,
+ "output": 2.5,
+ "cacheRead": 0.2,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsLongCacheRetention": false
+ }
+ },
+ "grok-4.5": {
+ "id": "grok-4.5",
+ "name": "Grok 4.5",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 500000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.3,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
+ },
+ "compat": {
+ "supportsLongCacheRetention": false
+ }
+ },
+ "grok-4.6": {
+ "id": "grok-4.6",
+ "name": "Grok 4.6",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 500000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsLongCacheRetention": false
+ }
+ },
+ "grok-4.7": {
+ "id": "grok-4.7",
+ "name": "Grok 4.7",
+ "api": "openai-responses",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 500000,
+ "maxTokens": 500000,
+ "pricingKnown": false,
+ "cost": {
+ "input": 2,
+ "output": 6,
+ "cacheRead": 0.5,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": "xhigh",
+ "max": null
+ },
+ "compat": {
+ "supportsLongCacheRetention": false
+ }
+ }
+ },
+ "xiaomi": {
+ "mimo-v2.5": {
+ "id": "mimo-v2.5",
+ "name": "MiMo-V2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.0028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.5-pro": {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo-V2.5-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.435,
+ "output": 0.87,
+ "cacheRead": 0.0036,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.5-pro-ultraspeed": {
+ "id": "mimo-v2.5-pro-ultraspeed",
+ "name": "MiMo-V2.5-Pro-UltraSpeed",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.305,
+ "output": 2.61,
+ "cacheRead": 0.0108,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-flash": {
+ "id": "mimo-v2.6-flash",
+ "name": "MiMo-V2.6-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.14,
+ "output": 0.28,
+ "cacheRead": 0.0028,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-pro": {
+ "id": "mimo-v2.6-pro",
+ "name": "MiMo-V2.6-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.435,
+ "output": 0.87,
+ "cacheRead": 0.0036,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-pro-ultraspeed": {
+ "id": "mimo-v2.6-pro-ultraspeed",
+ "name": "MiMo-V2.6-Pro-UltraSpeed",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 4.35,
+ "output": 8.7,
+ "cacheRead": 0.036,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ }
+ },
+ "xiaomi-token-plan-ams": {
+ "mimo-v2.5": {
+ "id": "mimo-v2.5",
+ "name": "MiMo-V2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.5-pro": {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo-V2.5-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-flash": {
+ "id": "mimo-v2.6-flash",
+ "name": "MiMo-V2.6-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-pro": {
+ "id": "mimo-v2.6-pro",
+ "name": "MiMo-V2.6-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ }
+ },
+ "xiaomi-token-plan-cn": {
+ "mimo-v2.5": {
+ "id": "mimo-v2.5",
+ "name": "MiMo-V2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.5-pro": {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo-V2.5-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-flash": {
+ "id": "mimo-v2.6-flash",
+ "name": "MiMo-V2.6-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-pro": {
+ "id": "mimo-v2.6-pro",
+ "name": "MiMo-V2.6-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ }
+ },
+ "xiaomi-token-plan-sgp": {
+ "mimo-v2.5": {
+ "id": "mimo-v2.5",
+ "name": "MiMo-V2.5",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.5-pro": {
+ "id": "mimo-v2.5-pro",
+ "name": "MiMo-V2.5-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-flash": {
+ "id": "mimo-v2.6-flash",
+ "name": "MiMo-V2.6-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ },
+ "mimo-v2.6-pro": {
+ "id": "mimo-v2.6-pro",
+ "name": "MiMo-V2.6-Pro",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1048576,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStrictMode": true,
+ "requiresReasoningContentOnAssistantMessages": true,
+ "thinkingFormat": "deepseek"
+ }
+ }
+ },
+ "zai": {
+ "glm-4.7": {
+ "id": "glm-4.7",
+ "name": "GLM-4.7",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 204800,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.6,
+ "output": 2.2,
+ "cacheRead": 0.11,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5-turbo": {
+ "id": "glm-5-turbo",
+ "name": "GLM-5-Turbo",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 200000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.2,
+ "output": 4,
+ "cacheRead": 0.24,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5.2": {
+ "id": "glm-5.2",
+ "name": "GLM-5.2",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5.2-highspeed": {
+ "id": "glm-5.2-highspeed",
+ "name": "GLM-5.2 Highspeed",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": null,
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5.3": {
+ "id": "glm-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5.3-flash": {
+ "id": "glm-5.3-flash",
+ "name": "GLM-5.3-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5.3-highspeed": {
+ "id": "glm-5.3-highspeed",
+ "name": "GLM-5.3 Highspeed",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ }
+ },
+ "zai-coding-cn": {
+ "glm-4.6v": {
+ "id": "glm-4.6v",
+ "name": "GLM-4.6V",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 128000,
+ "maxTokens": 32768,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.3,
+ "output": 0.9,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "off",
+ "minimal",
+ "low",
+ "medium",
+ "high"
+ ],
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": false,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5.3": {
+ "id": "glm-5.3",
+ "name": "GLM-5.3",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 1.4,
+ "output": 4.4,
+ "cacheRead": 0.26,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5.3-flash": {
+ "id": "glm-5.3-flash",
+ "name": "GLM-5.3-Flash",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": true,
+ "cost": {
+ "input": 0.15,
+ "output": 0.5,
+ "cacheRead": 0.03,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ },
+ "glm-5.3-highspeed": {
+ "id": "glm-5.3-highspeed",
+ "name": "GLM-5.3 Highspeed",
+ "api": "openai-completions",
+ "reasoning": true,
+ "input": [
+ "text"
+ ],
+ "contextWindow": 1000000,
+ "maxTokens": 131072,
+ "pricingKnown": false,
+ "cost": {
+ "input": 0,
+ "output": 0,
+ "cacheRead": 0,
+ "cacheWrite": 0
+ },
+ "thinkingLevels": [
+ "low",
+ "high",
+ "max"
+ ],
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null,
+ "low": "low",
+ "medium": null,
+ "high": "high",
+ "xhigh": null,
+ "max": "max"
+ },
+ "compat": {
+ "supportsStore": false,
+ "supportsDeveloperRole": false,
+ "supportsReasoningEffort": true,
+ "maxTokensField": "max_tokens",
+ "thinkingFormat": "zai",
+ "supportsStrictMode": true,
+ "zaiToolStream": true
+ }
+ }
+ }
+}
diff --git a/internal/agentharness/pi.go b/internal/agentharness/pi.go
new file mode 100644
index 0000000..fe8bf4c
--- /dev/null
+++ b/internal/agentharness/pi.go
@@ -0,0 +1,505 @@
+package agentharness
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ _ "embed"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "math"
+ "net/url"
+ "os"
+ "path"
+ "strings"
+ "time"
+
+ "github.com/mitkox/esf/internal/sandbox"
+)
+
+const PiContractVersion = "esf/pi/v1"
+const PiRuntimePath = "/opt/esf/agents/node"
+const piKeyEnvironment = "ESF_PI_API_KEY"
+const piSummaryLimit = 128 << 10
+
+// piPinnedCatalog is generated only from pi-ai 1.0.3 in the committed lockfile.
+//
+//go:embed pi-catalog.json
+var piPinnedCatalog []byte
+
+// PiOptions pins the complete execution chain. v1 only runs a preinstalled,
+// bundled runner and Node runtime; no dependency resolution happens in a run.
+type PiOptions struct {
+ Name, Binary, BinarySHA256, RuntimeBinary, RuntimeSHA256 string
+ Preinstalled bool
+ Provider, BaseURL, Model, API, APIKeyEnv, ThinkingLevel, CatalogCache string
+ EgressManaged bool
+ Timeout time.Duration
+ MaxProcessRestarts *int
+ ReadFile func(string) ([]byte, error)
+ LookupEnv func(string) (string, bool)
+}
+
+// PiModelMetadata is an offline model definition, with explicit limits and
+// pricing provenance. Model prices are estimates, never provider billing.
+type PiModelMetadata struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ API string `json:"api"`
+ Reasoning bool `json:"reasoning"`
+ Input []string `json:"input"`
+ ContextWindow int `json:"contextWindow"`
+ MaxTokens int `json:"maxTokens"`
+ Cost *PiModelCost `json:"cost,omitempty"`
+ PricingKnown bool `json:"pricingKnown"`
+ ThinkingLevels []string `json:"thinkingLevels"`
+ ThinkingLevelMap map[string]*string `json:"thinkingLevelMap,omitempty"`
+ Compat json.RawMessage `json:"compat,omitempty"`
+}
+type PiModelCost struct {
+ Input float64 `json:"input"`
+ Output float64 `json:"output"`
+ CacheRead float64 `json:"cacheRead"`
+ CacheWrite float64 `json:"cacheWrite"`
+}
+
+func (c *PiModelCost) UnmarshalJSON(data []byte) error {
+ var rates map[string]*float64
+ if err := json.Unmarshal(data, &rates); err != nil {
+ return err
+ }
+ if len(rates) != 4 || rates["input"] == nil || rates["output"] == nil || rates["cacheRead"] == nil || rates["cacheWrite"] == nil {
+ return fmt.Errorf("cost must explicitly declare input, output, cacheRead, and cacheWrite rates")
+ }
+ c.Input, c.Output, c.CacheRead, c.CacheWrite = *rates["input"], *rates["output"], *rates["cacheRead"], *rates["cacheWrite"]
+ return nil
+}
+
+type piRequest struct {
+ ContractVersion string `json:"contract_version"`
+ RunID string `json:"run_id"`
+ RequestID string `json:"request_id"`
+ Prompt string `json:"prompt"`
+ RepositoryDir string `json:"repository_dir"`
+ StateDir string `json:"state_dir"`
+ Provider string `json:"provider"`
+ BaseURL string `json:"base_url"`
+ Model string `json:"model"`
+ API string `json:"api"`
+ ThinkingLevel string `json:"thinking_level"`
+ TimeoutMS int64 `json:"timeout_ms"`
+ MaxProcessRestarts int `json:"max_process_restarts"`
+ RunnerSHA256 string `json:"runner_sha256"`
+ RuntimeSHA256 string `json:"runtime_sha256"`
+ Metadata PiModelMetadata `json:"metadata"`
+ Fingerprint string `json:"fingerprint,omitempty"`
+}
+type piTerminal struct {
+ ContractVersion string `json:"contract_version"`
+ RunID string `json:"run_id"`
+ RequestID string `json:"request_id"`
+ Fingerprint string `json:"fingerprint"`
+ Model string `json:"model"`
+ Status string `json:"status"`
+ Error string `json:"error,omitempty"`
+ Restarts int `json:"restarts"`
+}
+type piUsage struct {
+ ContractVersion string `json:"contract_version"`
+ RunID string `json:"run_id"`
+ Fingerprint string `json:"fingerprint"`
+ Complete bool `json:"complete"`
+ TokensIn *int64 `json:"tokens_in"`
+ TokensOut *int64 `json:"tokens_out"`
+ CostUSD *float64 `json:"cost_usd"`
+ CostBasis string `json:"cost_basis"`
+ Models map[string]piModelUsage `json:"models"`
+ Tools map[string]json.RawMessage `json:"tools"`
+}
+
+type piModelUsage struct {
+ Input int64 `json:"input"`
+ Output int64 `json:"output"`
+ CacheRead int64 `json:"cacheRead"`
+ CacheWrite int64 `json:"cacheWrite"`
+ TotalTokens int64 `json:"totalTokens"`
+}
+
+type PiHarness struct {
+ generic *GenericCommandHarness
+ opts PiOptions
+ metadata PiModelMetadata
+ restarts int
+}
+
+func NewPi(opts PiOptions) (*PiHarness, error) {
+ if opts.Name == "" {
+ opts.Name = "pi"
+ }
+ if !opts.Preinstalled {
+ return nil, fmt.Errorf("pi: v1 requires preinstalled = true")
+ }
+ if !path.IsAbs(opts.Binary) || !validPiDigest(opts.BinarySHA256) {
+ return nil, fmt.Errorf("pi: absolute binary and binary_sha256 are required")
+ }
+ if opts.RuntimeBinary == "" {
+ opts.RuntimeBinary = PiRuntimePath
+ }
+ if !path.IsAbs(opts.RuntimeBinary) || !validPiDigest(opts.RuntimeSHA256) {
+ return nil, fmt.Errorf("pi: absolute runtime_binary and runtime_sha256 are required")
+ }
+ if opts.API == "" {
+ opts.API = "openai-completions"
+ }
+ if opts.API != "openai-completions" && opts.API != "openai-responses" {
+ return nil, fmt.Errorf("pi: unsupported api %q", opts.API)
+ }
+ if !harnessNamePattern.MatchString(opts.Provider) {
+ return nil, fmt.Errorf("pi: provider is required and must be a simple identifier")
+ }
+ if _, err := validateUnrealModel(opts.Model); err != nil {
+ return nil, fmt.Errorf("pi: %w", err)
+ }
+ endpoint, err := url.Parse(opts.BaseURL)
+ if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") || endpoint.User != nil || endpoint.RawQuery != "" || endpoint.Fragment != "" {
+ return nil, fmt.Errorf("pi: base_url must be an http(s) URL without credentials, query, or fragment")
+ }
+ if opts.EgressManaged && endpoint.Scheme != "https" {
+ return nil, fmt.Errorf("pi: cube_egress requires https")
+ }
+ if opts.APIKeyEnv != "" {
+ if err := ValidateEnvironmentName(opts.APIKeyEnv); err != nil {
+ return nil, err
+ }
+ }
+ if !opts.EgressManaged && opts.Provider != "ollama" && opts.Provider != "local" && opts.APIKeyEnv == "" {
+ return nil, fmt.Errorf("pi: provider credential source is required")
+ }
+ if opts.ReadFile == nil {
+ opts.ReadFile = func(name string) ([]byte, error) {
+ stat, err := os.Stat(name)
+ if err != nil {
+ return nil, err
+ }
+ if !stat.Mode().IsRegular() || stat.Size() > piSummaryLimit {
+ return nil, fmt.Errorf("model definition must be a bounded regular file")
+ }
+ file, err := os.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ stat, err = file.Stat()
+ if err != nil {
+ return nil, err
+ }
+ if !stat.Mode().IsRegular() || stat.Size() > piSummaryLimit {
+ return nil, fmt.Errorf("model definition must be a bounded regular file")
+ }
+ return io.ReadAll(io.LimitReader(file, piSummaryLimit+1))
+ }
+ }
+ if opts.LookupEnv == nil {
+ opts.LookupEnv = os.LookupEnv
+ }
+ var data []byte
+ if opts.CatalogCache != "" {
+ data, err = opts.ReadFile(opts.CatalogCache)
+ } else {
+ var catalog map[string]map[string]json.RawMessage
+ if err = json.Unmarshal(piPinnedCatalog, &catalog); err == nil {
+ data = catalog[opts.Provider][opts.Model]
+ }
+ if len(data) == 0 && err == nil {
+ err = fmt.Errorf("model absent from pinned catalog; catalog_cache must provide explicit metadata")
+ }
+ }
+ if err != nil {
+ return nil, fmt.Errorf("pi: read model definition: %w", err)
+ }
+ if len(data) > piSummaryLimit {
+ return nil, fmt.Errorf("pi: model definition exceeds limit")
+ }
+ var metadata PiModelMetadata
+ decoder := json.NewDecoder(bytes.NewReader(data))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&metadata); err != nil {
+ return nil, fmt.Errorf("pi: decode model definition: %w", err)
+ }
+ if err := decoder.Decode(new(any)); err != io.EOF {
+ return nil, fmt.Errorf("pi: model definition must contain exactly one JSON object")
+ }
+ if metadata.ID != opts.Model || metadata.API != opts.API || metadata.ContextWindow <= 0 || metadata.ContextWindow > (1<<53)-1 || metadata.MaxTokens <= 0 || metadata.MaxTokens >= metadata.ContextWindow {
+ return nil, fmt.Errorf("pi: model definition must match model/api and declare positive context/output limits")
+ }
+ if metadata.Name == "" {
+ metadata.Name = metadata.ID
+ }
+ if len(metadata.Compat) != 0 {
+ var compat map[string]json.RawMessage
+ if err := json.Unmarshal(metadata.Compat, &compat); err != nil || compat == nil {
+ return nil, fmt.Errorf("pi: compat must be an API compatibility object")
+ }
+ }
+ if len(metadata.Input) != 1 || metadata.Input[0] != "text" {
+ return nil, fmt.Errorf("pi: v1 model definition requires input = [text]")
+ }
+ if metadata.PricingKnown && metadata.Cost == nil {
+ return nil, fmt.Errorf("pi: known pricing requires cost rates")
+ }
+ if metadata.Cost != nil {
+ for _, v := range []float64{metadata.Cost.Input, metadata.Cost.Output, metadata.Cost.CacheRead, metadata.Cost.CacheWrite} {
+ if math.IsNaN(v) || math.IsInf(v, 0) || v < 0 {
+ return nil, fmt.Errorf("pi: invalid cost rate")
+ }
+ }
+ }
+ if opts.ThinkingLevel == "" {
+ opts.ThinkingLevel = "off"
+ }
+ validThinking := false
+ for _, v := range []string{"off", "minimal", "low", "medium", "high", "xhigh", "max"} {
+ if opts.ThinkingLevel == v {
+ validThinking = true
+ }
+ }
+ if !validThinking {
+ return nil, fmt.Errorf("pi: unsupported thinking_level")
+ }
+ if mapped, exists := metadata.ThinkingLevelMap[opts.ThinkingLevel]; exists && (mapped == nil || *mapped == "") {
+ return nil, fmt.Errorf("pi: selected thinking_level is disabled by the model mapping")
+ }
+ if opts.ThinkingLevel == "xhigh" || opts.ThinkingLevel == "max" {
+ if metadata.ThinkingLevelMap[opts.ThinkingLevel] == nil {
+ return nil, fmt.Errorf("pi: extended thinking_level requires an explicit provider mapping")
+ }
+ }
+ if opts.ThinkingLevel != "off" {
+ supported := false
+ for _, v := range metadata.ThinkingLevels {
+ if v == opts.ThinkingLevel {
+ supported = true
+ }
+ }
+ if !metadata.Reasoning || !supported {
+ return nil, fmt.Errorf("pi: thinking_level is not supported by the pinned model definition")
+ }
+ }
+ restarts := 1
+ if opts.MaxProcessRestarts != nil {
+ restarts = *opts.MaxProcessRestarts
+ }
+ if restarts < 0 || restarts > 1 {
+ return nil, fmt.Errorf("pi: max_process_restarts must be 0 or 1")
+ }
+ if opts.Timeout <= 0 {
+ opts.Timeout = 30 * time.Minute
+ }
+ if opts.Timeout.Milliseconds() > 2147483647 {
+ return nil, fmt.Errorf("pi: timeout exceeds supervisor timer limit")
+ }
+ generic, err := NewGeneric(Spec{Name: opts.Name, Executable: opts.RuntimeBinary, Args: []string{"--use-system-ca", opts.Binary}, Model: opts.Model, Timeout: opts.Timeout, PromptMode: PromptStdinFile, Provision: Provision{Preinstalled: true, BinaryDest: opts.Binary, BinarySHA256: opts.BinarySHA256}})
+ if err != nil {
+ return nil, err
+ }
+ return &PiHarness{generic: generic, opts: opts, metadata: metadata, restarts: restarts}, nil
+}
+
+func validPiDigest(d string) bool {
+ b, e := hex.DecodeString(d)
+ return e == nil && len(b) == sha256.Size
+}
+func (h *PiHarness) Name() string { return h.generic.Name() }
+func (h *PiHarness) Model() string { return h.opts.Model }
+func (h *PiHarness) ValidateModel(m string) error {
+ if m != "" && m != h.Model() {
+ return fmt.Errorf("pi: model override %q differs from configured model", m)
+ }
+ return nil
+}
+func (h *PiHarness) ValidateModelEndpoint(e ModelEndpoint) error {
+ for _, pair := range [][2]string{{e.Provider, h.opts.Provider}, {e.Model, h.opts.Model}, {e.BaseURL, h.opts.BaseURL}, {e.APIKeyEnv, h.opts.APIKeyEnv}} {
+ if pair[0] != "" && pair[0] != pair[1] {
+ return fmt.Errorf("pi: resolved model endpoint differs from configured provider, model, base URL, or credential source")
+ }
+ }
+ return nil
+}
+func (h *PiHarness) ConfigureModelEndpoint(_ context.Context, _ sandbox.Sandbox, e ModelEndpoint) error {
+ return h.ValidateModelEndpoint(e)
+}
+func (h *PiHarness) Provision(ctx context.Context, sb sandbox.Sandbox) error {
+ // Check the interpreter before executing any runner-controlled code.
+ exec, err := sb.Execute(ctx, sandbox.Command{Argv: []string{"sha256sum", h.opts.RuntimeBinary}, Timeout: time.Minute, Description: "verify Pi Node runtime digest"})
+ if err != nil {
+ return err
+ }
+ fields := strings.Fields(exec.Stdout)
+ if !exec.Succeeded() || len(fields) == 0 || !strings.EqualFold(fields[0], h.opts.RuntimeSHA256) {
+ return fmt.Errorf("pi: runtime SHA-256 mismatch")
+ }
+ if err := h.generic.Provision(ctx, sb); err != nil {
+ return err
+ }
+ exec, err = sb.Execute(ctx, sandbox.Command{Argv: []string{h.opts.RuntimeBinary, h.opts.Binary, "--version"}, Timeout: time.Minute, Description: "verify Pi runner and runtime"})
+ if err != nil {
+ return err
+ }
+ if !exec.Succeeded() || !strings.HasPrefix(strings.TrimSpace(exec.Stdout), "esf-pi/1 pi-durable/1.0.3 node/") {
+ return fmt.Errorf("pi: runner self-check failed")
+ }
+ return nil
+}
+func (h *PiHarness) Version(context.Context, sandbox.Sandbox) string {
+ return "pi-durable:1.0.3;runner-sha256:" + strings.ToLower(h.opts.BinarySHA256) + ";node-sha256:" + strings.ToLower(h.opts.RuntimeSHA256)
+}
+func (h *PiHarness) request(task Task) (piRequest, error) {
+ if task.RunID == "" || strings.TrimSpace(task.Prompt) == "" || !path.IsAbs(task.RepositoryDir) {
+ return piRequest{}, fmt.Errorf("pi: run ID, task, and absolute repository directory are required")
+ }
+ if err := h.ValidateModel(task.Model); err != nil {
+ return piRequest{}, err
+ }
+ timeout := task.Timeout
+ if timeout <= 0 {
+ timeout = h.opts.Timeout
+ }
+ if timeout.Milliseconds() <= 0 || timeout.Milliseconds() > 2147483647 {
+ return piRequest{}, fmt.Errorf("pi: timeout outside supervisor timer limits")
+ }
+ id := sha256.Sum256([]byte(task.RunID))
+ requestID := sha256.Sum256([]byte(task.RunID + "\x00" + task.Prompt))
+ req := piRequest{ContractVersion: PiContractVersion, RunID: task.RunID, RequestID: hex.EncodeToString(requestID[:]), Prompt: task.Prompt, RepositoryDir: path.Clean(task.RepositoryDir), StateDir: path.Join(path.Dir(path.Clean(task.RepositoryDir)), ".factory", "pi", hex.EncodeToString(id[:])), Provider: h.opts.Provider, BaseURL: h.opts.BaseURL, Model: h.opts.Model, API: h.opts.API, ThinkingLevel: h.opts.ThinkingLevel, TimeoutMS: timeout.Milliseconds(), MaxProcessRestarts: h.restarts, RunnerSHA256: strings.ToLower(h.opts.BinarySHA256), RuntimeSHA256: strings.ToLower(h.opts.RuntimeSHA256), Metadata: h.metadata}
+ b, _ := json.Marshal(req)
+ digest := sha256.Sum256(b)
+ req.Fingerprint = hex.EncodeToString(digest[:])
+ return req, nil
+}
+func (h *PiHarness) Run(ctx context.Context, sb sandbox.Sandbox, task Task) (Result, error) {
+ req, err := h.request(task)
+ if err != nil {
+ return Result{}, err
+ }
+ // The canonical credential is owned by this adapter. Unrelated task/host
+ // environment, including settings that redirect providers, never reaches Pi.
+ key := "cube-egress-managed-placeholder"
+ if !h.opts.EgressManaged && h.opts.APIKeyEnv != "" {
+ var ok bool
+ key, ok = h.opts.LookupEnv(h.opts.APIKeyEnv)
+ if !ok || strings.TrimSpace(key) == "" {
+ return Result{}, fmt.Errorf("pi: credential environment variable %s is empty", h.opts.APIKeyEnv)
+ }
+ }
+ encoded, err := json.Marshal(req)
+ if err != nil {
+ return Result{}, err
+ }
+ task.Prompt = string(encoded)
+ task.Env = map[string]string{piKeyEnvironment: key}
+ // The supervisor owns the task deadline. Allow bounded time to persist
+ // its timeout/cancellation receipts before the data plane kills it.
+ task.Timeout = time.Duration(req.TimeoutMS)*time.Millisecond + 5*time.Second
+ result, err := h.generic.Run(ctx, sb, task)
+ if err != nil {
+ return result, err
+ }
+ result.Version = h.Version(ctx, sb)
+ result.Evidence = map[string][]byte{}
+ var terminal piTerminal
+ terminalBytes, readErr := sb.ReadFile(ctx, path.Join(req.StateDir, "terminal.json"))
+ if readErr == nil && len(terminalBytes) <= piSummaryLimit {
+ readErr = json.Unmarshal(terminalBytes, &terminal)
+ } else if readErr == nil {
+ readErr = fmt.Errorf("terminal summary exceeds limit")
+ }
+ if readErr != nil || terminal.ContractVersion != PiContractVersion || terminal.RunID != req.RunID || terminal.RequestID != req.RequestID || terminal.Fingerprint != req.Fingerprint || terminal.Model != req.Model || terminal.Restarts < 0 || terminal.Restarts > h.restarts || (terminal.Status != "completed" && terminal.Status != "failed" && terminal.Status != "cancelled" && terminal.Status != "timeout") {
+ result.ExitCode = 1
+ result.Stderr += "\npi: missing, malformed, or mismatched terminal summary"
+ return result, nil
+ }
+ result.Evidence["agent/pi-terminal.json"] = terminalBytes
+ if terminal.Status != "completed" {
+ if result.ExitCode == 0 {
+ result.ExitCode = 1
+ }
+ result.Stderr += "\npi: " + terminal.Error
+ }
+ if terminal.Status == "timeout" {
+ result.TimedOut = true
+ }
+ usageBytes, e := sb.ReadFile(ctx, path.Join(req.StateDir, "usage.json"))
+ var usage piUsage
+ if e == nil && len(usageBytes) <= piSummaryLimit && json.Unmarshal(usageBytes, &usage) == nil && usage.ContractVersion == PiContractVersion && usage.RunID == req.RunID && usage.Fingerprint == req.Fingerprint {
+ valid := true
+ if usage.CostBasis != "estimated" && usage.CostBasis != "unavailable" {
+ valid = false
+ }
+ for _, v := range []*int64{usage.TokensIn, usage.TokensOut} {
+ if v != nil && *v < 0 {
+ valid = false
+ }
+ }
+ if usage.CostUSD != nil && (!h.metadata.PricingKnown || usage.CostBasis != "estimated" || math.IsNaN(*usage.CostUSD) || math.IsInf(*usage.CostUSD, 0) || *usage.CostUSD < 0) {
+ valid = false
+ }
+ if usage.Complete {
+ u, ok := usage.Models[req.Provider+"/"+req.Model]
+ if !ok || len(usage.Models) != 1 || usage.TokensIn == nil || usage.TokensOut == nil {
+ valid = false
+ }
+ for _, count := range []int64{u.Input, u.Output, u.CacheRead, u.CacheWrite, u.TotalTokens} {
+ if count < 0 || count > (1<<53)-1 {
+ valid = false
+ }
+ }
+ input := u.Input + u.CacheRead + u.CacheWrite
+ if u.TotalTokens <= 0 || u.TotalTokens != input+u.Output || (usage.TokensIn != nil && *usage.TokensIn != input) || (usage.TokensOut != nil && *usage.TokensOut != u.Output) {
+ valid = false
+ }
+ if usage.CostUSD != nil && h.metadata.Cost != nil {
+ rates := h.metadata.Cost
+ expected := (float64(u.Input)*rates.Input + float64(u.Output)*rates.Output + float64(u.CacheRead)*rates.CacheRead + float64(u.CacheWrite)*rates.CacheWrite) / 1e6
+ if math.IsInf(expected, 0) || math.IsNaN(expected) || math.Abs(*usage.CostUSD-expected) > 1e-9*math.Max(1, expected) {
+ valid = false
+ }
+ }
+ } else if usage.TokensIn != nil || usage.TokensOut != nil || usage.CostUSD != nil {
+ valid = false
+ }
+ if valid {
+ result.Evidence["agent/usage.json"] = usageBytes
+ if usage.Complete {
+ result.TokensIn = usage.TokensIn
+ result.TokensOut = usage.TokensOut
+ result.CostUSD = usage.CostUSD
+ }
+ }
+ }
+ recovery, e := sb.ReadFile(ctx, path.Join(req.StateDir, "recovery.json"))
+ var recoveryID struct {
+ ContractVersion string `json:"contract_version"`
+ RunID string `json:"run_id"`
+ Fingerprint string `json:"fingerprint"`
+ Restarts int `json:"restarts"`
+ Attempts []struct {
+ Attempt int `json:"attempt"`
+ Code *int `json:"code"`
+ Signal *string `json:"signal"`
+ ActiveShell bool `json:"active_shell"`
+ } `json:"attempts"`
+ }
+ if e == nil && len(recovery) <= piSummaryLimit && json.Unmarshal(recovery, &recoveryID) == nil && recoveryID.ContractVersion == PiContractVersion && recoveryID.RunID == req.RunID && recoveryID.Fingerprint == req.Fingerprint && recoveryID.Restarts == terminal.Restarts && len(recoveryID.Attempts) <= terminal.Restarts+1 {
+ valid := true
+ for i, attempt := range recoveryID.Attempts {
+ if attempt.Attempt != i+1 || (attempt.Code != nil && (*attempt.Code < 0 || *attempt.Code > 255)) {
+ valid = false
+ }
+ }
+ if valid {
+ result.Evidence["agent/recovery.json"] = recovery
+ }
+ }
+ return result, nil
+}
diff --git a/internal/agentharness/pi_test.go b/internal/agentharness/pi_test.go
new file mode 100644
index 0000000..887d996
--- /dev/null
+++ b/internal/agentharness/pi_test.go
@@ -0,0 +1,227 @@
+package agentharness
+
+import (
+ "context"
+ "encoding/json"
+ "path"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/mitkox/esf/internal/sandbox"
+)
+
+const piTestMetadata = `{"id":"test-model","name":"Test","api":"openai-completions","reasoning":false,"input":["text"],"contextWindow":32768,"maxTokens":1024,"pricingKnown":false,"thinkingLevels":["off"]}`
+
+func piTestOptions() PiOptions {
+ return PiOptions{Binary: "/opt/esf/agents/pi-runner.mjs", BinarySHA256: strings.Repeat("a", 64), RuntimeSHA256: strings.Repeat("b", 64), Preinstalled: true, Provider: "local", BaseURL: "http://gateway.internal:8000/v1", Model: "test-model", CatalogCache: "model.json", Timeout: time.Minute, ReadFile: func(string) ([]byte, error) { return []byte(piTestMetadata), nil }}
+}
+
+func TestPiFixedTransportAndCredentialIsolation(t *testing.T) {
+ opts := piTestOptions()
+ opts.EgressManaged = true
+ opts.Provider = "openai"
+ opts.BaseURL = "https://api.openai.com/v1"
+ opts.LookupEnv = func(string) (string, bool) { t.Fatal("host credential accessed in managed mode"); return "", false }
+ h, err := NewPi(opts)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f := sandbox.NewFake()
+ sb, _ := f.Create(context.Background(), sandbox.Spec{})
+ task := Task{RunID: "run-1", RepositoryDir: "/workspace/repository", Prompt: `Fix $(whoami); "quotes" and `, Env: map[string]string{"UNRELATED_SECRET": "secret", "ESF_PI_API_KEY": "attacker", "NODE_OPTIONS": "--import evil"}}
+ f.ExecuteFunc = func(cmd sandbox.Command) (sandbox.Execution, error) {
+ if !reflect.DeepEqual(cmd.Argv, []string{PiRuntimePath, "--use-system-ca", opts.Binary}) {
+ t.Fatalf("argv=%v", cmd.Argv)
+ }
+ if len(cmd.Env) != 1 || cmd.Env[piKeyEnvironment] != "cube-egress-managed-placeholder" {
+ t.Fatalf("environment=%v", cmd.Env)
+ }
+ data, _ := sb.ReadFile(context.Background(), cmd.StdinPath)
+ var req piRequest
+ if err := json.Unmarshal(data, &req); err != nil {
+ t.Fatal(err)
+ }
+ if req.Prompt != task.Prompt || req.RunID != task.RunID || req.TimeoutMS != 60000 {
+ t.Fatalf("request=%+v", req)
+ }
+ terminal := piTerminal{ContractVersion: PiContractVersion, RunID: req.RunID, RequestID: req.RequestID, Fingerprint: req.Fingerprint, Model: req.Model, Status: "completed"}
+ data, _ = json.Marshal(terminal)
+ _ = sb.WriteFile(context.Background(), path.Join(req.StateDir, "terminal.json"), data)
+ return sandbox.Execution{ExitCode: 0}, nil
+ }
+ result, err := h.Run(context.Background(), sb, task)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !result.Succeeded() || strings.Contains(result.CommandLine, task.Prompt) {
+ t.Fatalf("result=%+v", result)
+ }
+ if len(result.Evidence["agent/pi-terminal.json"]) == 0 {
+ t.Fatal("terminal evidence missing")
+ }
+ req1, _ := h.request(task)
+ req2, _ := h.request(task)
+ if req1.RequestID != req2.RequestID || req1.Fingerprint != req2.Fingerprint {
+ t.Fatal("unstable submission identity")
+ }
+ task.Prompt += " changed"
+ req2, _ = h.request(task)
+ if req1.Fingerprint == req2.Fingerprint || req1.RequestID == req2.RequestID {
+ t.Fatal("changed task reused identity")
+ }
+}
+
+func TestPiExitZeroRequiresMatchingTerminal(t *testing.T) {
+ for _, kind := range []string{"missing", "malformed", "wrong identity"} {
+ t.Run(kind, func(t *testing.T) {
+ h, _ := NewPi(piTestOptions())
+ f := sandbox.NewFake()
+ sb, _ := f.Create(context.Background(), sandbox.Spec{})
+ task := Task{RunID: "run", RepositoryDir: "/repo", Prompt: "task"}
+ req, _ := h.request(task)
+ if kind != "missing" {
+ data := []byte(`{`)
+ if kind == "wrong identity" {
+ data = []byte(`{"contract_version":"esf/pi/v1","status":"completed","run_id":"other"}`)
+ }
+ _ = sb.WriteFile(context.Background(), path.Join(req.StateDir, "terminal.json"), data)
+ }
+ result, err := h.Run(context.Background(), sb, task)
+ if err != nil || result.Succeeded() {
+ t.Fatalf("result=%+v err=%v", result, err)
+ }
+ })
+ }
+}
+
+func TestPiProvisionRefusesRuntimeAndBundleDigestMismatch(t *testing.T) {
+ for _, which := range []string{"runtime", "bundle"} {
+ t.Run(which, func(t *testing.T) {
+ h, _ := NewPi(piTestOptions())
+ f := sandbox.NewFake()
+ sb, _ := f.Create(context.Background(), sandbox.Spec{})
+ f.ExecuteFunc = func(cmd sandbox.Command) (sandbox.Execution, error) {
+ if cmd.Argv[0] != "sha256sum" {
+ t.Fatalf("executed runner before digest verification: %v", cmd.Argv)
+ }
+ digest := strings.Repeat("a", 64)
+ if cmd.Argv[1] == PiRuntimePath {
+ digest = strings.Repeat("b", 64)
+ }
+ if (which == "runtime" && cmd.Argv[1] == PiRuntimePath) || (which == "bundle" && cmd.Argv[1] != PiRuntimePath) {
+ digest = strings.Repeat("c", 64)
+ }
+ return sandbox.Execution{ExitCode: 0, Stdout: digest + " file"}, nil
+ }
+ if h.Provision(context.Background(), sb) == nil {
+ t.Fatal("digest mismatch accepted")
+ }
+ })
+ }
+}
+
+func TestPiRejectsModelPolicyAndInvalidConfiguration(t *testing.T) {
+ h, _ := NewPi(piTestOptions())
+ for _, e := range []ModelEndpoint{{Model: "other"}, {Provider: "other"}, {BaseURL: "http://other/v1"}, {APIKeyEnv: "OTHER_KEY"}} {
+ if h.ValidateModelEndpoint(e) == nil {
+ t.Fatalf("accepted %+v", e)
+ }
+ }
+ if h.ValidateModel("other") == nil {
+ t.Fatal("model override accepted")
+ }
+ for _, mutate := range []func(*PiOptions){
+ func(o *PiOptions) { o.Preinstalled = false }, func(o *PiOptions) { o.RuntimeSHA256 = "" }, func(o *PiOptions) { o.BinarySHA256 = "bad" },
+ func(o *PiOptions) { o.API = "other" }, func(o *PiOptions) { n := 2; o.MaxProcessRestarts = &n }, func(o *PiOptions) { o.CatalogCache = "" },
+ func(o *PiOptions) { o.ThinkingLevel = "high" }, func(o *PiOptions) {
+ o.ReadFile = func(string) ([]byte, error) { return []byte(piTestMetadata + ` {}`), nil }
+ },
+ func(o *PiOptions) {
+ o.ReadFile = func(string) ([]byte, error) {
+ return []byte(strings.Replace(piTestMetadata, `"contextWindow":32768`, `"contextWindow":0`, 1)), nil
+ }
+ },
+ func(o *PiOptions) {
+ o.ReadFile = func(string) ([]byte, error) {
+ return []byte(strings.Replace(piTestMetadata, `"contextWindow":32768`, `"contextWindow":9007199254740992`, 1)), nil
+ }
+ },
+ func(o *PiOptions) {
+ o.ReadFile = func(string) ([]byte, error) {
+ return []byte(strings.TrimSuffix(piTestMetadata, "}") + `,"compat":"invalid"}`), nil
+ }
+ },
+ func(o *PiOptions) {
+ o.ReadFile = func(string) ([]byte, error) {
+ return []byte(strings.TrimSuffix(piTestMetadata, "}") + `,"compat":null}`), nil
+ }
+ },
+ func(o *PiOptions) {
+ o.ReadFile = func(string) ([]byte, error) {
+ return []byte(strings.TrimSuffix(piTestMetadata, "}") + `,"cost":{"input":0,"output":0,"cacheRead":0}}`), nil
+ }
+ },
+ func(o *PiOptions) {
+ o.ReadFile = func(string) ([]byte, error) {
+ return []byte(strings.TrimSuffix(piTestMetadata, "}") + `,"cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":null}}`), nil
+ }
+ },
+ } {
+ opts := piTestOptions()
+ mutate(&opts)
+ if _, err := NewPi(opts); err == nil {
+ t.Fatalf("accepted invalid options %+v", opts)
+ }
+ }
+}
+
+func TestPiPinnedCatalogAndUsageValidation(t *testing.T) {
+ opts := piTestOptions()
+ opts.CatalogCache = ""
+ opts.Provider = "openai"
+ opts.Model = "gpt-4.1"
+ opts.API = "openai-responses"
+ opts.APIKeyEnv = "TEST_KEY"
+ if _, err := NewPi(opts); err != nil {
+ t.Fatalf("pinned catalog model: %v", err)
+ }
+ for _, kind := range []string{"complete", "partial", "inconsistent"} {
+ t.Run(kind, func(t *testing.T) {
+ h, _ := NewPi(piTestOptions())
+ f := sandbox.NewFake()
+ sb, _ := f.Create(context.Background(), sandbox.Spec{})
+ task := Task{RunID: "run", RepositoryDir: "/repo", Prompt: "task"}
+ req, _ := h.request(task)
+ terminal, _ := json.Marshal(piTerminal{ContractVersion: PiContractVersion, RunID: req.RunID, RequestID: req.RequestID, Fingerprint: req.Fingerprint, Model: req.Model, Status: "completed"})
+ _ = sb.WriteFile(context.Background(), path.Join(req.StateDir, "terminal.json"), terminal)
+ input, output := int64(12), int64(5)
+ u := piUsage{ContractVersion: PiContractVersion, RunID: req.RunID, Fingerprint: req.Fingerprint, Complete: true, TokensIn: &input, TokensOut: &output, CostBasis: "unavailable", Models: map[string]piModelUsage{"local/test-model": {Input: 10, Output: 5, CacheRead: 2, TotalTokens: 17}}}
+ if kind == "partial" {
+ u.Complete = false
+ u.TokensIn = nil
+ u.TokensOut = nil
+ }
+ if kind == "inconsistent" {
+ input = 13
+ }
+ data, _ := json.Marshal(u)
+ _ = sb.WriteFile(context.Background(), path.Join(req.StateDir, "usage.json"), data)
+ result, err := h.Run(context.Background(), sb, task)
+ if err != nil || !result.Succeeded() {
+ t.Fatalf("run=%+v err=%v", result, err)
+ }
+ if kind == "complete" {
+ if result.TokensIn == nil || *result.TokensIn != 12 || result.TokensOut == nil || *result.TokensOut != 5 {
+ t.Fatal("valid committed usage lost")
+ }
+ } else if result.TokensIn != nil || result.TokensOut != nil {
+ t.Fatal("partial or inconsistent usage presented as a total")
+ }
+ if result.CostUSD != nil {
+ t.Fatal("unknown prices presented as a cost")
+ }
+ })
+ }
+}
diff --git a/internal/factory/activities.go b/internal/factory/activities.go
index cdf3fb6..445ed07 100644
--- a/internal/factory/activities.go
+++ b/internal/factory/activities.go
@@ -519,6 +519,11 @@ func (a *Activities) ValidateRequest(ctx context.Context, in ValidateInput) (Val
if err != nil {
return ValidateOutput{}, fmt.Errorf("resolve resources: %w", err)
}
+ if validator, ok := harness.(agentharness.ModelEndpointValidator); ok {
+ if err := validator.ValidateModelEndpoint(agentharness.ModelEndpoint{Provider: resolved.ModelProvider, Model: resolved.ModelID, BaseURL: resolved.ModelBaseURL, APIKeyEnv: resolved.ModelAPIKeyEnv}); err != nil {
+ return ValidateOutput{}, err
+ }
+ }
// A scope narrows the global allowlist; it never widens it. The check is
// repeated here because the repository provider enforces only the global
// policy.
@@ -984,6 +989,18 @@ func (a *Activities) RunAgent(ctx context.Context, in RunAgentInput) (RunAgentOu
store.Write(ArtifactAgentPrompt, a.redactBytesString(in.Prompt)),
a.writeJSON(store, ArtifactAgentResult, map[string]any{"result": result, "attempt": attempt}),
}
+ for name, data := range result.Evidence {
+ switch name {
+ case "agent/pi-terminal.json", "agent/usage.json", "agent/recovery.json":
+ if len(data) > 128<<10 {
+ writes = append(writes, fmt.Errorf("supplementary agent evidence exceeds limit"))
+ continue
+ }
+ writes = append(writes, store.Write(name, a.redactBytesString(string(data))))
+ default:
+ writes = append(writes, fmt.Errorf("supplementary agent evidence path is not allowed"))
+ }
+ }
if out.Behavior != nil {
writes = append(writes, a.writeJSON(store, ArtifactBehavior, out.Behavior))
}
diff --git a/internal/factory/config.go b/internal/factory/config.go
index aad38e1..4386b52 100644
--- a/internal/factory/config.go
+++ b/internal/factory/config.go
@@ -173,9 +173,14 @@ type ObservabilityConfig struct {
//
// A caller names one of these keys. It can never supply an executable.
type HarnessConfig struct {
- // Type selects the harness implementation: "opencode", "unreal", or
- // "generic".
+ // Type selects "opencode", "unreal", "pi", or "generic".
Type string `toml:"type"`
+ // Pi runs a pinned Node interpreter and a bundled runner, with an explicit
+ // OpenAI-compatible protocol and bounded in-sandbox process recovery.
+ RuntimeBinary string `toml:"runtime_binary"`
+ RuntimeSHA256 string `toml:"runtime_sha256"`
+ API string `toml:"api"`
+ MaxProcessRestarts *int `toml:"max_process_restarts"`
// Executable is the agent program (generic harness only).
Executable string `toml:"executable"`
// Args is the fixed argument vector (generic harness only).
@@ -185,9 +190,9 @@ type HarnessConfig struct {
// Model is the default model.
Model string `toml:"model"`
// Provider selects the model provider for harnesses with a native provider
- // abstraction (currently unreal).
+ // abstraction (Unreal and Pi).
Provider string `toml:"provider"`
- // ThinkingLevel controls reasoning effort for unreal-agent.
+ // ThinkingLevel controls reasoning effort for Unreal and Pi.
ThinkingLevel string `toml:"thinking_level"`
// Timeout bounds one agent run.
Timeout tomlx.Duration `toml:"timeout"`
@@ -400,10 +405,15 @@ func (c Config) Validate() error {
problems = append(problems, "sandbox.base_packages: "+err.Error())
}
for name, h := range c.Harnesses {
+ if strings.EqualFold(strings.TrimSpace(h.Type), "pi") {
+ if _, err := buildPiHarness(name, h); err != nil {
+ problems = append(problems, err.Error())
+ }
+ }
if h.Preinstalled {
kind := strings.ToLower(strings.TrimSpace(h.Type))
- if kind != "opencode" && kind != "unreal" {
- problems = append(problems, fmt.Sprintf("harness %q: preinstalled is supported only for opencode and unreal", name))
+ if kind != "opencode" && kind != "unreal" && kind != "pi" {
+ problems = append(problems, fmt.Sprintf("harness %q: preinstalled is supported only for opencode, unreal, and pi", name))
}
if !filepath.IsAbs(h.Binary) || len(h.BinarySHA256) != 64 || len(h.Packages) != 0 {
problems = append(problems, fmt.Sprintf("harness %q: preinstalled requires an absolute sandbox binary path, a SHA-256 digest, and no packages", name))
@@ -419,8 +429,8 @@ func (c Config) Validate() error {
if mode != "" && mode != "environment" && mode != "cube_egress" {
problems = append(problems, fmt.Sprintf("harness %q: credential_mode must be environment or cube_egress", name))
}
- if mode == "cube_egress" && strings.ToLower(strings.TrimSpace(h.Type)) != "unreal" && strings.ToLower(strings.TrimSpace(h.Type)) != "opencode" {
- problems = append(problems, fmt.Sprintf("harness %q: cube_egress credential mode requires unreal or opencode", name))
+ if mode == "cube_egress" && strings.ToLower(strings.TrimSpace(h.Type)) != "unreal" && strings.ToLower(strings.TrimSpace(h.Type)) != "opencode" && strings.ToLower(strings.TrimSpace(h.Type)) != "pi" {
+ problems = append(problems, fmt.Sprintf("harness %q: cube_egress credential mode requires unreal, opencode, or pi", name))
}
if strings.TrimSpace(h.APIKeyFile) != "" && mode != "cube_egress" {
problems = append(problems, fmt.Sprintf("harness %q: api_key_file requires credential_mode = cube_egress", name))
@@ -607,6 +617,8 @@ func (c Config) BuildHarnesses() (*agentharness.Registry, error) {
Timeout: hc.Timeout.Std(),
Packages: hc.Packages,
})
+ case "pi":
+ harness, err = buildPiHarness(name, hc)
default:
return nil, fmt.Errorf("harness %q: unknown type %q", name, hc.Type)
}
@@ -620,6 +632,24 @@ func (c Config) BuildHarnesses() (*agentharness.Registry, error) {
return registry, nil
}
+func buildPiHarness(name string, hc HarnessConfig) (*agentharness.PiHarness, error) {
+ if hc.Executable != "" || len(hc.Args) != 0 || hc.ModelFlag != "" || hc.PromptMode != "" || len(hc.PassEnv) != 0 || len(hc.ProviderFiles) != 0 || len(hc.Packages) != 0 {
+ return nil, fmt.Errorf("harness %q: pi invocation is fixed; executable, args, model_flag, prompt_mode, pass_env, provider_files, and packages are not allowed", name)
+ }
+ h, err := agentharness.NewPi(agentharness.PiOptions{
+ Name: name, Binary: hc.Binary, BinarySHA256: hc.BinarySHA256, Preinstalled: hc.Preinstalled,
+ RuntimeBinary: hc.RuntimeBinary, RuntimeSHA256: hc.RuntimeSHA256,
+ Provider: hc.Provider, BaseURL: hc.BaseURL, Model: hc.Model, API: hc.API,
+ APIKeyEnv: hc.APIKeyEnv, ThinkingLevel: hc.ThinkingLevel, CatalogCache: hc.CatalogCache,
+ EgressManaged: strings.EqualFold(strings.TrimSpace(hc.CredentialMode), "cube_egress"),
+ Timeout: hc.Timeout.Std(), MaxProcessRestarts: hc.MaxProcessRestarts,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("harness %q: %w", name, err)
+ }
+ return h, nil
+}
+
// defaultVerificationProfiles provides a small, safe default so the factory can
// run before an operator writes their own profile.
//
diff --git a/internal/factory/credential_policy.go b/internal/factory/credential_policy.go
index ca6fade..cfb06c7 100644
--- a/internal/factory/credential_policy.go
+++ b/internal/factory/credential_policy.go
@@ -29,8 +29,8 @@ func (c Config) runtimeNetworkForHarness(name string) (sandbox.Network, bool, er
if !strings.EqualFold(strings.TrimSpace(h.CredentialMode), cubeEgressCredentialMode) {
return sandbox.Network{}, false, nil
}
- if !strings.EqualFold(strings.TrimSpace(h.Type), "unreal") && !strings.EqualFold(strings.TrimSpace(h.Type), "opencode") {
- return sandbox.Network{}, false, fmt.Errorf("harness %q: cube_egress credential mode requires type unreal or opencode", name)
+ if !strings.EqualFold(strings.TrimSpace(h.Type), "unreal") && !strings.EqualFold(strings.TrimSpace(h.Type), "opencode") && !strings.EqualFold(strings.TrimSpace(h.Type), "pi") {
+ return sandbox.Network{}, false, fmt.Errorf("harness %q: cube_egress credential mode requires type unreal, opencode, or pi", name)
}
if err := validateCubeEgressConfig(name, h); err != nil {
return sandbox.Network{}, false, err
diff --git a/internal/factory/example.toml b/internal/factory/example.toml
index 8b57ace..55c449f 100644
--- a/internal/factory/example.toml
+++ b/internal/factory/example.toml
@@ -273,3 +273,21 @@ description = "repository test script"
# timeout = "24h"
# preview_ports = [3000]
# suspend = true
+
+# Opt-in Pi v1 candidate; requires a separately qualified READY template.
+# See docs/harness-pi.md. OpenCode remains the automatic default.
+# [harnesses.pi]
+# type = "pi"
+# preinstalled = true
+# binary = "/opt/esf/agents/pi-runner.mjs"
+# binary_sha256 = "9dab48151c793cf3265af4058ea7aac8671d1778b31873ee25ac3fc24afe0e2c"
+# runtime_binary = "/opt/esf/agents/node"
+# runtime_sha256 = "7fde7b8afa198da66257f42ee2001d874c7355631e6d1579a5fb5ef1f246df4c"
+# provider = "local"
+# base_url = "http://192.168.0.14:8000/v1"
+# model = ""
+# api = "openai-completions"
+# catalog_cache = "/absolute/path/to/validated-model.json"
+# thinking_level = "off"
+# max_process_restarts = 1
+# timeout = "30m"
diff --git a/internal/factory/pi_test.go b/internal/factory/pi_test.go
new file mode 100644
index 0000000..e4e173e
--- /dev/null
+++ b/internal/factory/pi_test.go
@@ -0,0 +1,139 @@
+package factory
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/mitkox/esf/internal/agentharness"
+ artifacts "github.com/mitkox/esf/internal/factoryartifacts"
+ "github.com/mitkox/esf/internal/repository"
+ "github.com/mitkox/esf/internal/sandbox"
+ "github.com/mitkox/esf/internal/tomlx"
+)
+
+func piFactoryConfig(t *testing.T) Config {
+ t.Helper()
+ cfg := testValidConfigForCredentialPolicy()
+ cache := filepath.Join(t.TempDir(), "model.json")
+ if err := os.WriteFile(cache, []byte(`{"id":"test-model","api":"openai-completions","input":["text"],"contextWindow":32768,"maxTokens":1024,"thinkingLevels":["off"],"pricingKnown":false}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ cfg.Harnesses["pi"] = HarnessConfig{Type: "pi", Binary: "/opt/esf/agents/pi-runner.mjs", BinarySHA256: strings.Repeat("a", 64), RuntimeSHA256: strings.Repeat("b", 64), Preinstalled: true, Provider: "local", BaseURL: "http://gateway.internal:8000/v1", Model: "test-model", CatalogCache: cache, Timeout: tomlx.FromStd(time.Minute)}
+ return cfg
+}
+
+func TestPiConfigurationRegistersWithoutChangingDefault(t *testing.T) {
+ cfg := piFactoryConfig(t)
+ if err := cfg.Validate(); err != nil {
+ t.Fatal(err)
+ }
+ reg, err := cfg.BuildHarnesses()
+ if err != nil {
+ t.Fatal(err)
+ }
+ h, err := reg.Resolve("pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := h.(*agentharness.PiHarness); !ok {
+ t.Fatalf("harness=%T", h)
+ }
+ for _, mutate := range []func(*HarnessConfig){func(h *HarnessConfig) { h.Args = []string{"evil"} }, func(h *HarnessConfig) { h.PassEnv = []string{"SECRET"} }, func(h *HarnessConfig) { h.RuntimeSHA256 = "" }, func(h *HarnessConfig) { h.CatalogCache = "missing.json" }} {
+ bad := piFactoryConfig(t)
+ h := bad.Harnesses["pi"]
+ mutate(&h)
+ bad.Harnesses["pi"] = h
+ if bad.Validate() == nil {
+ t.Fatal("unsafe Pi configuration accepted")
+ }
+ }
+}
+
+func TestPiRejectsResolvedEndpointBeforeSandboxAllocation(t *testing.T) {
+ cfg := piFactoryConfig(t)
+ cfg.Repositories.Allowed = []string{"https://github.com/acme/"}
+ cfg.Models = map[string]ModelConfig{"other": {Provider: "local", Model: "test-model", BaseURL: "http://wrong.internal:8000/v1"}}
+ reg, err := cfg.BuildHarnesses()
+ if err != nil {
+ t.Fatal(err)
+ }
+ provider := sandbox.NewFake()
+ store, err := artifacts.NewLocal(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ acts, err := NewActivities(ActivitiesOptions{Config: cfg, Provider: provider, Repositories: repository.New(cfg.Repositories.Allowed), Harnesses: reg, Profiles: cfg.VerificationProfiles(), ArtifactFactory: store})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = acts.ValidateRequest(context.Background(), ValidateInput{Request: RunRequest{RunID: "run-pi", Repository: "https://github.com/acme/repo", Revision: "abc", Task: "fix", AgentHarness: "pi", VerificationProfile: "default", Model: "other"}})
+ if err == nil || !strings.Contains(err.Error(), "resolved model endpoint") {
+ t.Fatalf("error=%v", err)
+ }
+ if len(provider.Created()) != 0 {
+ t.Fatal("allocated sandbox before model policy rejection")
+ }
+}
+
+type piEvidenceHarness struct{ agentharness.Harness }
+
+func (h piEvidenceHarness) Run(context.Context, sandbox.Sandbox, agentharness.Task) (agentharness.Result, error) {
+ return agentharness.Result{ExitCode: 0, Evidence: map[string][]byte{"agent/usage.json": []byte(`{"secret":"provider-secret"}`), "../../escape": []byte("unsafe")}}, nil
+}
+func TestPiSupplementaryEvidenceIsRedactedAndTransient(t *testing.T) {
+ provider := sandbox.NewFake()
+ sb, _ := provider.Create(context.Background(), sandbox.Spec{})
+ store, err := artifacts.NewLocal(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ generic, _ := agentharness.NewGeneric(agentharness.Spec{Name: "pi", Executable: "agent", Timeout: time.Minute})
+ reg := agentharness.NewRegistry()
+ _ = reg.Register(piEvidenceHarness{generic})
+ acts, err := NewActivities(ActivitiesOptions{Provider: provider, Repositories: repository.New(nil), Harnesses: reg, ArtifactFactory: store, Redactor: NewRedactor("provider-secret")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ out, err := acts.RunAgent(context.Background(), RunAgentInput{RunID: "pi-evidence", SandboxID: sb.ID(), Harness: "pi", Prompt: "task", RepositoryDir: "/repo"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ runStore, _ := store.ForRun("pi-evidence")
+ bytes, err := runStore.Read("agent/usage.json")
+ if err != nil || strings.Contains(string(bytes), "provider-secret") {
+ t.Fatalf("evidence=%s err=%v", bytes, err)
+ }
+ encoded, _ := json.Marshal(out)
+ if strings.Contains(string(encoded), "provider-secret") || strings.Contains(string(encoded), "escape") {
+ t.Fatal("transient evidence leaked into workflow payload")
+ }
+ if out.EvidenceError == "" {
+ t.Fatal("unsafe evidence path not surfaced")
+ }
+}
+
+func TestPiCredentialRemainsAtCubeEgress(t *testing.T) {
+ cfg := piFactoryConfig(t)
+ h := cfg.Harnesses["pi"]
+ h.Provider = "openai"
+ h.BaseURL = "https://api.openai.com/v1"
+ h.APIKeyEnv = "TEST_PI_KEY"
+ h.CredentialMode = "cube_egress"
+ cfg.Harnesses["pi"] = h
+ t.Setenv("TEST_PI_KEY", "test-provider-secret")
+ if err := cfg.Validate(); err != nil {
+ t.Fatal(err)
+ }
+ network, applies, err := cfg.runtimeNetworkForHarness("pi")
+ if err != nil || !applies {
+ t.Fatalf("policy=%v %v", applies, err)
+ }
+ if *network.AllowInternet || len(network.Rules) != 1 || network.Rules[0].Action.Inject[0].Secret != "test-provider-secret" {
+ t.Fatal("Pi credential policy not scoped to proxy")
+ }
+}
diff --git a/scripts/generate-sbom.py b/scripts/generate-sbom.py
index c43cdfa..c0ca262 100644
--- a/scripts/generate-sbom.py
+++ b/scripts/generate-sbom.py
@@ -51,12 +51,20 @@ def main():
go_modules(),
npm_packages("internal/controlplane/web/package-lock.json"),
npm_packages("agents/opencode/package-lock.json"),
+ npm_packages("agents/pi/package-lock.json"),
python_packages(),
)
for source in sources:
for ecosystem, name, version in source:
purl = f"pkg:{ecosystem}/{quote(name, safe='/')}@{quote(version, safe='.+-')}"
components[purl] = {"type": "library", "bom-ref": purl, "name": name, "version": version, "purl": purl}
+ pi = json.loads((ROOT / "agents/pi/inventory.json").read_text())
+ for name, entry in (("esf-pi-runner", pi["runner"]), ("node", pi["runtime"])):
+ ref = "esf:pi:" + name
+ components[ref] = {"type": "application", "bom-ref": ref, "name": name,
+ "version": pi["contract_version"] if name == "esf-pi-runner" else entry["version"],
+ "hashes": [{"alg": "SHA-256", "content": entry["sha256"]}],
+ "licenses": [{"license": {"id": "MIT"}}]}
ordered = [components[key] for key in sorted(components)]
component_digest = hashlib.sha256(json.dumps(ordered, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
bom = {
diff --git a/scripts/install-pi-agent.sh b/scripts/install-pi-agent.sh
new file mode 100755
index 0000000..3051c6d
--- /dev/null
+++ b/scripts/install-pi-agent.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# Install offline artifacts into a template staging filesystem, never a run.
+set -euo pipefail
+[[ $# = 2 ]] || { echo 'usage: install-pi-agent.sh DIGEST_PINNED_NODE_BINARY DESTINATION' >&2; exit 2; }
+[[ $(uname -s)/$(uname -m) = Linux/x86_64 ]] || { echo 'Pi v1 qualifies Linux/amd64 only' >&2; exit 2; }
+python3 scripts/verify-agent-file.py pi agents/pi/dist/pi-runner.mjs
+python3 scripts/verify-agent-file.py pi-node "$1"
+python3 scripts/verify-pi-inventory.py
+mkdir -p "$2"
+install -m 0755 "$1" "$2/.node.new"
+install -m 0644 agents/pi/dist/pi-runner.mjs "$2/.pi-runner.mjs.new"
+install -m 0644 agents/pi/dist/THIRD_PARTY_NOTICES.txt "$2/.THIRD_PARTY_NOTICES.txt.new"
+mv -f "$2/.node.new" "$2/node"
+mv -f "$2/.pi-runner.mjs.new" "$2/pi-runner.mjs"
+mv -f "$2/.THIRD_PARTY_NOTICES.txt.new" "$2/THIRD_PARTY_NOTICES.txt"
+printf 'installed verified Pi 1.0.3 execution chain in %s\n' "$2"
diff --git a/scripts/verify-agent-file.py b/scripts/verify-agent-file.py
index 4790fca..379fd97 100644
--- a/scripts/verify-agent-file.py
+++ b/scripts/verify-agent-file.py
@@ -6,8 +6,8 @@
from pathlib import Path
import sys
-if len(sys.argv) != 3 or sys.argv[1] not in {"opencode", "unreal", "unreal-archive", "unreal-sums"}:
- raise SystemExit("usage: verify-agent-file.py {opencode|unreal|unreal-archive|unreal-sums} FILE")
+if len(sys.argv) != 3 or sys.argv[1] not in {"opencode", "unreal", "unreal-archive", "unreal-sums", "pi", "pi-node"}:
+ raise SystemExit("usage: verify-agent-file.py {opencode|unreal|unreal-archive|unreal-sums|pi|pi-node} FILE")
root = Path(__file__).resolve().parents[1]
dependencies = json.loads((root / "release/inventory.json").read_text())["dependencies"]
@@ -16,9 +16,17 @@
"unreal": ("unreal", "binary_sha256"),
"unreal-archive": ("unreal", "linux_amd64_archive_sha256"),
"unreal-sums": ("unreal", "sha256sums_sha256"),
-}[sys.argv[1]]
-expected = dependencies[key[0]][key[1]]
-digest = hashlib.file_digest(open(sys.argv[2], "rb"), "sha256").hexdigest()
+}.get(sys.argv[1])
+if key:
+ expected = dependencies[key[0]][key[1]]
+else:
+ pi = json.loads((root / "agents/pi/inventory.json").read_text())
+ expected = pi["runner" if sys.argv[1] == "pi" else "runtime"]["sha256"]
+sha256 = hashlib.sha256()
+with open(sys.argv[2], "rb") as artifact:
+ for chunk in iter(lambda: artifact.read(1 << 20), b""):
+ sha256.update(chunk)
+digest = sha256.hexdigest()
if digest != expected:
raise SystemExit(f"{sys.argv[1]} digest mismatch: {digest}")
print(f"{sys.argv[1]} sha256 verified: {digest}")
diff --git a/scripts/verify-pi-inventory.py b/scripts/verify-pi-inventory.py
new file mode 100755
index 0000000..44e9a4e
--- /dev/null
+++ b/scripts/verify-pi-inventory.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+"""Check candidate Pi artifacts without changing historical release records."""
+import hashlib
+import json
+from pathlib import Path
+
+root = Path(__file__).resolve().parents[1]
+inventory = json.loads((root / "agents/pi/inventory.json").read_text())
+lock_path = root / "agents/pi/package-lock.json"
+lock = json.loads(lock_path.read_text())
+assert hashlib.sha256(lock_path.read_bytes()).hexdigest() == inventory["package_lock_sha256"], "Pi lock digest mismatch"
+for name in ("pi-durable", "pi-ai", "chord"):
+ package = lock["packages"]["node_modules/@earendil-works/" + name]
+ assert package["version"] == "1.0.3" and package["integrity"].startswith("sha512-"), "Pi package not pinned"
+assert inventory["pi_durable"]["git_commit"] == "d78dc83d633229d12f8b79631384c4c2717c399f"
+assert hashlib.sha256((root / "internal/agentharness/pi-catalog.json").read_bytes()).hexdigest() == inventory["model_catalog_sha256"], "Pi catalog pin mismatch"
+digest = hashlib.sha256((root / "agents/pi/dist/pi-runner.mjs").read_bytes()).hexdigest()
+assert digest == inventory["runner"]["sha256"], "Pi runner inventory mismatch"
+assert (root / "agents/pi/dist/SHA256SUMS").read_text() == digest + " pi-runner.mjs\n"
+dockerfile = (root / "deploy/cube/Dockerfile.pi-v1").read_text()
+for entry in (inventory["runtime"], inventory["runner"]):
+ assert entry["sha256"] in dockerfile, "Pi template pin mismatch"
+assert inventory["runtime"]["image"] in dockerfile
+assert hashlib.sha256((root / "agents/pi/dist/THIRD_PARTY_NOTICES.txt").read_bytes()).hexdigest() == inventory["third_party_notices_sha256"], "Pi license notices mismatch"
+print("Pi candidate inventory and pinned dependency graph verified")