commit e3664ed4e9dd7640b85aba4b3cd6d345ad3ab69a Author: shinyobjectz Date: Sun Oct 18 11:07:18 2026 -0700 raea: the Render Anything Engine, first public canary One GPU engine for video, motion, games and 3D, written as React and TypeScript with @raea/motion and rendered by Bevy; void, the Mac app on top of it; an agent skill and a Claude Code plugin. Licensed FSL-1.1-ALv2. diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 00000000..7545ae9e --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,9 @@ +# raea's executables carry the JIT entitlement (tools/link-jit.sh): JavaScriptCore, the JS engine that replaces V8, +# keeps its JIT off without it +[target.aarch64-apple-darwin] +linker = "tools/link-jit.sh" + +# no strip after linking: rustc's strip pass re-signs the binary and drops the entitlement (release has no debug info +# of its own; std's stays) +[profile.release] +strip = false diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 00000000..c761d885 --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,11 @@ +{ + "name": "raea", + "owner": { "name": "Shane Murphy", "url": "https://raea.io" }, + "plugins": [ + { + "name": "raea", + "source": "./", + "description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine." + } + ] +} diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 00000000..5fcbb669 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,10 @@ +{ + "name": "raea", + "version": "0.1.0", + "description": "Make video, motion graphics, games and 3D with raea, the Render Anything Engine: write @raea/motion compositions, render them on the GPU, check the frames.", + "author": { "name": "Shane Murphy", "url": "https://raea.io" }, + "homepage": "https://raea.io", + "repository": "https://github.com/shinyobjectz/raea", + "license": "FSL-1.1-ALv2", + "keywords": ["video", "motion-graphics", "game-development", "rendering", "bevy", "react", "mcp"] +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..b48962f7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +target/ +.DS_Store +.premerge-git/ +# regenerable frame embeddings from the temporal bench (siglip_frames.py, vjepa_windows.py) +meaning/bench/temporal/out/*.npz +__pycache__/ +void/tw/node_modules/ +motion/node_modules/ +media/golden/ diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 00000000..0dbef303 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,8 @@ +# gitleaks: the default rules, minus raea's asset ledgers, whose "key" field is a content hash of the made file +# (prompt, seed and model), not a credential. +[extend] +useDefault = true + +[allowlist] +description = "asset ledgers" +paths = ['''(^|/)assets/made\.jsonl$'''] diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..926929c4 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,105 @@ +# Functional Source License, Version 1.1, ALv2 Future License + +## Abbreviation + +FSL-1.1-ALv2 + +## Notice + +Copyright 2026 Shane Murphy + +## Terms and Conditions + +### Licensor ("We") + +The party offering the Software under these Terms and Conditions. + +### The Software + +The "Software" is each version of the software that we make available under +these Terms and Conditions, as indicated by our inclusion of these Terms and +Conditions with the Software. + +### License Grant + +Subject to your compliance with this License Grant and the Patents, +Redistribution and Trademark clauses below, we hereby grant you the right to +use, copy, modify, create derivative works, publicly perform, publicly display +and redistribute the Software for any Permitted Purpose identified below. + +### Permitted Purpose + +A Permitted Purpose is any purpose other than a Competing Use. A Competing Use +means making the Software available to others in a commercial product or +service that: + +1. substitutes for the Software; + +2. substitutes for any other product or service we offer using the Software + that exists as of the date we make the Software available; or + +3. offers the same or substantially similar functionality as the Software. + +Permitted Purposes specifically include using the Software: + +1. for your internal use and access; + +2. for non-commercial education; + +3. for non-commercial research; and + +4. in connection with professional services that you provide to a licensee + using the Software in accordance with these Terms and Conditions. + +### Patents + +To the extent your use for a Permitted Purpose would necessarily infringe our +patents, the license grant above includes a license under our patents. If you +make a claim against any party that the Software infringes or contributes to +the infringement of any patent, then your patent license to the Software ends +immediately. + +### Redistribution + +The Terms and Conditions apply to all copies, modifications and derivatives of +the Software. + +If you redistribute any copies, modifications or derivatives of the Software, +you must include a copy of or a link to these Terms and Conditions and not +remove any copyright notices provided in or with the Software. + +### Disclaimer + +THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR +PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT. + +IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE +SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, +EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE. + +### Trademarks + +Except for displaying the License Details and identifying us as the origin of +the Software, you have no right under these Terms and Conditions to use our +trademarks, trade names, service marks or product names. + +## Grant of Future License + +We hereby irrevocably grant you an additional license to use the Software under +the Apache License, Version 2.0 that is effective on the second anniversary of +the date we make the Software available. On or after that date, you may use the +Software under the Apache License, Version 2.0, in which case the following +will apply: + +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. diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 00000000..ae06b37e --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,190 @@ + 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 the 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 the 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 any 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 + + Copyright 2026 HeyGen, Inc. + + 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. diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..fe30a23a --- /dev/null +++ b/NOTICE @@ -0,0 +1,38 @@ +raea, the Render Anything Engine +Copyright 2026 Shane Murphy +Licensed under the Functional Source License, Version 1.1, ALv2 Future License (LICENSE.md). + +raea includes software and work derived from the following projects, each under its own licence. + +HyperFrames: https://github.com/heygen-com/hyperframes + Copyright HeyGen. Licensed under the Apache License, Version 2.0 (LICENSES/Apache-2.0.txt). + raea's HTML composition path ports from HyperFrames' packages/core and packages/producer: the composition format, + the compile rules for sub-compositions (inlining, CSS and script scoping, inner-root wrappers), the runtime timing + rules (data-start expressions, clip visibility, frame snapping, timeline nesting, variables) and the deterministic + font rules. The ported files carry a header saying so: engine/src/compile.rs, fonts.rs, scene.rs, runtime.rs and + gsap_shim.js. raea renamed the format's runtime names (window.__raea, data-raea-* attributes, the "html" profile). + +Blitz: https://github.com/DioxusLabs/blitz + Copyright DioxusLabs contributors. MIT OR Apache-2.0. engine/vendor/blitz-paint is a modified copy of + packages/blitz-paint (text-shadow painting, tiled-gradient limit); see its Cargo.toml and licence files. + +pi: https://github.com/nktkt/pi (a Rust port of https://github.com/earendil-works/pi) + MIT. agent/crates/pi-ai and pi-agent are copies with changes listed in agent/crates/NOTICE.md + (licence: agent/crates/LICENSE-pi-rust-port). + +muxide: media/vendor/muxide, MIT OR Apache-2.0 (its LICENSE-MIT and LICENSE-APACHE). + +GSAP compatibility: engine/src/gsap_shim.js and engine/src/gsap.rs are an independent implementation of the GSAP + authoring API, evaluated with animato. No GSAP code is included. GSAP is a trademark of GreenSock / Webflow. + +WebGL (the engine's `webgl` feature, engine/vendor/angle): prebuilt dynamic libraries taken unmodified from the + Electron 38.4.0 release for darwin-arm64 (Chromium 140). libEGL.dylib and libGLESv2.dylib are ANGLE + (https://chromium.googlesource.com/angle/angle, BSD-3-Clause, Copyright The ANGLE Project Authors); + libvk_swiftshader.dylib and vk_swiftshader_icd.json are SwiftShader (https://swiftshader.googlesource.com/SwiftShader, + Apache-2.0, Copyright The SwiftShader Authors). Electron is MIT (engine/vendor/angle/LICENSE.electron); the Chromium + third-party notices are in engine/vendor/angle/LICENSES.chromium.html. They are loaded at run time through EGL and + are not linked into the binary. + +animato (MIT OR Apache-2.0), Stylo (MPL-2.0), Vello (Apache-2.0 OR MIT), Boa (MIT OR Unlicense), usvg (Apache-2.0 OR +MIT), mediabunny (MPL-2.0, used unmodified), manifold-rust (Apache-2.0), Bevy (MIT OR Apache-2.0) and the other +crates and packages in each Cargo.lock and package.json, each under its own licence. diff --git a/README.md b/README.md new file mode 100644 index 00000000..b50dc004 --- /dev/null +++ b/README.md @@ -0,0 +1,123 @@ +

+ + + raea's cat + +

+ +

raea

+ +

Render Anything Engine (for Anyone)

+ +

+ One GPU engine for video, motion, games, 3D and documents, written as React and TypeScript,
+ rendered faster than it plays, on the device you already own. +

+ +

+ raea.io · + Why we built it · + How it works · + Settings · + Agent skill +

+ +

+ licence FSL-1.1-ALv2 + status canary + macOS, Apple Silicon +

+ +--- + +> **Canary.** raea is in active development and changes daily. It builds and renders on a Mac with Apple Silicon, +> and parts of it are rough. Expect breaking changes, missing docs, and things that only work the way we use them. + +## What it is + +raea renders compositions: React components that draw a frame for a given moment, written with `@raea/motion`. +The engine runs them inside [Bevy](https://bevyengine.org) on the GPU, composites video with fused compute kernels, +encodes in hardware, and keeps everything it drew as data you can query. The same file renders to an MP4, plays live +as a game, or renders one frame for an agent to look at. + +```tsx +import { AbsoluteFill, Composition, interpolate, registerRoot, useCurrentFrame } from "@raea/motion"; + +function Hello() { + const f = useCurrentFrame(); + return Hello; +} + +registerRoot(() => ); +``` + +```sh +raea-motion render hello.tsx -o hello.mp4 +``` + +**void** is the Mac app built on raea: a black window you talk to. Describe a reel, a promo or a game; its agent +writes the composition, renders it, checks the frames and the sound, and plays it on its stage. + +## Get started + +Requirements: macOS on Apple Silicon, [Rust](https://rustup.rs) (stable), [bun](https://bun.sh), Xcode command-line +tools. + +```sh +git clone https://github.com/shinyobjectz/raea && cd raea + +# the CLI: render, play, run and test compositions +cd react && cargo build --release --bin raea-motion && cd .. +react/target/release/raea-motion render react/bench/games/pong/edit.tsx -o pong.mp4 + +# void, the Mac app +cd void && cargo build --release && ./target/release/void +``` + +void's agent needs a model. Put a key in `~/.raea/env`; OpenRouter is the default, and Anthropic, Z.ai, DeepSeek, +Moonshot or any Anthropic-compatible endpoint work through `RAEA_LLM_PROVIDER`: + +```sh +mkdir -p ~/.raea && echo "OPENROUTER_API_KEY=sk-or-..." >> ~/.raea/env +``` + +Everything else is optional; [docs/settings.md](docs/settings.md) lists every setting, and how to run the small API +behind generated music and speech yourself. + +## Use it from your agent + +- **Agent skill.** `skills/raea/SKILL.md` teaches any agent to write, render and check raea compositions. + `skills/raea-bevy` covers 3D and games drawn by Bevy. +- **Claude Code plugin.** `/plugin marketplace add shinyobjectz/raea`, then `/plugin install raea@raea`. +- **MCP.** With void running, `claude mcp add --transport http void http://127.0.0.1:7457/mcp` gives an agent void's + tools: `state`, `screenshot`, `send`, `act`, `wait`, `logs`, `hear`, `say`. + +## What's in here + +| Folder | What | +|---|---| +| [`engine/`](engine) | The core crate (`raea`): HTML and DOM rendering (Blitz, Stylo, Vello), compositing, fonts, the GPU | +| [`react/`](react) | `raea-motion`: runs `@raea/motion` compositions in Bevy; render, play, run, test; the iPhone bindings | +| [`motion/`](motion) | `@raea/motion`, the TypeScript SDK: its spec, conformance suite and source | +| [`rdb/`](rdb) | Loading and rendering an edit, its assets and generated sound; previz before render | +| [`kgpu/`](kgpu) | K on the GPU: a small array language compiled to WGSL, bit-exact with its interpreter | +| [`media/`](media) | Decode and encode behind one seam: VideoToolbox, AV1, a muxer | +| [`perception/`](perception) | Reading footage the way an editor does: faces, speech, shots, motion | +| [`meaning/`](meaning) | Frame embeddings and hyperdimensional computing over them | +| [`void/`](void) | void, the Mac app: the terminal, the stage, the agent, its MCP server | +| [`agent/`](agent) | The agent runtime and its multi-provider model layer | +| [`native/`](native), [`modules/`](modules) | The JavaScript engine's native calls and module loader | +| [`score/`](score), [`brief/`](brief) | A brief split into beats, and the notation an edit is planned in | +| [`browser/`](browser), [`shell/`](shell), [`data/`](data), [`cli/`](cli) | The agent's browser, shell, project record and part library | +| [`sandbox/`](sandbox), [`ios-probe/`](ios-probe), [`gputrace/`](gputrace) | The iPhone sandbox and probe, GPU telemetry | +| [`tabular/`](tabular) | Tabular models over what perception and embeddings measured | +| [`skills/`](skills) | Agent skills for working in raea | +| [`docs/`](docs) | Cross-cutting docs and [settings](docs/settings.md) | + +Most folders carry a `.feature` file: the spec for that part, written as behaviour, with what was measured. + +## Licence + +raea is under the [Functional Source License 1.1, ALv2 Future License](LICENSE.md) (FSL-1.1-ALv2): use it, change +it and build on it for anything except a competing product or service. Each release becomes Apache 2.0 two years +after it ships. Third-party parts keep their own licences; see [NOTICE](NOTICE). diff --git a/agent/.gitignore b/agent/.gitignore new file mode 100644 index 00000000..eb5a316c --- /dev/null +++ b/agent/.gitignore @@ -0,0 +1 @@ +target diff --git a/agent/Cargo.lock b/agent/Cargo.lock new file mode 100644 index 00000000..19e9f862 --- /dev/null +++ b/agent/Cargo.lock @@ -0,0 +1,1774 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "eventsource-stream" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74fef4569247a5f429d9156b9d0a2599914385dd189c539334c625d8099d90ab" +dependencies = [ + "futures-core", + "nom", + "pin-project-lite", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "globset" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ignore" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b69833ed729dc5aa7d19541d96d6cf8e9137194207a04916d658e43168402f" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pi-agent" +version = "1.2.0" +dependencies = [ + "anyhow", + "async-stream", + "async-trait", + "chrono", + "futures", + "glob", + "ignore", + "pi-ai", + "regex", + "reqwest", + "serde", + "serde_json", + "shell-words", + "similar", + "thiserror 1.0.69", + "tokio", + "tokio-util", + "tracing", + "uuid", +] + +[[package]] +name = "pi-ai" +version = "1.2.0" +dependencies = [ + "async-stream", + "async-trait", + "bytes", + "chrono", + "eventsource-stream", + "futures", + "reqwest", + "serde", + "serde_json", + "thiserror 1.0.69", + "tokio", + "tokio-util", + "tracing", + "url", + "uuid", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raea-spec" +version = "0.1.0" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/agent/Cargo.toml b/agent/Cargo.toml new file mode 100644 index 00000000..fdecd874 --- /dev/null +++ b/agent/Cargo.toml @@ -0,0 +1,35 @@ +# raea's agent (agent.feature): pi's agent loop (the vendored Rust port, crates/pi-ai and crates/pi-agent, MIT; see +# crates/NOTICE.md) and raea-spec (Gherkin for the harness). Moved from ~/host/agent on 2026-10-15 (agent.feature +# phase 2); the host app's ugc-agent, ugc-core and ugc-eval depend on them by path. +[workspace] +resolver = "2" +members = ["crates/pi-ai", "crates/pi-agent", "crates/raea-spec"] + +[workspace.package] +version = "1.2.0" +edition = "2021" +rust-version = "1.80" +license = "MIT" +repository = "https://github.com/earendil-works/pi" +authors = ["Pi Rust Port Contributors"] + +[workspace.dependencies] +tokio = { version = "1.40", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util", "net"] } +tokio-util = { version = "0.7", features = ["rt"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] } +eventsource-stream = "0.2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +async-trait = "0.1" +futures = "0.3" +thiserror = "1" +anyhow = "1" +tracing = "0.1" +chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } +async-stream = "0.3" +bytes = "1" +url = "2" +uuid = { version = "1", features = ["v4"] } +glob = "0.3" +ignore = "0.4" +shell-words = "1" diff --git a/agent/agent.feature b/agent/agent.feature new file mode 100644 index 00000000..e204fe0d --- /dev/null +++ b/agent/agent.feature @@ -0,0 +1,105 @@ +Feature: One editing agent, two hosts: raea's harness and the host app's Agent + Status 2026-10-14: design, approved by the user ("whatever you design for the agent i approve"). Nothing has moved + yet; the phases below say what moves when and how each step is checked. + + The founder, 2026-10-14: all video editing work should move to raea; the the host app Agent stays (it is specific to that + app and is how editing gets tested today), but raea should have its own harness agent, without the two drifting, + and the host app's API is in the loop. + + Background: + Given how things stand on 2026-10-14 + | piece | where | size | what it is | + | the loop | ~/host/agent/crates/pi-agent | 2.0k lines | pi's agent runtime, vendored Rust port (MIT): streaming loop, tool calls, permissions | + | the providers | ~/host/agent/crates/pi-ai | 3.2k lines | Anthropic, OpenAI, Gemini, any OpenAI-compatible endpoint | + | the host app's Agent | ~/host/agent/crates/ugc-agent | 38k lines | pi's loop + 30 tools + sessions + the C interface for Swift | + | the evals | ~/host/agent/crates/ugc-eval | 7.1k lines | real MiniMax M3 through your raea API, real projects and renders, graded | + | Gherkin for the harness | ~/host/agent/crates/ugc-spec | 1.0k lines | Features/Rules/Scenarios shared by ugc-eval and the prompt build | + | the embedder | ~/host/agent/crates/ugc-embed | 0.7k lines | SigLIP 2 on ONNX; raea/meaning depends on it (the wrong way round) | + | raea's edit verbs | raea/rrl (agent.rs, memory.rs, recall.rs) | 4.3k lines | apply/undo/schema/at over an .rrl edit, guarded, with memory | + | raea's overnight loop | raea/rrl/examples/overnight | | ugc-eval (the host app's real Agent) driving rrl edits, scored by hidden expects | + And host already depends on raea by path (ugc-agent and ugc-core use ../../../../raea/engine), and + ~/host/framework is a symlink to raea/engine, so "the host app uses raea" is the existing direction + + Rule: Dependencies point one way: the host app depends on raea, never the reverse + Scenario: What raea owns after the move + Then raea owns everything an editing agent needs that isn't about the host app the business: + | moves to raea | as | why | + | pi-ai, pi-agent | raea/agent/pi-ai, raea/agent/pi-agent | a generic loop and providers; both hosts need them | + | ugc-spec | raea/agent/spec | Gherkin for rules and evals; raea's docs are Gherkin too | + | ugc-embed | raea/meaning/embed | the meaning plane's model; removes raea -> host | + | the editing tools | raea/agent/tools (crate raea-agent) | cut, edit, footage, look, music, performance, scene, review, versions, brief, read, write, and the shell's probe/lint/snapshot/render | + | the editing prompt parts | raea/agent/prompts/editing.feature | the house editing rules, with their scenarios as evals | + | the editing eval scenarios | raea/agent/evals | one bank both hosts are graded on (the overnight bank joins it) | + And the host app keeps what is about the host app: sessions and the Swift interface (ffi.rs), the business tools (advice, + brainstorm, clients, inbox, inspo, invoices, rate_card, references, site, tasks, web_fetch, web_search, + canvas, watch, plan, script_check), Kelly's knowledge, the persona prompts, ugc-runner and the app-only evals + And a tool whose side is unclear when its turn comes is decided by one test: does it need a the host app account, + project store or business record? If not, it is editing and moves + + Rule: Two hosts compose the same pieces, so there is nothing to drift + Scenario: The two hosts + Then the host app's Agent is pi's loop + raea_agent::editing_tools(ctx) + its own tools + its prompts, as today + And raea's harness is a binary, `raea agent`, that is pi's loop + raea_agent::editing_tools(ctx) + a project + folder + raea's editing prompt; no the host app code at all + And the model is a pi-ai provider either way: your raea API (the the host app proxy, MiniMax M3 today) is one + provider config (base URL + token), direct Anthropic/OpenAI/OpenRouter keys are others; the harness reads + RAEA_AGENT_PROVIDER, so using the the host app API from raea is a setting, not a dependency + + Scenario: Checks that catch drift + Then a contract test in raea snapshots the editing tools' names, descriptions and JSON schemas, and the host app's + build runs the same test against its composed tool list: a tool changed in one host fails the other's build + And the editing eval bank runs against both hosts in the overnight loop; the same scenario failing on one host + and passing on the other is reported as drift, not as a regression + And the editing prompt's markdown is generated from raea/agent/prompts/editing.feature and included by UGC + Pro's prompt build, byte-stable (the chat_is_todays_base_md test keeps passing) + + Rule: The move is staged; each phase ends with both hosts building and their evals unchanged + Scenario: Phase 1 done (2026-10-15) + Given ugc-embed moved to raea/meaning/embed (its version, edition and licence written out, no longer inherited + from host's workspace), raea/meaning depending on it by `path = "embed"`, and ~/host/agent/crates/ugc-embed a + symlink to it that is no longer a workspace member (no crate there depends on it) + Then raea-meaning builds against it and writes a byte-identical SigLIP column (broll-screen.mov at 8 a second, + against the column ingest stored before the move) + And `cargo check -p ugc-core -p ugc-eval` in ~/host/agent is green without it; raea no longer depends on host + And host's Cargo.lock drops the crate the next time anyone builds (left uncommitted here: another session had + uncommitted changes in it) + + Scenario: raea's names are UGC-agnostic (2026-10-15) + Given the user: raea will cover gaming as well as video, so its libraries don't carry the host app's name + Then ugc-embed is raea-embed (package, lib raea_embed, binary raea-embed; a ugc-embed binary stays as an alias for + the host app's knowledge scripts), and the model folder is ~/.local/share/raea-models (RAEA_MODELS, else UGC_MODELS; + ~/.local/share/ugc-models is a symlink to it) + And the SigLIP column it writes is byte-identical to before (broll-screen.mov at 8 a second) + And the editing agent's crate is raea-agent (this file's phases); the host app's agent keeps its own name, being UGC + Pro's; perception's Core ML packages still come from ~/host/models (UGC_MODELS), the apps' own folder + + Scenario: Phases + Then phase 1: ugc-embed moves to raea/meaning/embed; host's Cargo paths point at it; raea/meaning and + host's ad cards build and `ugc-embed check` passes (cosine 0.99 on 200 frames) + And phase 2: pi-ai, pi-agent and ugc-spec move to raea/agent; host's workspace members become path + dependencies; `cargo test` green in both; the xcframework builds; one eval round unchanged + And phase 3: the editing tools move one at a time (footage, then cut, look, scene, music, performance, review, + versions, brief, edit), each with its tests, behind raea_agent::editing_tools; the contract test lands with + the first one + And phase 4: `raea agent` runs the editing eval bank end to end on your raea API and on one direct provider; + the overnight loop grades both hosts + And every phase is a commit in each repo, and nothing is deleted from host until its replacement is green + + Scenario: Phase 2 done (2026-10-15) + Given pi-ai, pi-agent and ugc-spec copied from host's HEAD into raea/agent/crates (ugc-spec renamed raea-spec; + nothing depended on it), their own workspace with host's workspace.package and dependencies; the pi port's + NOTICE.md and licence beside them; host's ugc-agent and ugc-eval depending on them by path + (../../../../raea/agent/crates), its workspace members down to ugc-agent, ugc-core, ugc-eval and ugc-runner, and + ugc-spec's lock entry gone (the lockfile kept at format 3) + When it was built and tested in a host worktree first (the shared target, so nothing rebuilt from scratch), + against the same tests run in the main checkout without the move + Then raea/agent: `cargo test` passes but raea-spec's every-feature-parses test, which reads the host's Gherkin + (RAEA_SPEC_REPO, else ~/host; raea's own docs wrap their steps) and fails on host's + docs/new-project-flow.feature as ugc-spec's did before the move + And host: the same with and without it (ugc-agent 228 and its integration tests, ugc-eval 23, ugc-runner 4 pass; + renderer.rs lint_and_probe_in_process fails in both, the scene gate refusing its render) + And HostCore's iPhone and Simulator slices build (1 min 51 s, 2 min 34 s) + And an eval round on the moved crates passes: app-management-01-due-and-status 5/5, settings-01-accent-colour + 4/4, teaching-01-what-is-a-hook 3/3; pi-ai and pi-agent are byte-identical to host's, so the agent can't + behave differently + And so host's crates/pi-ai, pi-agent and ugc-spec are deleted (host 751a4ce, raea's copy first) diff --git a/agent/crates/LICENSE-pi-rust-port b/agent/crates/LICENSE-pi-rust-port new file mode 100644 index 00000000..4da4068c --- /dev/null +++ b/agent/crates/LICENSE-pi-rust-port @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 pi (Rust port) 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. diff --git a/agent/crates/NOTICE.md b/agent/crates/NOTICE.md new file mode 100644 index 00000000..39648c91 --- /dev/null +++ b/agent/crates/NOTICE.md @@ -0,0 +1,11 @@ +# Third-party code + +`pi-ai/` and `pi-agent/` are copied from the Rust port of pi, https://github.com/nktkt/pi at commit +0808c75 (1.2.0, 2026-05-12), itself a port of https://github.com/earendil-works/pi. MIT License, +see `LICENSE-pi-rust-port`. Changes in this copy: removed the `bash` and `web_fetch` tools; the +workspace's dependency features are trimmed for iOS. +- `pi-ai/src/providers/anthropic.rs`: also reads input and cache token counts from `message_delta` + (MiniMax's Anthropic-compatible API reports them there). + +- pi-agent: `AgentConfig::keep_images` — only the newest N tool-result images are sent to the model; older ones are replaced by a one-line placeholder (they stay in the saved conversation). Added for the host app. +- pi-agent: `AgentConfig::compact_at_chars` — past that size, tool results and long tool-call string arguments older than the last 6 are shortened in one pass, at most once per 50% growth (keeps the prompt-cache prefix stable between compactions). Added for the host app. diff --git a/agent/crates/pi-agent/Cargo.toml b/agent/crates/pi-agent/Cargo.toml new file mode 100644 index 00000000..6b700726 --- /dev/null +++ b/agent/crates/pi-agent/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "pi-agent" +description = "Agent runtime with tool calling (Rust port of @earendil-works/pi-agent-core). Streaming agent loop, permission policy, built-in tools (read/write/edit/bash/grep/glob/web_fetch/todo)." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +readme = "README.md" +keywords = ["llm", "ai", "agent", "tools", "coding-agent"] +categories = ["asynchronous", "api-bindings"] + +[dependencies] +pi-ai = { path = "../pi-ai", version = "1.2.0" } +tokio = { workspace = true } +tokio-util = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +async-trait = { workspace = true } +futures = { workspace = true } +thiserror = { workspace = true } +anyhow = { workspace = true } +tracing = { workspace = true } +chrono = { workspace = true } +async-stream = { workspace = true } +uuid = { workspace = true } +glob = { workspace = true } +ignore = { workspace = true } +shell-words = { workspace = true } +reqwest = { workspace = true } +similar = "2.7" +regex = "1.10" diff --git a/agent/crates/pi-agent/README.md b/agent/crates/pi-agent/README.md new file mode 100644 index 00000000..924f9752 --- /dev/null +++ b/agent/crates/pi-agent/README.md @@ -0,0 +1,44 @@ +# pi-agent + +Agent runtime with tool calling. Part of the +[`pi`](https://github.com/nktkt/pi) agent harness — a Rust port of +[`@earendil-works/pi-agent-core`](https://github.com/earendil-works/pi). + +Builds on [`pi-ai`](https://crates.io/crates/pi-ai) and adds: + +- `run_agent` / `run_agent_with_history` — streaming agent loop with sequential + tool execution. +- `AgentTool` trait — implement once, plug in via `AgentConfig::with_tools`. +- `PermissionPolicy` trait with `Allow` / `AllowSession` / `Deny` — + tools that flag `requires_permission()` (e.g. `bash`, `write`, `edit`) are + gated. +- Streaming `AgentEvent::TextDelta` / `ThinkingDelta` / + `ToolExecutionStart` / `ToolExecutionEnd` events through an + `mpsc::UnboundedSender`. +- Built-in tools under `pi_agent::tools::*`: `read`, `write`, `edit`, + `bash`, `ls`, `grep`, `glob_tool`, `web_fetch`, `todo`. Pre-bundled as + `pi_agent::tools::default_tools()`. + +## Quick start + +```rust +use pi_agent::{run_agent, tools::default_tools, AgentConfig}; +use pi_ai::{Message, Model}; + +# tokio_test::block_on(async { +let cfg = AgentConfig::new( + Model::anthropic_claude_sonnet_4_6(), + "You are a helpful coding assistant.", +) +.with_tools(default_tools()) +.with_max_turns(8); + +let user = Message::user_text("List the .rs files in the current directory."); +let run = run_agent(&cfg, user, None).await.unwrap(); +println!("{} messages", run.messages.len()); +# }); +``` + +## License + +MIT diff --git a/agent/crates/pi-agent/src/agent_loop.rs b/agent/crates/pi-agent/src/agent_loop.rs new file mode 100644 index 00000000..f6ec290a --- /dev/null +++ b/agent/crates/pi-agent/src/agent_loop.rs @@ -0,0 +1,470 @@ +//! Agent loop — Rust port of `packages/agent/src/agent-loop.ts`. +//! +//! Streams assistant deltas, executes tool calls, and surfaces permission +//! decisions. Cancellation is honored via `StreamOptions::cancel`. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use futures::StreamExt; +use pi_ai::{ + stream_simple, AssistantMessageEvent, Content, Context, Message, StopReason, ToolResultMessage, +}; +use serde_json::Value; +use tokio::sync::mpsc; +use tracing::instrument; + +use crate::error::{AgentError, Result}; +use crate::types::{AgentConfig, AgentEvent, AgentTool, AgentToolResult, PermissionDecision}; + +pub struct AgentRun { + pub messages: Vec, + pub stopped_at_turn_limit: bool, +} + +/// What a turn ends with when the reply stream was cut off twice in a row (a dropped connection, not an answer). +pub const REPLY_CUT_OFF: &str = "My reply was cut off before it finished (the connection dropped twice), so I stopped there. \ + Send your message again and I'll pick it up."; + +/// What a tool call cut off by the output limit is answered with: with a size, since "smaller pieces" alone got five +/// whole rewrites in a row (output-limit-mid-write, 2026-10-13). +pub fn cut_off(limit: u32) -> String { + format!("Not run: your reply reached the output limit ({limit} tokens) before this call's arguments were finished, so \ + nothing was written or changed. Do it in smaller pieces, about {} lines per call: write the start of a big file, then \ + add the rest with edit, one piece per call. Don't send the whole thing again.", (limit / 20).max(5)) +} + +/// Gives every assistant tool call that has no result a "not run" error result, right after its message's other results. +/// Returns how many it added. The provider rejects a conversation with an unanswered call. +pub fn answer_unanswered(messages: &mut Vec) -> usize { + let mut out = Vec::with_capacity(messages.len()); + let mut added = 0; + let mut rest = std::mem::take(messages).into_iter().peekable(); + while let Some(m) = rest.next() { + let calls: Vec<(String, String)> = match &m { + Message::Assistant(a) => a.content.iter().filter_map(|c| match c { + Content::ToolCall { id, name, .. } => Some((id.clone(), name.clone())), + _ => None, + }).collect(), + _ => Vec::new(), + }; + out.push(m); + if calls.is_empty() { continue; } + let mut answered = HashSet::new(); + while let Some(Message::ToolResult(tr)) = rest.peek() { + answered.insert(tr.tool_call_id.clone()); + out.push(rest.next().unwrap()); + } + for (id, name) in calls { + if answered.contains(&id) { continue; } + out.push(Message::ToolResult(ToolResultMessage { + tool_call_id: id, tool_name: name, is_error: true, timestamp: pi_ai::now_ms(), + content: vec![Content::text("Not run: the turn ended before this call finished.")], + })); + added += 1; + } + } + *messages = out; + added +} + +#[instrument(skip(config, initial_prompt, events), fields(model = %config.model.id))] +pub async fn run_agent( + config: &AgentConfig, + initial_prompt: Message, + events: Option>, +) -> Result { + run_agent_with_history(config, vec![initial_prompt], events).await +} + +/// The request a run's first step sends for this transcript, built as the loop builds it. A speculative turn (T-200) +/// sends it early and hands its stream back as `seeded_stream`, so the run starts exactly where that request left off. +pub fn first_request(config: &AgentConfig, mut messages: Vec) -> (Context, pi_ai::StreamOptions) { + answer_unanswered(&mut messages); + if conversation_chars(&messages) > config.compact_at_chars { compact(&mut messages, 6); } + let ctx = Context { + system_prompt: Some(config.system_prompt.clone()), + system_suffix: (!config.system_suffix.is_empty()).then(|| config.system_suffix.clone()), + trailing: (!config.trailing.is_empty()).then(|| config.trailing.clone()), + messages: with_recent_images(&messages, config.keep_images), + tools: config.tools.iter().map(|t| crate::types::tool_def(t.as_ref())).collect(), + }; + let mut options = config.stream_options.clone(); + if options.reasoning.is_none() && config.thinking_level != pi_ai::ThinkingLevel::Off { + options.reasoning = Some(config.thinking_level); + } + (ctx, options) +} + +/// Continue a run with an existing transcript. Use this for `pi --resume`. +pub async fn run_agent_with_history( + config: &AgentConfig, + mut messages: Vec, + events: Option>, +) -> Result { + answer_unanswered(&mut messages); + if let Some(last) = messages.last().cloned() { + emit(&events, AgentEvent::UserMessage { message: last }); + } + emit(&events, AgentEvent::AgentStart); + + let tool_index: HashMap> = config + .tools + .iter() + .map(|t| (t.name().to_string(), t.clone())) + .collect(); + let tool_defs: Vec = config + .tools + .iter() + .map(|t| crate::types::tool_def(t.as_ref())) + .collect(); + + let mut session_allowed: HashSet = HashSet::new(); + let mut compacted_size = 0usize; + let mut turn: u32 = 0; + let mut stopped_at_turn_limit = false; + let mut asked_before_reply = false; + let mut seed = config.seeded_stream.as_ref().and_then(|s| s.take()); + + 'outer: while turn < config.max_turns { + turn += 1; + emit(&events, AgentEvent::TurnStart); + + // Compact rarely: past the limit, and only once the conversation has grown half again since the last + // compaction (each one costs a prompt-cache miss; doing it every step costs more than it saves). + let size = conversation_chars(&messages); + if size > config.compact_at_chars && size > compacted_size + compacted_size / 2 { + compact(&mut messages, 6); + compacted_size = conversation_chars(&messages); + } + let ctx = Context { + system_prompt: Some(config.system_prompt.clone()), + system_suffix: (!config.system_suffix.is_empty()).then(|| config.system_suffix.clone()), + trailing: (!config.trailing.is_empty()).then(|| config.trailing.clone()), + messages: with_recent_images(&messages, config.keep_images), + tools: tool_defs.clone(), + }; + + let mut options = config.stream_options.clone(); + if options.reasoning.is_none() && config.thinking_level != pi_ai::ThinkingLevel::Off { + options.reasoning = Some(config.thinking_level); + } + + let mut drops = 0; + let (stop, msg) = loop { + // A speculative turn's stream (T-200) stands in for the first call: what it buffered comes out at once. + let mut stream = match seed.take() { Some(s) => s, None => stream_simple(&config.model, &ctx, &options).await? }; + + let mut final_message: Option = None; + let mut stop = StopReason::Stop; + let mut ended_early = false; + + while let Some(ev) = stream.next().await { + let ev = match ev { + // A dropped connection: retry this step once rather than end the turn on half a reply. + Err(pi_ai::Error::InvalidResponse(m)) if m == pi_ai::STREAM_ENDED_EARLY => { ended_early = true; break; } + other => other?, + }; + match ev { + AssistantMessageEvent::Done { reason, message } => { + stop = reason; + final_message = Some(message); + break; + } + AssistantMessageEvent::Error { reason: _, error } => { + let err_msg = error + .error_message + .clone() + .unwrap_or_else(|| "provider error".into()); + return Err(AgentError::Other(err_msg)); + } + AssistantMessageEvent::TextDelta { delta, .. } => { + emit(&events, AgentEvent::TextDelta { delta }); + } + AssistantMessageEvent::ThinkingDelta { delta, .. } => { + emit(&events, AgentEvent::ThinkingDelta { delta }); + } + _ => {} + } + } + + if ended_early { + drops += 1; + if drops < 2 { continue; } + return Err(AgentError::Other(REPLY_CUT_OFF.into())); + } + let Some(msg) = final_message else { + return Err(AgentError::Other( + "provider stream produced no terminal event".into(), + )); + }; + break (stop, msg); + }; + + let assistant_message = Message::Assistant(msg.clone()); + messages.push(assistant_message.clone()); + emit( + &events, + AgentEvent::AssistantMessage { + message: assistant_message, + }, + ); + + let tool_calls: Vec<(String, String, Value)> = msg + .content + .iter() + .filter_map(|c| match c { + Content::ToolCall { + id, + name, + arguments, + } => Some((id.clone(), name.clone(), arguments.clone())), + _ => None, + }) + .collect(); + + if !tool_calls.is_empty() && stop == StopReason::Length { + // The reply hit the output limit inside a tool call: its arguments are cut off, so nothing runs. Answer every + // call (a call without a result makes the provider reject the conversation from here on) and go on, so the + // model can redo it in smaller pieces. + let limit = config.stream_options.max_tokens.unwrap_or(config.model.max_tokens); + for (id, name, args) in tool_calls { + let content = vec![Content::text(cut_off(limit))]; + emit(&events, AgentEvent::ToolExecutionStart { tool_call_id: id.clone(), tool_name: name.clone(), args }); + emit(&events, AgentEvent::ToolExecutionEnd { tool_call_id: id.clone(), tool_name: name.clone(), is_error: true, content: content.clone() }); + messages.push(Message::ToolResult(ToolResultMessage { tool_call_id: id, tool_name: name, content, is_error: true, timestamp: pi_ai::now_ms() })); + } + emit(&events, AgentEvent::TurnEnd); + continue 'outer; + } + if tool_calls.is_empty() || stop != StopReason::ToolUse { + // A reply that would end the run: once per run, and only with a step left to act on, the caller may send the + // model back with what's still unfinished, as a user message, instead of ending here (T-141). + if tool_calls.is_empty() && !asked_before_reply && turn < config.max_turns + && !matches!(stop, StopReason::Error | StopReason::Aborted) { + if let Some(hook) = &config.before_reply { + asked_before_reply = true; + if let Some(text) = hook(messages.as_slice()).await { + let note = Message::User { content: vec![Content::text(text)], timestamp: pi_ai::now_ms() }; + messages.push(note.clone()); + emit(&events, AgentEvent::UserMessage { message: note }); + emit(&events, AgentEvent::TurnEnd); + continue 'outer; + } + } + } + emit(&events, AgentEvent::TurnEnd); + break 'outer; + } + + let mut any_terminate = !tool_calls.is_empty(); + for (id, name, args) in tool_calls { + // Permission gate (only for tools that require it, and only once + // per name per run if the user said "allow session"). + let tool_obj = tool_index.get(&name); + let needs_perm = tool_obj.map(|t| t.requires_permission()).unwrap_or(false) + && !session_allowed.contains(&name); + if needs_perm { + match config.permission.check(&name, &args).await { + PermissionDecision::Allow => {} + PermissionDecision::AllowSession => { + session_allowed.insert(name.clone()); + } + PermissionDecision::Deny { reason } => { + emit( + &events, + AgentEvent::PermissionDenied { + tool_name: name.clone(), + reason: reason.clone(), + }, + ); + let tr = ToolResultMessage { + tool_call_id: id, + tool_name: name, + content: vec![Content::text(format!("permission denied: {reason}"))], + is_error: true, + timestamp: pi_ai::now_ms(), + }; + messages.push(Message::ToolResult(tr)); + any_terminate = false; + continue; + } + } + } + + emit( + &events, + AgentEvent::ToolExecutionStart { + tool_call_id: id.clone(), + tool_name: name.clone(), + args: args.clone(), + }, + ); + let (content, is_error, terminate) = match tool_obj { + Some(tool) => match tool.execute(&id, args).await { + Ok(AgentToolResult { + content, + details: _, + terminate, + }) => (content, false, terminate), + Err(e) => (vec![Content::text(format!("tool error: {e}"))], true, false), + }, + None => ( + vec![Content::text(format!("unknown tool: {name}"))], + true, + false, + ), + }; + if !terminate { + any_terminate = false; + } + emit( + &events, + AgentEvent::ToolExecutionEnd { + tool_call_id: id.clone(), + tool_name: name.clone(), + is_error, + content: content.clone(), + }, + ); + let tr = ToolResultMessage { + tool_call_id: id, + tool_name: name, + content, + is_error, + timestamp: pi_ai::now_ms(), + }; + messages.push(Message::ToolResult(tr)); + } + if let Some((left, note)) = &config.wrap_up { + if config.max_turns.saturating_sub(turn) == *left { + if let Some(Message::ToolResult(tr)) = messages.last_mut() { tr.content.push(Content::text(note.clone())); } + } + } + emit(&events, AgentEvent::TurnEnd); + if any_terminate { + break; + } + } + + if turn >= config.max_turns { + stopped_at_turn_limit = true; + } + + emit( + &events, + AgentEvent::AgentEnd { + messages: messages.clone(), + }, + ); + Ok(AgentRun { + messages, + stopped_at_turn_limit, + }) +} + +fn emit(sink: &Option>, ev: AgentEvent) { + if let Some(s) = sink { + let _ = s.send(ev); + } +} + +/// The conversation with all but the newest `keep` images in tool results replaced by a placeholder. +fn with_recent_images(messages: &[Message], keep: usize) -> Vec { + let total: usize = messages.iter().map(|m| match m { + Message::ToolResult(t) => t.content.iter().filter(|c| matches!(c, Content::Image { .. })).count(), + _ => 0, + }).sum(); + if total <= keep { return messages.to_vec(); } + let mut drop = total - keep; + messages.iter().map(|m| match m { + Message::ToolResult(t) if drop > 0 && t.content.iter().any(|c| matches!(c, Content::Image { .. })) => { + let mut t = t.clone(); + t.content = t.content.into_iter().map(|c| match c { + Content::Image { .. } if drop > 0 => { drop -= 1; Content::Text { text: "[an earlier image, no longer shown]".into() } } + other => other, + }).collect(); + Message::ToolResult(t) + } + other => other.clone(), + }).collect() +} + +/// Characters of text in the conversation (images not counted: they're limited separately). +fn conversation_chars(messages: &[Message]) -> usize { + fn content(c: &[Content]) -> usize { + c.iter().map(|x| match x { + Content::Text { text } => text.len(), + Content::ToolCall { arguments, .. } => arguments.to_string().len(), + _ => 0, + }).sum() + } + messages.iter().map(|m| match m { + Message::User { content: c, .. } => content(c), + Message::Assistant(a) => content(&a.content), + Message::ToolResult(t) => content(&t.content), + }).sum() +} + +const TRIMMED: &str = "… [shortened to save space; run the tool again if you need this]"; + +fn shorten(text: &str, keep: usize) -> String { + if text.len() <= keep + TRIMMED.len() { return text.to_string(); } + let cut = text.char_indices().map(|(i, _)| i).take_while(|&i| i <= keep).last().unwrap_or(0); + format!("{}{TRIMMED}", &text[..cut]) +} + +/// Shortens everything but the last `keep` tool results and assistant messages: long tool outputs to their start, +/// and long string arguments of old tool calls (whole files passed to write/edit) to theirs. +fn compact(messages: &mut [Message], keep: usize) { + let results: Vec = messages.iter().enumerate().filter(|(_, m)| matches!(m, Message::ToolResult(_))).map(|(i, _)| i).collect(); + let assistants: Vec = messages.iter().enumerate().filter(|(_, m)| matches!(m, Message::Assistant(_))).map(|(i, _)| i).collect(); + let old_results: std::collections::HashSet = results.iter().rev().skip(keep).copied().collect(); + let old_assistants: std::collections::HashSet = assistants.iter().rev().skip(keep).copied().collect(); + for (i, m) in messages.iter_mut().enumerate() { + match m { + Message::ToolResult(t) if old_results.contains(&i) => { + for c in t.content.iter_mut() { + if let Content::Text { text } = c { if text.len() > 900 { *text = shorten(text, 600); } } + } + } + Message::Assistant(a) if old_assistants.contains(&i) => { + for c in a.content.iter_mut() { + if let Content::ToolCall { arguments, .. } = c { + if let Some(obj) = arguments.as_object_mut() { + for v in obj.values_mut() { + if let Some(s) = v.as_str() { if s.len() > 900 { *v = Value::String(shorten(s, 300)); } } + } + } + } + } + } + _ => {} + } + } +} + +#[cfg(test)] +mod compact_tests { + use super::*; + use pi_ai::ToolResultMessage; + + fn result(text: &str) -> Message { + Message::ToolResult(ToolResultMessage { tool_call_id: "c".into(), tool_name: "read".into(), content: vec![Content::Text { text: text.into() }], is_error: false, timestamp: 0 }) + } + + #[test] + fn compaction_shortens_only_old_bulky_parts() { + let big = "x".repeat(5000); + let mut msgs: Vec = (0..14).map(|_| result(&big)).collect(); + msgs.push(result("short")); + let before = conversation_chars(&msgs); + compact(&mut msgs, 10); + let after = conversation_chars(&msgs); + assert!(after < before - 20_000, "{before} → {after}"); // the five oldest of fifteen shrink + // The newest ten are untouched; older ones keep their start. + if let Message::ToolResult(t) = &msgs[14] { assert!(matches!(&t.content[0], Content::Text { text } if text == "short")); } + if let Message::ToolResult(t) = &msgs[13] { assert!(matches!(&t.content[0], Content::Text { text } if text.len() == 5000)); } + if let Message::ToolResult(t) = &msgs[0] { assert!(matches!(&t.content[0], Content::Text { text } if text.starts_with("xxx") && text.ends_with("need this]"))); } + } +} diff --git a/agent/crates/pi-agent/src/error.rs b/agent/crates/pi-agent/src/error.rs new file mode 100644 index 00000000..d2aa1316 --- /dev/null +++ b/agent/crates/pi-agent/src/error.rs @@ -0,0 +1,21 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum AgentError { + #[error("provider error: {0}")] + Provider(#[from] pi_ai::Error), + + #[error("tool '{tool}' failed: {message}")] + Tool { tool: String, message: String }, + + #[error("agent cancelled")] + Cancelled, + + #[error("agent reached max turns ({0})")] + MaxTurns(u32), + + #[error("{0}")] + Other(String), +} + +pub type Result = std::result::Result; diff --git a/agent/crates/pi-agent/src/lib.rs b/agent/crates/pi-agent/src/lib.rs new file mode 100644 index 00000000..8d552e27 --- /dev/null +++ b/agent/crates/pi-agent/src/lib.rs @@ -0,0 +1,19 @@ +//! `pi-agent` — Agent runtime with tool calling. +//! +//! Rust port of `@earendil-works/pi-agent-core`. Provides: +//! - [`AgentTool`] / [`AgentToolResult`] for defining tools +//! - [`AgentConfig`] for configuring a run, plus a [`PermissionPolicy`] hook +//! - [`run_agent`] / [`run_agent_with_history`] — the agent loop +//! - Builtin tools under [`tools`] + +pub mod agent_loop; +pub mod error; +pub mod tools; +pub mod types; + +pub use agent_loop::{first_request, run_agent, run_agent_with_history, AgentRun}; +pub use error::{AgentError, Result}; +pub use types::{ + tool_def, AgentConfig, AgentEvent, AgentTool, AgentToolResult, AllowAllPolicy, BeforeReply, + PermissionDecision, PermissionPolicy, SeededStream, +}; diff --git a/agent/crates/pi-agent/src/tools/edit.rs b/agent/crates/pi-agent/src/tools/edit.rs new file mode 100644 index 00000000..dd0cb7bb --- /dev/null +++ b/agent/crates/pi-agent/src/tools/edit.rs @@ -0,0 +1,94 @@ +use async_trait::async_trait; +use pi_ai::Content; +use serde_json::{json, Value}; +use similar::TextDiff; +use tokio::fs; + +use crate::types::{AgentTool, AgentToolResult}; + +pub struct EditTool; + +#[async_trait] +impl AgentTool for EditTool { + fn name(&self) -> &str { + "edit" + } + fn requires_permission(&self) -> bool { + true + } + fn description(&self) -> &str { + "Replace one occurrence (or all, with replace_all) of old_string with new_string in the file at path. Returns a unified diff of the change." + } + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "path": {"type": "string"}, + "old_string": {"type": "string"}, + "new_string": {"type": "string"}, + "replace_all": {"type": "boolean", "default": false} + }, + "required": ["path", "old_string", "new_string"] + }) + } + async fn execute(&self, _id: &str, args: Value) -> Result { + let path = args + .get("path") + .and_then(|v| v.as_str()) + .ok_or("missing 'path'")?; + let old_s = args + .get("old_string") + .and_then(|v| v.as_str()) + .ok_or("missing 'old_string'")?; + let new_s = args + .get("new_string") + .and_then(|v| v.as_str()) + .ok_or("missing 'new_string'")?; + let replace_all = args + .get("replace_all") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + + let original = fs::read_to_string(path) + .await + .map_err(|e| format!("read {path}: {e}"))?; + let count = original.matches(old_s).count(); + if count == 0 { + return Err(format!("old_string not found in {path}")); + } + if count > 1 && !replace_all { + return Err(format!( + "old_string occurs {count} times in {path}; pass replace_all=true or expand the match" + )); + } + let replaced = if replace_all { + original.replace(old_s, new_s) + } else { + original.replacen(old_s, new_s, 1) + }; + // Preserve CRLF line endings if the original used them. + let updated = if original.contains("\r\n") { + replaced.replace("\r\n", "\n").replace('\n', "\r\n") + } else { + replaced + }; + fs::write(path, &updated) + .await + .map_err(|e| format!("write {path}: {e}"))?; + let n = if replace_all { count } else { 1 }; + + let diff = TextDiff::from_lines(&original, &updated) + .unified_diff() + .header(&format!("a/{path}"), &format!("b/{path}")) + .to_string(); + + Ok(AgentToolResult { + content: vec![ + Content::text(format!("edited {path}: {n} replacement(s)")), + Content::text(diff), + ], + details: Value::Null, + terminate: false, + }) + } +} diff --git a/agent/crates/pi-agent/src/tools/glob_tool.rs b/agent/crates/pi-agent/src/tools/glob_tool.rs new file mode 100644 index 00000000..3a6f7e8f --- /dev/null +++ b/agent/crates/pi-agent/src/tools/glob_tool.rs @@ -0,0 +1,51 @@ +use async_trait::async_trait; +use serde_json::{json, Value}; + +use crate::types::{AgentTool, AgentToolResult}; + +pub struct GlobTool; + +#[async_trait] +impl AgentTool for GlobTool { + fn name(&self) -> &str { + "glob" + } + fn description(&self) -> &str { + "Expand a glob pattern (e.g. 'src/**/*.rs') and return matching paths." + } + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": {"pattern": {"type": "string"}, "max": {"type": "integer", "default": 500}}, + "required": ["pattern"] + }) + } + async fn execute(&self, _id: &str, args: Value) -> Result { + let pattern = args + .get("pattern") + .and_then(|v| v.as_str()) + .ok_or("missing 'pattern'")? + .to_string(); + let max = args.get("max").and_then(|v| v.as_u64()).unwrap_or(500) as usize; + + let result = tokio::task::spawn_blocking(move || -> Result { + let mut buf = String::new(); + let entries = glob::glob(&pattern).map_err(|e| e.to_string())?; + for (count, path) in entries.flatten().enumerate() { + if count >= max { + buf.push_str(&format!("... (truncated at {max})\n")); + break; + } + buf.push_str(&format!("{}\n", path.display())); + } + Ok(buf) + }) + .await + .map_err(|e| e.to_string())??; + Ok(AgentToolResult::text(if result.is_empty() { + "(no matches)".to_string() + } else { + result + })) + } +} diff --git a/agent/crates/pi-agent/src/tools/grep.rs b/agent/crates/pi-agent/src/tools/grep.rs new file mode 100644 index 00000000..498d32d1 --- /dev/null +++ b/agent/crates/pi-agent/src/tools/grep.rs @@ -0,0 +1,135 @@ +use async_trait::async_trait; +use ignore::WalkBuilder; +use regex::Regex; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +use std::fs; + +use crate::types::{AgentTool, AgentToolResult}; + +pub struct GrepTool; + +#[async_trait] +impl AgentTool for GrepTool { + fn name(&self) -> &str { + "grep" + } + fn description(&self) -> &str { + "Search file contents under a directory. The pattern is a regex by default; set fixed_string=true to match it literally. Supports before/after context lines. Honors .gitignore." + } + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "pattern": {"type": "string", "description": "Pattern to search for (regex by default)"}, + "path": {"type": "string", "description": "Directory to search (default: cwd)"}, + "fixed_string": {"type": "boolean", "default": false, "description": "If true, treat pattern as a literal string (escaped with regex::escape)"}, + "before": {"type": "integer", "default": 0, "description": "Number of context lines to show before each match"}, + "after": {"type": "integer", "default": 0, "description": "Number of context lines to show after each match"}, + "max_matches": {"type": "integer", "default": 200} + }, + "required": ["pattern"] + }) + } + async fn execute(&self, _id: &str, args: Value) -> Result { + let pattern = args + .get("pattern") + .and_then(|v| v.as_str()) + .ok_or("missing 'pattern'")? + .to_string(); + let path = args + .get("path") + .and_then(|v| v.as_str()) + .unwrap_or(".") + .to_string(); + let fixed_string = args + .get("fixed_string") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let before = args.get("before").and_then(|v| v.as_u64()).unwrap_or(0) as usize; + let after = args.get("after").and_then(|v| v.as_u64()).unwrap_or(0) as usize; + let max = args + .get("max_matches") + .and_then(|v| v.as_u64()) + .unwrap_or(200) as usize; + + let compiled_pattern = if fixed_string { + regex::escape(&pattern) + } else { + pattern.clone() + }; + let re = Regex::new(&compiled_pattern).map_err(|e| format!("invalid regex: {e}"))?; + + let result = tokio::task::spawn_blocking(move || -> Result { + let mut buf = String::new(); + let mut hits = 0usize; + let walker = WalkBuilder::new(&path).follow_links(false).build(); + 'outer: for entry in walker.flatten() { + if hits >= max { + break; + } + let p = entry.path(); + if !p.is_file() { + continue; + } + let text = match fs::read_to_string(p) { + Ok(t) => t, + Err(_) => continue, // skip binary or unreadable + }; + let lines: Vec<&str> = text.lines().collect(); + // Find matching line indices first. + let mut match_indices: Vec = Vec::new(); + for (i, line) in lines.iter().enumerate() { + if re.is_match(line) { + match_indices.push(i); + } + } + if match_indices.is_empty() { + continue; + } + // Cap match indices by remaining budget. + let remaining = max.saturating_sub(hits); + if match_indices.len() > remaining { + match_indices.truncate(remaining); + } + // Collect context line indices for each match. + let match_set: BTreeSet = match_indices.iter().copied().collect(); + let mut context_set: BTreeSet = BTreeSet::new(); + for &mi in &match_indices { + let start = mi.saturating_sub(before); + let end = mi.saturating_add(after).min(lines.len().saturating_sub(1)); + for k in start..=end { + context_set.insert(k); + } + } + for idx in &context_set { + let lineno = idx + 1; + let line = lines[*idx]; + let sep = if match_set.contains(idx) { ':' } else { '-' }; + buf.push_str(&format!( + "{}{}{}{}{}\n", + p.display(), + sep, + lineno, + sep, + line + )); + } + hits += match_indices.len(); + if hits >= max { + buf.push_str(&format!("... (truncated at {max} matches)\n")); + break 'outer; + } + } + Ok(buf) + }) + .await + .map_err(|e| e.to_string())??; + + Ok(AgentToolResult::text(if result.is_empty() { + "(no matches)".to_string() + } else { + result + })) + } +} diff --git a/agent/crates/pi-agent/src/tools/ls.rs b/agent/crates/pi-agent/src/tools/ls.rs new file mode 100644 index 00000000..c238c5e1 --- /dev/null +++ b/agent/crates/pi-agent/src/tools/ls.rs @@ -0,0 +1,50 @@ +use async_trait::async_trait; +use serde_json::{json, Value}; +use tokio::fs; + +use crate::types::{AgentTool, AgentToolResult}; + +pub struct LsTool; + +#[async_trait] +impl AgentTool for LsTool { + fn name(&self) -> &str { + "ls" + } + fn description(&self) -> &str { + "List entries in a directory. Returns name and kind (file/dir/symlink)." + } + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": {"path": {"type": "string"}}, + "required": ["path"] + }) + } + async fn execute(&self, _id: &str, args: Value) -> Result { + let path = args + .get("path") + .and_then(|v| v.as_str()) + .ok_or("missing 'path'")?; + let mut read = fs::read_dir(path) + .await + .map_err(|e| format!("ls {path}: {e}"))?; + let mut buf = String::new(); + while let Some(entry) = read.next_entry().await.map_err(|e| e.to_string())? { + let ft = entry.file_type().await.map_err(|e| e.to_string())?; + let kind = if ft.is_dir() { + "dir" + } else if ft.is_symlink() { + "symlink" + } else { + "file" + }; + buf.push_str(&format!( + "{}\t{}\n", + kind, + entry.file_name().to_string_lossy() + )); + } + Ok(AgentToolResult::text(buf)) + } +} diff --git a/agent/crates/pi-agent/src/tools/mod.rs b/agent/crates/pi-agent/src/tools/mod.rs new file mode 100644 index 00000000..a4b5cf87 --- /dev/null +++ b/agent/crates/pi-agent/src/tools/mod.rs @@ -0,0 +1,30 @@ +//! Builtin tools: read, write, edit, ls, grep, glob, todo. +//! +//! Mirrors the core toolset shipped in `packages/coding-agent/src/core/...`. the host app's copy drops +//! `bash` (spawns processes, which the iPhone can't) and `web_fetch` (open web access); the app's +//! own tools in `ugc-agent` replace them. + +pub mod edit; +pub mod glob_tool; +pub mod grep; +pub mod ls; +pub mod read; +pub mod todo; +pub mod write; + +use std::sync::Arc; + +use crate::types::AgentTool; + +/// Returns the default suite of builtin tools used by the coding agent. +pub fn default_tools() -> Vec> { + vec![ + Arc::new(read::ReadTool), + Arc::new(write::WriteTool), + Arc::new(edit::EditTool), + Arc::new(ls::LsTool), + Arc::new(grep::GrepTool), + Arc::new(glob_tool::GlobTool), + Arc::new(todo::TodoTool::new()), + ] +} diff --git a/agent/crates/pi-agent/src/tools/read.rs b/agent/crates/pi-agent/src/tools/read.rs new file mode 100644 index 00000000..5e9afabe --- /dev/null +++ b/agent/crates/pi-agent/src/tools/read.rs @@ -0,0 +1,57 @@ +use async_trait::async_trait; +use serde_json::{json, Value}; +use tokio::fs; + +use crate::types::{AgentTool, AgentToolResult}; + +pub struct ReadTool; + +#[async_trait] +impl AgentTool for ReadTool { + fn name(&self) -> &str { + "read" + } + fn description(&self) -> &str { + "Read the contents of a file from disk. Returns text content with optional line numbers." + } + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "path": {"type": "string", "description": "Absolute or relative path to the file"}, + "offset": {"type": "integer", "description": "Line offset (1-based), optional"}, + "limit": {"type": "integer", "description": "Max number of lines, optional"} + }, + "required": ["path"] + }) + } + async fn execute(&self, _id: &str, args: Value) -> Result { + let path = args + .get("path") + .and_then(|v| v.as_str()) + .ok_or("missing 'path'")?; + let offset = args + .get("offset") + .and_then(|v| v.as_u64()) + .map(|v| v as usize); + let limit = args + .get("limit") + .and_then(|v| v.as_u64()) + .map(|v| v as usize); + + let text = fs::read_to_string(path) + .await + .map_err(|e| format!("read {path}: {e}"))?; + let lines: Vec<&str> = text.lines().collect(); + let start = offset.map(|o| o.saturating_sub(1)).unwrap_or(0); + let end = limit + .map(|l| std::cmp::min(start + l, lines.len())) + .unwrap_or(lines.len()); + + let mut buf = String::new(); + for (i, line) in lines[start..end].iter().enumerate() { + buf.push_str(&format!("{:>5}\t{}\n", start + i + 1, line)); + } + Ok(AgentToolResult::text(buf)) + } +} diff --git a/agent/crates/pi-agent/src/tools/todo.rs b/agent/crates/pi-agent/src/tools/todo.rs new file mode 100644 index 00000000..c99b27a5 --- /dev/null +++ b/agent/crates/pi-agent/src/tools/todo.rs @@ -0,0 +1,94 @@ +//! Lightweight in-memory todo list shared across one agent run. The model can +//! `add`, `complete`, `list`, or `clear` items. Useful for long-horizon tasks. + +use std::sync::Mutex; + +use async_trait::async_trait; +use serde_json::{json, Value}; + +use crate::types::{AgentTool, AgentToolResult}; + +#[derive(Default)] +pub struct TodoTool { + items: Mutex>, +} + +#[derive(Clone)] +struct TodoItem { + text: String, + done: bool, +} + +impl TodoTool { + pub fn new() -> Self { + Self::default() + } +} + +#[async_trait] +impl AgentTool for TodoTool { + fn name(&self) -> &str { + "todo" + } + fn description(&self) -> &str { + "Track tasks across a single agent run. action ∈ {add, complete, list, clear}. add expects 'text'; complete expects 'index' (1-based)." + } + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "action": {"type": "string", "enum": ["add", "complete", "list", "clear"]}, + "text": {"type": "string"}, + "index": {"type": "integer"} + }, + "required": ["action"] + }) + } + async fn execute(&self, _id: &str, args: Value) -> Result { + let action = args + .get("action") + .and_then(|v| v.as_str()) + .ok_or("missing 'action'")?; + let mut items = self.items.lock().map_err(|e| e.to_string())?; + match action { + "add" => { + let text = args + .get("text") + .and_then(|v| v.as_str()) + .ok_or("missing 'text'")? + .to_string(); + items.push(TodoItem { text, done: false }); + Ok(AgentToolResult::text(format_list(&items))) + } + "complete" => { + let idx = args + .get("index") + .and_then(|v| v.as_u64()) + .ok_or("missing 'index'")? as usize; + if idx == 0 || idx > items.len() { + return Err(format!("index {idx} out of range (1..={})", items.len())); + } + items[idx - 1].done = true; + Ok(AgentToolResult::text(format_list(&items))) + } + "list" => Ok(AgentToolResult::text(format_list(&items))), + "clear" => { + items.clear(); + Ok(AgentToolResult::text("(cleared)".to_string())) + } + other => Err(format!("unknown action: {other}")), + } + } +} + +fn format_list(items: &[TodoItem]) -> String { + if items.is_empty() { + return "(empty)".to_string(); + } + let mut out = String::new(); + for (i, item) in items.iter().enumerate() { + let mark = if item.done { "[x]" } else { "[ ]" }; + out.push_str(&format!("{} {} {}\n", i + 1, mark, item.text)); + } + out +} diff --git a/agent/crates/pi-agent/src/tools/write.rs b/agent/crates/pi-agent/src/tools/write.rs new file mode 100644 index 00000000..1181f567 --- /dev/null +++ b/agent/crates/pi-agent/src/tools/write.rs @@ -0,0 +1,53 @@ +use async_trait::async_trait; +use serde_json::{json, Value}; +use tokio::fs; + +use crate::types::{AgentTool, AgentToolResult}; + +pub struct WriteTool; + +#[async_trait] +impl AgentTool for WriteTool { + fn name(&self) -> &str { + "write" + } + fn requires_permission(&self) -> bool { + true + } + fn description(&self) -> &str { + "Write the given content to the path, replacing any existing file. Creates parent directories as needed." + } + fn parameters(&self) -> Value { + json!({ + "type": "object", + "properties": { + "path": {"type": "string"}, + "content": {"type": "string"} + }, + "required": ["path", "content"] + }) + } + async fn execute(&self, _id: &str, args: Value) -> Result { + let path = args + .get("path") + .and_then(|v| v.as_str()) + .ok_or("missing 'path'")?; + let content = args + .get("content") + .and_then(|v| v.as_str()) + .ok_or("missing 'content'")?; + if let Some(parent) = std::path::Path::new(path).parent() { + if !parent.as_os_str().is_empty() { + fs::create_dir_all(parent).await.ok(); + } + } + fs::write(path, content) + .await + .map_err(|e| format!("write {path}: {e}"))?; + Ok(AgentToolResult::text(format!( + "wrote {} bytes to {}", + content.len(), + path + ))) + } +} diff --git a/agent/crates/pi-agent/src/types.rs b/agent/crates/pi-agent/src/types.rs new file mode 100644 index 00000000..5a7f1154 --- /dev/null +++ b/agent/crates/pi-agent/src/types.rs @@ -0,0 +1,206 @@ +use std::sync::Arc; + +use async_trait::async_trait; +use pi_ai::{Content, Message, Model, StreamOptions, ThinkingLevel, Tool}; +use serde_json::Value; + +/// A live result returned from a tool execution. +#[derive(Debug, Clone, Default)] +pub struct AgentToolResult { + pub content: Vec, + pub details: Value, + pub terminate: bool, +} + +impl AgentToolResult { + pub fn text(s: impl Into) -> Self { + Self { + content: vec![Content::text(s)], + details: Value::Null, + terminate: false, + } + } +} + +/// Permission outcome for a tool call. Returned by a [`PermissionPolicy`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PermissionDecision { + Allow, + /// Allow this call and remember the choice for the rest of the run. + AllowSession, + /// Deny this call; emit an error tool result with `reason`. + Deny { + reason: String, + }, +} + +/// User-supplied permission policy. Implementations may prompt interactively or +/// consult a static allow-list. +#[async_trait] +pub trait PermissionPolicy: Send + Sync { + async fn check(&self, tool_name: &str, args: &Value) -> PermissionDecision; +} + +/// Always-allow policy — useful for tests and non-interactive runs. +pub struct AllowAllPolicy; + +#[async_trait] +impl PermissionPolicy for AllowAllPolicy { + async fn check(&self, _tool_name: &str, _args: &Value) -> PermissionDecision { + PermissionDecision::Allow + } +} + +/// Tool execution trait — analog of `AgentTool.execute` in TS. +#[async_trait] +pub trait AgentTool: Send + Sync { + fn name(&self) -> &str; + fn label(&self) -> &str { + self.name() + } + fn description(&self) -> &str; + fn parameters(&self) -> Value; + /// Whether the tool requires user permission by default. Read-only tools + /// (`read`, `ls`, `grep`, `glob`) return `false`; mutating or side-effecting + /// tools (`bash`, `write`, `edit`) return `true`. + fn requires_permission(&self) -> bool { + false + } + async fn execute(&self, tool_call_id: &str, args: Value) -> Result; +} + +pub fn tool_def(t: &dyn AgentTool) -> Tool { + Tool { + name: t.name().to_string(), + description: t.description().to_string(), + parameters: t.parameters(), + } +} + +/// What the loop asks before a reply without tool calls ends the run: given the conversation so far, the text of one +/// more user message (what's still unfinished), or None to let the reply stand. the host app addition (T-141). +pub type BeforeReply = Arc futures::future::BoxFuture<'static, Option> + Send + Sync>; + +/// Agent configuration controlling the loop. +/// A reply stream for one run's first step (T-200). Taken once; behind a lock so `AgentConfig` stays `Clone`. +#[derive(Clone)] +pub struct SeededStream(Arc>>); + +impl SeededStream { + pub fn new(stream: pi_ai::AssistantMessageEventStream) -> Self { Self(Arc::new(std::sync::Mutex::new(Some(stream)))) } + pub fn take(&self) -> Option { self.0.lock().unwrap().take() } +} + +#[derive(Clone)] +pub struct AgentConfig { + pub model: Model, + pub thinking_level: ThinkingLevel, + pub stream_options: StreamOptions, + pub max_turns: u32, + pub tools: Vec>, + pub system_prompt: String, + pub permission: Arc, + /// Only the newest this-many images in tool results are sent to the model; older ones become a short + /// placeholder (they stay in the conversation). the host app addition. + pub keep_images: usize, + /// When the conversation passes this many characters, older tool results and long tool-call arguments are + /// shortened in one go (one prompt-cache miss, then a smaller stable prefix). the host app addition. + pub compact_at_chars: usize, + /// This turn's own instructions, sent after `system_prompt` and outside its cache breakpoint (pi-ai + /// Context::system_suffix). the host app addition. + pub system_suffix: String, + /// This turn's moving lines, after the conversation and outside the cache (pi-ai Context::trailing, T-251). + pub trailing: String, + /// The first step's reply stream, already started elsewhere (a speculative voice turn, T-200): the first step reads + /// it instead of calling the model (what it buffered comes out at once, the rest live), then the run goes on as usual + /// (running its tool calls). the host app addition. + pub seeded_stream: Option, + /// With this many steps left before `max_turns`, the text is added to that step's last tool result, once, so a long + /// job ends with something delivered instead of stopping mid-way at the limit. the host app addition. + pub wrap_up: Option<(u32, String)>, + /// Asked once per run, when the model replies without calling a tool and a step is left: Some(text) adds the text + /// as a user message and the run goes on; None, or any later reply, ends the run as before. the host app addition (T-141). + pub before_reply: Option, +} + +impl AgentConfig { + pub fn new(model: Model, system_prompt: impl Into) -> Self { + Self { + model, + thinking_level: ThinkingLevel::Off, + stream_options: StreamOptions::default(), + max_turns: 32, + tools: Vec::new(), + system_prompt: system_prompt.into(), + permission: Arc::new(AllowAllPolicy), + keep_images: usize::MAX, + compact_at_chars: usize::MAX, + system_suffix: String::new(), + trailing: String::new(), + seeded_stream: None, + wrap_up: None, + before_reply: None, + } + } + + pub fn with_tools(mut self, tools: Vec>) -> Self { + self.tools = tools; + self + } + + pub fn with_max_turns(mut self, n: u32) -> Self { + self.max_turns = n; + self + } + + pub fn with_permission(mut self, p: Arc) -> Self { + self.permission = p; + self + } + + pub fn with_thinking(mut self, level: ThinkingLevel) -> Self { + self.thinking_level = level; + self + } +} + +/// Events emitted by the agent loop, mirroring `AgentEvent` in TS. +#[derive(Debug, Clone)] +pub enum AgentEvent { + AgentStart, + AgentEnd { + messages: Vec, + }, + TurnStart, + TurnEnd, + AssistantMessage { + message: Message, + }, + UserMessage { + message: Message, + }, + /// Streaming text chunk while the assistant types. + TextDelta { + delta: String, + }, + /// Streaming thinking chunk. + ThinkingDelta { + delta: String, + }, + ToolExecutionStart { + tool_call_id: String, + tool_name: String, + args: Value, + }, + ToolExecutionEnd { + tool_call_id: String, + tool_name: String, + is_error: bool, + content: Vec, + }, + /// Permission denied for a tool call (the loop appended an error tool result). + PermissionDenied { + tool_name: String, + reason: String, + }, +} diff --git a/agent/crates/pi-agent/tests/before_reply.rs b/agent/crates/pi-agent/tests/before_reply.rs new file mode 100644 index 00000000..0d751290 --- /dev/null +++ b/agent/crates/pi-agent/tests/before_reply.rs @@ -0,0 +1,142 @@ +//! T-141: before a reply without tool calls ends the run, the caller's `before_reply` may send the model back once +//! with what's unfinished. Against a fake Anthropic-style server: the first final reply gets the note as a user +//! message and the loop goes on; the second final reply ends the run, whatever the hook would say. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use futures::future::BoxFuture; +use pi_agent::{run_agent_with_history, AgentConfig, AgentEvent, BeforeReply}; +use pi_ai::{Content, Message, Model, ModelPricing}; +use serde_json::{json, Value}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +fn sse(events: &[(&str, Value)]) -> String { + events.iter().map(|(name, data)| format!("event: {name}\ndata: {data}\n\n")).collect() +} + +fn text(id: &str, t: &str) -> String { + sse(&[ + ("message_start", json!({"type": "message_start", "message": {"id": id, "type": "message", "role": "assistant", + "content": [], "model": "MiniMax-M3", "stop_reason": null, "usage": {"input_tokens": 120, "output_tokens": 1}}})), + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": t}})), + ("content_block_stop", json!({"type": "content_block_stop", "index": 0})), + ("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 12}})), + ("message_stop", json!({"type": "message_stop"})), + ]) +} + +/// Serves `bodies` in order as SSE; records each request's JSON body. +async fn mock(bodies: Vec) -> (String, Arc>>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let seen = Arc::new(Mutex::new(Vec::new())); + let (seen2, bodies, count) = (seen.clone(), Arc::new(bodies), Arc::new(AtomicUsize::new(0))); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { return }; + let (seen, bodies, count) = (seen2.clone(), bodies.clone(), count.clone()); + tokio::spawn(async move { + let (mut buf, mut chunk) = (Vec::new(), [0u8; 8192]); + let body = loop { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { return; } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_lowercase(); + let len: usize = head.lines().find_map(|l| l.strip_prefix("content-length:").map(|v| v.trim().parse().unwrap_or(0))).unwrap_or(0); + while buf.len() < pos + 4 + len { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { break; } + buf.extend_from_slice(&chunk[..n]); + } + break buf[pos + 4..].to_vec(); + } + }; + seen.lock().unwrap().push(serde_json::from_slice(&body).unwrap_or(Value::Null)); + let i = count.fetch_add(1, Ordering::SeqCst); + let (status, body) = match bodies.get(i) { Some(b) => (200, b.clone()), None => (500, "no more scripted replies".to_string()) }; + let kind = if status == 200 { "text/event-stream" } else { "application/json" }; + let head = format!("HTTP/1.1 {status} X\r\ncontent-type: {kind}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", body.len()); + let _ = sock.write_all(head.as_bytes()).await; + let _ = sock.write_all(body.as_bytes()).await; + }); + } + }); + (format!("http://{addr}"), seen) +} + +fn config(base: &str, max_turns: u32) -> AgentConfig { + let model = Model { + id: "MiniMax-M3".into(), name: "MiniMax-M3".into(), api: "anthropic-messages".into(), provider: "test".into(), + base_url: base.into(), reasoning: false, context_window: 200_000, max_tokens: 16_384, pricing: ModelPricing::default(), + }; + let mut c = AgentConfig::new(model, "test").with_max_turns(max_turns); + c.stream_options.api_key = Some("test".into()); + c +} + +fn user(t: &str) -> Message { Message::User { content: vec![Content::text(t)], timestamp: pi_ai::now_ms() } } + +const NOTE: &str = "Before you reply: render: no export from this turn. Fix these, then reply."; + +/// A hook that counts its calls and always says `says` (None: everything passed). +fn hook(calls: Arc, says: Option<&'static str>) -> BeforeReply { + Arc::new(move |_messages: &[Message]| -> BoxFuture<'static, Option> { + calls.fetch_add(1, Ordering::SeqCst); + Box::pin(async move { says.map(String::from) }) + }) +} + +fn text_of(m: &Message) -> String { + let content = match m { Message::User { content, .. } => content, Message::Assistant(a) => &a.content, Message::ToolResult(t) => &t.content }; + content.iter().filter_map(|c| c.as_text()).collect::>().join("") +} + +#[tokio::test] +async fn before_reply_sends_the_first_final_reply_back_once() { + let (base, seen) = mock(vec![text("m1", "Done, the cut is ready."), text("m2", "Rendered: exports/cut.mp4.")]).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut c = config(&base, 5); + c.before_reply = Some(hook(calls.clone(), Some(NOTE))); + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let run = run_agent_with_history(&c, vec![user("Cut it and render")], Some(tx)).await.unwrap(); + + assert_eq!(seen.lock().unwrap().len(), 2, "the first final reply was sent back and the model asked again"); + assert_eq!(calls.load(Ordering::SeqCst), 1, "asked once per run: the second final reply ends it"); + let said: Vec = run.messages.iter().map(text_of).collect(); + assert_eq!(said, ["Cut it and render", "Done, the cut is ready.", NOTE, "Rendered: exports/cut.mp4."]); + assert!(matches!(&run.messages[2], Message::User { .. }), "the note is a user message"); + let second = seen.lock().unwrap()[1].clone(); + assert!(second["messages"].to_string().contains("no export from this turn"), "the second request carries the note: {second}"); + // The note is an event too, so a host that saves messages from events keeps it. + let mut notes = 0; + while let Ok(ev) = rx.try_recv() { + if let AgentEvent::UserMessage { message } = ev { if text_of(&message) == NOTE { notes += 1; } } + } + assert_eq!(notes, 1); + assert!(!run.stopped_at_turn_limit); +} + +#[tokio::test] +async fn before_reply_that_passes_lets_the_reply_end_the_run() { + let (base, seen) = mock(vec![text("m1", "Rendered: exports/cut.mp4.")]).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut c = config(&base, 5); + c.before_reply = Some(hook(calls.clone(), None)); + let run = run_agent_with_history(&c, vec![user("Cut it and render")], None).await.unwrap(); + assert_eq!((seen.lock().unwrap().len(), calls.load(Ordering::SeqCst), run.messages.len()), (1, 1, 2)); +} + +#[tokio::test] +async fn before_reply_is_not_asked_without_a_step_left() { + let (base, seen) = mock(vec![text("m1", "Here's where it stands.")]).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut c = config(&base, 1); + c.before_reply = Some(hook(calls.clone(), Some(NOTE))); + let run = run_agent_with_history(&c, vec![user("Cut it and render")], None).await.unwrap(); + assert_eq!((seen.lock().unwrap().len(), calls.load(Ordering::SeqCst)), (1, 0), "a note with no step to act on is never sent"); + assert!(matches!(run.messages.last(), Some(Message::Assistant(_)))); +} diff --git a/agent/crates/pi-agent/tests/length_stop.rs b/agent/crates/pi-agent/tests/length_stop.rs new file mode 100644 index 00000000..08bb9aa4 --- /dev/null +++ b/agent/crates/pi-agent/tests/length_stop.rs @@ -0,0 +1,219 @@ +//! T-120: a reply that hits the output limit inside a tool call. Before the fix the loop ended the turn with the call +//! unanswered, and the provider rejected every later request in that chat ("tool call result does not follow tool +//! call"). Against a fake Anthropic-style server: the cut-off call isn't run, it's answered, and the loop carries on; +//! and a history that already holds an unanswered call is repaired before the first request. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; +use pi_agent::{run_agent_with_history, AgentConfig, AgentTool, AgentToolResult}; +use pi_ai::{AssistantMessage, Content, Message, Model, ModelPricing, StopReason, Usage}; +use serde_json::{json, Value}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +fn sse(events: &[(&str, Value)]) -> String { + events.iter().map(|(name, data)| format!("event: {name}\ndata: {data}\n\n")).collect() +} + +fn start(id: &str) -> (&'static str, Value) { + ("message_start", json!({"type": "message_start", "message": {"id": id, "type": "message", "role": "assistant", + "content": [], "model": "MiniMax-M3", "stop_reason": null, "usage": {"input_tokens": 120, "output_tokens": 1}}})) +} + +/// A reply cut off by max_tokens halfway through a `write` call's arguments. +fn cut_off_write() -> String { + sse(&[ + start("m1"), + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Let me build the new file:"}})), + ("content_block_stop", json!({"type": "content_block_stop", "index": 0})), + ("content_block_start", json!({"type": "content_block_start", "index": 1, "content_block": {"type": "tool_use", "id": "tu_1", "name": "write", "input": {}}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"path\": \"edits/v2.w.html\", \"content\": \"
String { + sse(&[ + start(id), + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": t}})), + ("content_block_stop", json!({"type": "content_block_stop", "index": 0})), + ("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 12}})), + ("message_stop", json!({"type": "message_stop"})), + ]) +} + +/// A reply that calls `write` with whole arguments. +fn full_write(id: &str, tu: &str) -> String { + sse(&[ + start(id), + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": tu, "name": "write", "input": {}}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": "{\"path\": \"a.txt\", \"content\": \"hi\"}"}})), + ("content_block_stop", json!({"type": "content_block_stop", "index": 0})), + ("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 30}})), + ("message_stop", json!({"type": "message_stop"})), + ]) +} + +/// A reply whose stream just stops: text, then no stop reason and no message_stop (a dropped connection). +fn cut_mid_reply() -> String { + sse(&[ + start("m0"), + ("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})), + ("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "I'll inline the end card directly into the edit"}})), + ]) +} + +/// Serves `bodies` in order as SSE; records each request's JSON body. +async fn mock(bodies: Vec) -> (String, Arc>>) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let seen = Arc::new(Mutex::new(Vec::new())); + let (seen2, bodies, count) = (seen.clone(), Arc::new(bodies), Arc::new(AtomicUsize::new(0))); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { return }; + let (seen, bodies, count) = (seen2.clone(), bodies.clone(), count.clone()); + tokio::spawn(async move { + let (mut buf, mut chunk) = (Vec::new(), [0u8; 8192]); + let body = loop { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { return; } + buf.extend_from_slice(&chunk[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&buf[..pos]).to_lowercase(); + let len: usize = head.lines().find_map(|l| l.strip_prefix("content-length:").map(|v| v.trim().parse().unwrap_or(0))).unwrap_or(0); + while buf.len() < pos + 4 + len { + let n = sock.read(&mut chunk).await.unwrap_or(0); + if n == 0 { break; } + buf.extend_from_slice(&chunk[..n]); + } + break buf[pos + 4..].to_vec(); + } + }; + seen.lock().unwrap().push(serde_json::from_slice(&body).unwrap_or(Value::Null)); + let i = count.fetch_add(1, Ordering::SeqCst); + let (status, body) = match bodies.get(i) { Some(b) => (200, b.clone()), None => (500, "no more scripted replies".to_string()) }; + let kind = if status == 200 { "text/event-stream" } else { "application/json" }; + let head = format!("HTTP/1.1 {status} X\r\ncontent-type: {kind}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", body.len()); + let _ = sock.write_all(head.as_bytes()).await; + let _ = sock.write_all(body.as_bytes()).await; + }); + } + }); + (format!("http://{addr}"), seen) +} + +/// A `write` that counts its calls: a cut-off call must never reach it. +struct Write(Arc); + +#[async_trait] +impl AgentTool for Write { + fn name(&self) -> &str { "write" } + fn description(&self) -> &str { "write a file" } + fn parameters(&self) -> Value { json!({"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}}) } + async fn execute(&self, _id: &str, _a: Value) -> Result { + self.0.fetch_add(1, Ordering::SeqCst); + Ok(AgentToolResult::text("wrote it")) + } +} + +fn config(base: &str, writes: Arc) -> AgentConfig { + let model = Model { + id: "MiniMax-M3".into(), name: "MiniMax-M3".into(), api: "anthropic-messages".into(), provider: "test".into(), + base_url: base.into(), reasoning: false, context_window: 200_000, max_tokens: 16_384, pricing: ModelPricing::default(), + }; + let mut c = AgentConfig::new(model, "test").with_tools(vec![Arc::new(Write(writes))]).with_max_turns(5); + c.stream_options.api_key = Some("test".into()); + c +} + +fn user(t: &str) -> Message { Message::User { content: vec![Content::text(t)], timestamp: pi_ai::now_ms() } } + +fn assistant(content: Vec, stop_reason: StopReason) -> Message { + Message::Assistant(AssistantMessage { content, api: "anthropic-messages".into(), provider: "test".into(), model: "MiniMax-M3".into(), + usage: Usage::default(), stop_reason, error_message: None, timestamp: 0 }) +} + +/// Whether the request's messages answer tool call `id` (an Anthropic tool_result block for it). +fn answers(request: &Value, id: &str) -> bool { + request["messages"].as_array().into_iter().flatten() + .flat_map(|m| m["content"].as_array().cloned().unwrap_or_default()) + .any(|b| b["type"] == "tool_result" && b["tool_use_id"] == id) +} + +#[tokio::test] +async fn length_stop_inside_a_tool_call_is_answered_and_the_turn_goes_on() { + let (base, seen) = mock(vec![cut_off_write(), text("m2", "That file is big, so I'll write it in two parts.")]).await; + let writes = Arc::new(AtomicUsize::new(0)); + let run = run_agent_with_history(&config(&base, writes.clone()), vec![user("Make a 90 s version")], None).await.unwrap(); + + assert_eq!(writes.load(Ordering::SeqCst), 0, "a cut-off call never runs"); + let requests = seen.lock().unwrap().clone(); + assert_eq!(requests.len(), 2, "the loop asked the model again instead of ending the turn"); + assert!(answers(&requests[1], "tu_1"), "the second request answers the cut-off call: {}", requests[1]); + let result = run.messages.iter().find_map(|m| match m { Message::ToolResult(t) if t.tool_call_id == "tu_1" => Some(t), _ => None }).unwrap(); + assert!(result.is_error); + assert!(format!("{:?}", result.content).contains("output limit"), "it says why: {:?}", result.content); + assert!(matches!(run.messages.last(), Some(Message::Assistant(a)) if a.stop_reason == StopReason::Stop)); +} + +#[tokio::test] +async fn length_stop_left_in_a_history_is_repaired_before_the_first_request() { + let (base, seen) = mock(vec![text("m3", "Here's the punchier version.")]).await; + let open = assistant(vec![Content::text("Let me build the new file:"), + Content::ToolCall { id: "tu_old".into(), name: "write".into(), arguments: json!({}) }], StopReason::Length); + let history = vec![user("Make a 90 s version"), open, user("Try again")]; + let run = run_agent_with_history(&config(&base, Arc::new(AtomicUsize::new(0))), history, None).await.unwrap(); + let requests = seen.lock().unwrap().clone(); + assert!(answers(&requests[0], "tu_old"), "the old call is answered in the first request: {}", requests[0]); + assert!(run.messages.iter().any(|m| matches!(m, Message::ToolResult(t) if t.tool_call_id == "tu_old" && t.is_error))); +} + +#[test] +fn length_stop_helper_answers_only_what_is_open() { + let call = |id: &str| Content::ToolCall { id: id.into(), name: "write".into(), arguments: json!({}) }; + let result = |id: &str| Message::ToolResult(pi_ai::ToolResultMessage { tool_call_id: id.into(), tool_name: "write".into(), + content: vec![Content::text("ok")], is_error: false, timestamp: 0 }); + let mut messages = vec![user("go"), assistant(vec![call("a"), call("b")], StopReason::ToolUse), result("a"), user("next")]; + assert_eq!(pi_agent::agent_loop::answer_unanswered(&mut messages), 1); + assert!(matches!(&messages[3], Message::ToolResult(t) if t.tool_call_id == "b" && t.is_error), "b answered right after a's result"); + assert!(matches!(&messages[4], Message::User { .. })); + assert_eq!(pi_agent::agent_loop::answer_unanswered(&mut messages), 0, "nothing left to answer"); +} + +#[tokio::test] +async fn stream_ended_early_is_retried_once() { + let (base, seen) = mock(vec![cut_mid_reply(), text("m4", "Rendered: exports/end-card.mp4.")]).await; + let run = run_agent_with_history(&config(&base, Arc::new(AtomicUsize::new(0))), vec![user("Add the end card and render")], None) + .await.unwrap(); + assert_eq!(seen.lock().unwrap().len(), 2, "the cut-off step is asked again"); + let last = match run.messages.last() { Some(Message::Assistant(a)) => a.clone(), other => panic!("{other:?}") }; + assert!(format!("{:?}", last.content).contains("Rendered"), "the turn ends on the retried reply: {:?}", last.content); + assert_eq!(run.messages.iter().filter(|m| matches!(m, Message::Assistant(_))).count(), 1, "the half reply isn't kept"); +} + +#[tokio::test] +async fn stream_ended_early_twice_is_an_error_that_says_so() { + let (base, _seen) = mock(vec![cut_mid_reply(), cut_mid_reply()]).await; + let err = run_agent_with_history(&config(&base, Arc::new(AtomicUsize::new(0))), vec![user("Add the end card and render")], None) + .await.err().expect("two cut-off replies end the turn with an error"); + assert!(err.to_string().contains("cut off"), "{err}"); +} + +#[tokio::test] +async fn near_the_step_limit_the_tool_results_say_so_once() { + let (base, seen) = mock(vec![full_write("m1", "tu_1"), full_write("m2", "tu_2"), text("m3", "Rendered what I had.")]).await; + let writes = Arc::new(AtomicUsize::new(0)); + let mut c = config(&base, writes.clone()).with_max_turns(3); + c.wrap_up = Some((1, "1 step left: render what you have.".into())); + run_agent_with_history(&c, vec![user("Cut it and render")], None).await.unwrap(); + let requests = seen.lock().unwrap().clone(); + assert_eq!((requests.len(), writes.load(Ordering::SeqCst)), (3, 2)); + let said = |r: &Value| r.to_string().matches("1 step left").count(); + assert_eq!((said(&requests[1]), said(&requests[2])), (0, 1), "only the step with one left carries it, once"); +} diff --git a/agent/crates/pi-agent/tests/tools_smoke.rs b/agent/crates/pi-agent/tests/tools_smoke.rs new file mode 100644 index 00000000..c7ac4828 --- /dev/null +++ b/agent/crates/pi-agent/tests/tools_smoke.rs @@ -0,0 +1,152 @@ +//! Smoke tests for builtin tools. No LLM is required — these exercise the +//! tool implementations directly against a tempfile-backed scratch dir. + +use std::path::PathBuf; +use std::sync::Arc; + +use pi_agent::tools::{edit, glob_tool, grep, ls, read, write}; +use pi_agent::types::AgentTool; +use serde_json::json; + +fn scratch_dir() -> PathBuf { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let c = COUNTER.fetch_add(1, Ordering::Relaxed); + let tid = format!("{:?}", std::thread::current().id()); + let tid_filtered: String = tid.chars().filter(|c| c.is_alphanumeric()).collect(); + let dir = std::env::temp_dir().join(format!("pi-rs-test-{n:x}-{c}-{tid_filtered}")); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[tokio::test] +async fn write_then_read_roundtrips() { + let dir = scratch_dir(); + let path = dir.join("hello.txt"); + let path_s = path.to_string_lossy().to_string(); + + let res = write::WriteTool + .execute("1", json!({"path": path_s, "content": "hello\nworld\n"})) + .await + .unwrap(); + assert!(matches!(res.content[0], pi_ai::Content::Text { .. })); + + let res = read::ReadTool + .execute("2", json!({"path": path_s})) + .await + .unwrap(); + let text = res.content[0].as_text().unwrap().to_string(); + assert!(text.contains("hello")); + assert!(text.contains("world")); +} + +#[tokio::test] +async fn edit_replaces_single_occurrence() { + let dir = scratch_dir(); + let path = dir.join("a.txt"); + let path_s = path.to_string_lossy().to_string(); + std::fs::write(&path, "foo bar baz").unwrap(); + + let res = edit::EditTool + .execute( + "1", + json!({"path": path_s, "old_string": "bar", "new_string": "BAR"}), + ) + .await + .unwrap(); + assert!(res.content[0].as_text().unwrap().contains("edited")); + let diff = res.content[1].as_text().unwrap(); + assert!( + diff.contains("-foo bar baz"), + "diff missing '-foo bar baz':\n{diff}" + ); + assert!( + diff.contains("+foo BAR baz"), + "diff missing '+foo BAR baz':\n{diff}" + ); + let after = std::fs::read_to_string(&path).unwrap(); + assert_eq!(after, "foo BAR baz"); +} + +#[tokio::test] +async fn ls_lists_dir() { + let dir = scratch_dir(); + std::fs::write(dir.join("a.txt"), "x").unwrap(); + std::fs::create_dir(dir.join("sub")).unwrap(); + + let res = ls::LsTool + .execute("1", json!({"path": dir.to_string_lossy()})) + .await + .unwrap(); + let text = res.content[0].as_text().unwrap(); + assert!(text.contains("a.txt")); + assert!(text.contains("sub")); +} + +#[tokio::test] +async fn grep_finds_pattern() { + let dir = scratch_dir(); + std::fs::write(dir.join("a.txt"), "needle\nhaystack\n").unwrap(); + std::fs::write(dir.join("b.txt"), "nothing here\n").unwrap(); + + let res = grep::GrepTool + .execute( + "1", + json!({"pattern": "needle", "path": dir.to_string_lossy()}), + ) + .await + .unwrap(); + let text = res.content[0].as_text().unwrap(); + assert!(text.contains("a.txt")); + assert!(text.contains("needle")); +} + +#[tokio::test] +async fn grep_context_lines() { + let dir = scratch_dir(); + let sub = dir.join("dir"); + std::fs::create_dir_all(&sub).unwrap(); + std::fs::write(sub.join("a.txt"), "alpha\nbeta needle gamma\ndelta\n").unwrap(); + + let res = grep::GrepTool + .execute( + "1", + json!({ + "pattern": "needle", + "path": sub.to_string_lossy(), + "before": 1, + "after": 1, + }), + ) + .await + .unwrap(); + let text = res.content[0].as_text().unwrap(); + assert!(text.contains("alpha"), "expected 'alpha' in: {text}"); + assert!( + text.contains("beta needle gamma"), + "expected 'beta needle gamma' in: {text}" + ); + assert!(text.contains("delta"), "expected 'delta' in: {text}"); +} + +#[tokio::test] +async fn glob_finds_files() { + let dir = scratch_dir(); + std::fs::write(dir.join("a.rs"), "").unwrap(); + std::fs::write(dir.join("b.rs"), "").unwrap(); + std::fs::write(dir.join("c.txt"), "").unwrap(); + + let pattern = format!("{}/*.rs", dir.to_string_lossy()); + let res = glob_tool::GlobTool + .execute("1", json!({"pattern": pattern})) + .await + .unwrap(); + let text = res.content[0].as_text().unwrap(); + assert!(text.contains("a.rs")); + assert!(text.contains("b.rs")); + assert!(!text.contains("c.txt")); +} diff --git a/agent/crates/pi-ai/Cargo.toml b/agent/crates/pi-ai/Cargo.toml new file mode 100644 index 00000000..e0350a74 --- /dev/null +++ b/agent/crates/pi-ai/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "pi-ai" +description = "Unified multi-provider LLM API (Rust port of @earendil-works/pi-ai). Streams from Anthropic, OpenAI, Google Gemini, and any OpenAI-compatible endpoint." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +readme = "README.md" +keywords = ["llm", "ai", "anthropic", "openai", "agent"] +categories = ["api-bindings", "asynchronous"] + +[dependencies] +tokio = { workspace = true } +tokio-util = { workspace = true } +reqwest = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +async-trait = { workspace = true } +futures = { workspace = true } +thiserror = { workspace = true } +tracing = { workspace = true } +chrono = { workspace = true } +async-stream = { workspace = true } +bytes = { workspace = true } +url = { workspace = true } +uuid = { workspace = true } +eventsource-stream = { workspace = true } diff --git a/agent/crates/pi-ai/README.md b/agent/crates/pi-ai/README.md new file mode 100644 index 00000000..4767096b --- /dev/null +++ b/agent/crates/pi-ai/README.md @@ -0,0 +1,61 @@ +# pi-ai + +Unified multi-provider LLM API. Part of the [`pi`](https://github.com/nktkt/pi) +agent runtime — a Rust port of +[`@earendil-works/pi-ai`](https://github.com/earendil-works/pi). + +## Providers + +| API string | Implemented by | Endpoints | +|------------|---------------|-----------| +| `anthropic-messages` | `AnthropicProvider` | Anthropic Messages SSE | +| `openai-completions` | `OpenAiProvider` | OpenAI Chat Completions + any OpenAI-compatible base URL (OpenRouter, Together, Groq, Cerebras, DeepSeek, Fireworks, xAI, etc.) | +| `google-generative-ai` | `GoogleProvider` | Gemini `streamGenerateContent?alt=sse` | + +All three stream via SSE, emit per-block `text_delta` / `thinking_delta` / +`toolcall_delta` events, share a retry helper with `Retry-After` parsing, +and honor a `CancellationToken` for mid-stream abort. + +## Quick start + +```rust +use pi_ai::{stream_simple, Context, Message, Model, StreamOptions}; +use futures::StreamExt; + +# tokio_test::block_on(async { +let model = Model::anthropic_claude_sonnet_4_6(); +let ctx = Context { + system_prompt: Some("You are a helpful assistant.".into()), + system_suffix: None, + messages: vec![Message::user_text("Say hi in one word.")], + trailing: None, + tools: vec![], +}; +let mut events = stream_simple(&model, &ctx, &StreamOptions::default()).await.unwrap(); +while let Some(ev) = events.next().await { + println!("{:?}", ev.unwrap()); +} +# }); +``` + +`ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` / `GOOGLE_API_KEY` / +`GEMINI_API_KEY`) is read from the environment unless +`StreamOptions::api_key` is set. + +## OpenAI-compatible passthrough + +```rust +use pi_ai::Model; +let m = Model::openai_compat( + "openrouter", + "anthropic/claude-3.5-sonnet", + "https://openrouter.ai/api/v1", + 200_000, 8_192, +); +``` + +Set `OPENAI_API_KEY` to the provider's key, or pass `api_key` directly. + +## License + +MIT diff --git a/agent/crates/pi-ai/src/error.rs b/agent/crates/pi-ai/src/error.rs new file mode 100644 index 00000000..718245fd --- /dev/null +++ b/agent/crates/pi-ai/src/error.rs @@ -0,0 +1,36 @@ +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error("missing API key for provider {0}")] + MissingApiKey(String), + + #[error("unsupported provider/api: {0}")] + UnsupportedProvider(String), + + #[error("http error: {0}")] + Http(#[from] reqwest::Error), + + #[error("invalid response from provider: {0}")] + InvalidResponse(String), + + #[error("provider returned an error (status {status}): {body}")] + ProviderError { status: u16, body: String }, + + #[error("request cancelled")] + Cancelled, + + #[error("retried {attempts} times, last error: {source}")] + RetryExhausted { attempts: u32, source: Box }, + + #[error("json: {0}")] + Json(#[from] serde_json::Error), + + #[error("io: {0}")] + Io(#[from] std::io::Error), + + #[error("{0}")] + Other(String), +} + +pub type Result = std::result::Result; diff --git a/agent/crates/pi-ai/src/lib.rs b/agent/crates/pi-ai/src/lib.rs new file mode 100644 index 00000000..c9aec304 --- /dev/null +++ b/agent/crates/pi-ai/src/lib.rs @@ -0,0 +1,57 @@ +//! `pi-ai` — Unified multi-provider LLM API. +//! +//! Rust port of the TypeScript package `@earendil-works/pi-ai`. The original +//! project supports many providers; this port focuses on the two most common +//! agent backends: Anthropic Messages and OpenAI Chat Completions. Both share +//! the same `Message`/`Tool`/`AssistantMessageEvent` types so the agent loop +//! is provider-agnostic. + +pub mod error; +pub mod providers; +pub mod retry; +pub mod stream; +pub mod types; + +pub use error::{Error, Result}; + +/// The `InvalidResponse` message for a reply stream that ended before the reply did (no stop reason, no message_stop): +/// a dropped connection, not a finished answer. pi-agent retries the step once on it. +pub const STREAM_ENDED_EARLY: &str = "the reply stream ended before the reply finished"; +pub use providers::{ + anthropic::AnthropicProvider, google::GoogleProvider, openai::OpenAiProvider, + openai_responses::OpenAiResponsesProvider, Provider, +}; +pub use stream::AssistantMessageEventStream; +pub use types::{ + now_ms, AssistantMessage, AssistantMessageEvent, CacheRetention, Content, Context, Cost, + Message, Model, ModelPricing, StopReason, StreamOptions, ThinkingLevel, Tool, + ToolResultMessage, Usage, +}; + +/// Entry point that mirrors `streamSimple()` in pi-ai TS: pick the provider +/// implementation from `model.api` and return a stream of message events. +/// +/// `openai-completions` covers OpenAI and every OpenAI-compatible passthrough +/// (OpenRouter, Together, Groq, Cerebras, DeepSeek, Fireworks, xAI, etc.) — +/// just set `Model::base_url` (or `StreamOptions::base_url`) accordingly. +pub async fn stream_simple( + model: &Model, + context: &Context, + options: &StreamOptions, +) -> Result { + match model.api.as_str() { + "anthropic-messages" => { + AnthropicProvider::new() + .stream(model, context, options) + .await + } + "openai-completions" => OpenAiProvider::new().stream(model, context, options).await, + "openai-responses" => { + OpenAiResponsesProvider::new() + .stream(model, context, options) + .await + } + "google-generative-ai" => GoogleProvider::new().stream(model, context, options).await, + other => Err(Error::UnsupportedProvider(other.into())), + } +} diff --git a/agent/crates/pi-ai/src/providers/anthropic.rs b/agent/crates/pi-ai/src/providers/anthropic.rs new file mode 100644 index 00000000..59d25c3d --- /dev/null +++ b/agent/crates/pi-ai/src/providers/anthropic.rs @@ -0,0 +1,622 @@ +//! Anthropic Messages API provider — streaming via Server-Sent Events. +//! +//! Mirrors `packages/ai/src/providers/anthropic.ts` from the upstream TS. +//! Emits `text_delta`, `thinking_delta`, and `toolcall_delta` events as data +//! arrives. Tool-call input JSON is assembled across `input_json_delta` +//! events and parsed at `content_block_stop` time. + +use std::collections::BTreeMap; + +use async_stream::stream; +use async_trait::async_trait; +use eventsource_stream::Eventsource; +use futures::StreamExt; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::error::{Error, Result}; +use crate::providers::Provider; +use crate::retry::{classify_status, parse_retry_after, with_retry, Attempt, RetryConfig}; +use crate::stream::AssistantMessageEventStream; +use crate::types::{ + now_ms, AssistantMessage, AssistantMessageEvent, CacheRetention, Content, Context, Message, + Model, StopReason, StreamOptions, ThinkingLevel, Usage, +}; + +const ANTHROPIC_VERSION: &str = "2023-06-01"; + +#[derive(Deserialize, Debug)] +#[serde(tag = "type")] +enum SseEvent { + #[serde(rename = "message_start")] + MessageStart { message: MessageStartPayload }, + #[serde(rename = "content_block_start")] + ContentBlockStart { + index: usize, + content_block: BlockStart, + }, + #[serde(rename = "content_block_delta")] + ContentBlockDelta { index: usize, delta: BlockDelta }, + #[serde(rename = "content_block_stop")] + ContentBlockStop { index: usize }, + #[serde(rename = "message_delta")] + MessageDelta { + delta: MessageDeltaPayload, + #[serde(default)] + usage: Option, + }, + #[serde(rename = "message_stop")] + MessageStop, + #[serde(rename = "ping")] + Ping, + #[serde(rename = "error")] + Error { error: ErrorBody }, + #[serde(other)] + Other, +} + +#[derive(Deserialize, Debug)] +struct MessageStartPayload { + #[serde(default)] + model: Option, + #[serde(default)] + usage: Option, +} + +#[derive(Deserialize, Debug)] +#[serde(tag = "type")] +enum BlockStart { + #[serde(rename = "text")] + Text {}, + #[serde(rename = "thinking")] + Thinking {}, + #[serde(rename = "tool_use")] + ToolUse { id: String, name: String }, + #[serde(other)] + Other, +} + +#[derive(Deserialize, Debug)] +#[serde(tag = "type")] +enum BlockDelta { + #[serde(rename = "text_delta")] + TextDelta { text: String }, + #[serde(rename = "thinking_delta")] + ThinkingDelta { thinking: String }, + #[serde(rename = "input_json_delta")] + InputJsonDelta { partial_json: String }, + #[serde(rename = "signature_delta")] + SignatureDelta { signature: String }, + #[serde(other)] + Other, +} + +#[derive(Deserialize, Debug, Default)] +struct MessageDeltaPayload { + #[serde(default)] + stop_reason: Option, +} + +#[derive(Deserialize, Debug, Default)] +struct UsageDelta { + #[serde(default)] + input_tokens: u64, + #[serde(default)] + output_tokens: u64, + #[serde(default)] + cache_read_input_tokens: u64, + #[serde(default)] + cache_creation_input_tokens: u64, +} + +#[derive(Deserialize, Debug)] +struct ErrorBody { + #[serde(rename = "type")] + kind: String, + message: String, +} + +pub struct AnthropicProvider { + client: reqwest::Client, +} + +impl AnthropicProvider { + pub fn new() -> Self { + Self { + // A stalled connection must fail, not hang the turn forever: connecting gets 20 s, and every read + // (the response head, then each streamed chunk) 150 s of silence before it errors (retried before the + // stream starts; an error mid-stream ends the turn with a message). + client: reqwest::Client::builder() + .pool_max_idle_per_host(4) + .connect_timeout(std::time::Duration::from_secs(20)) + .read_timeout(std::time::Duration::from_secs(150)) + .build() + .expect("reqwest client"), + } + } +} + +impl Default for AnthropicProvider { + fn default() -> Self { + Self::new() + } +} + +fn convert_messages(messages: &[Message]) -> Vec { + let mut out = Vec::with_capacity(messages.len()); + for m in messages { + match m { + Message::User { content, .. } => { + let blocks = content.iter().map(content_to_block).collect::>(); + out.push(json!({"role": "user", "content": blocks})); + } + Message::Assistant(a) => { + let blocks = a.content.iter().map(content_to_block).collect::>(); + out.push(json!({"role": "assistant", "content": blocks})); + } + Message::ToolResult(tr) => { + let body: Vec = tr + .content + .iter() + .map(|c| match c { + Content::Text { text } => json!({"type": "text", "text": text}), + Content::Image { data, mime_type } => json!({ + "type": "image", + "source": {"type": "base64", "media_type": mime_type, "data": data} + }), + _ => json!({"type": "text", "text": ""}), + }) + .collect(); + out.push(json!({ + "role": "user", + "content": [{ + "type": "tool_result", + "tool_use_id": tr.tool_call_id, + "content": body, + "is_error": tr.is_error, + }] + })); + } + } + } + out +} + +fn content_to_block(c: &Content) -> Value { + match c { + Content::Text { text } => json!({"type": "text", "text": text}), + Content::Thinking { + thinking, + thinking_signature, + } => { + let mut v = json!({"type": "thinking", "thinking": thinking}); + if let Some(sig) = thinking_signature { + v["signature"] = json!(sig); + } + v + } + Content::Image { data, mime_type } => json!({ + "type": "image", + "source": {"type": "base64", "media_type": mime_type, "data": data} + }), + Content::ToolCall { + id, + name, + arguments, + } => json!({ + "type": "tool_use", + "id": id, + "name": name, + "input": arguments, + }), + } +} + +fn thinking_budget(level: ThinkingLevel) -> Option { + match level { + ThinkingLevel::Off => None, + ThinkingLevel::Minimal => Some(1024), + ThinkingLevel::Low => Some(2048), + ThinkingLevel::Medium => Some(8192), + ThinkingLevel::High => Some(16384), + ThinkingLevel::Xhigh => Some(24576), + } +} + +fn cache_control_json(retention: CacheRetention) -> Option { + match retention { + CacheRetention::None => None, + CacheRetention::Short => Some(json!({"type": "ephemeral"})), + CacheRetention::Long => Some(json!({"type": "ephemeral", "ttl": "1h"})), + } +} + +/// Build the raw Anthropic Messages request body. Exposed for tests/inspection; +/// the streaming path goes through this same function. +pub fn build_request_body(model: &Model, context: &Context, options: &StreamOptions) -> Value { + build_body(model, context, options) +} + +fn build_body(model: &Model, context: &Context, options: &StreamOptions) -> Value { + let cc = cache_control_json(options.cache_retention); + let mut messages = convert_messages(&context.messages); + // The last user-role message: its last block carries the moving breakpoint, whatever it is (a tool step's + // tool_result too; before T-251 only text was marked, so tool steps re-sent the turn so far uncached), and this + // turn's trailing lines follow it, outside the cache. + if let Some(idx) = messages.iter().rposition(|m| m["role"] == "user") { + if let Some(content) = messages[idx].get_mut("content") { + if let Some(s) = content.as_str().map(String::from) { *content = json!([{"type": "text", "text": s}]); } + if let Some(arr) = content.as_array_mut() { + if let (Some(cc), Some(last)) = (&cc, arr.last_mut()) { last["cache_control"] = cc.clone(); } + if let Some(t) = context.trailing.as_deref().filter(|t| !t.trim().is_empty()) { + arr.push(json!({"type": "text", "text": t})); + } + } + } + } + + let mut body = json!({ + "model": model.id, + "max_tokens": options.max_tokens.unwrap_or(model.max_tokens), + "messages": messages, + "stream": true, + }); + if let Some(sp) = &context.system_prompt { + match &cc { + Some(cc) => { + // The stable prompt and the slow-moving suffix each carry a breakpoint (4 in all, the most allowed: these + // two, the last tool, the last message); a turn's moving lines go after the conversation (`trailing`). + let mut blocks = vec![json!({"type": "text", "text": sp, "cache_control": cc})]; + if let Some(suffix) = context.system_suffix.as_deref().filter(|s| !s.trim().is_empty()) { + blocks.push(json!({"type": "text", "text": suffix, "cache_control": cc})); + } + body["system"] = json!(blocks); + } + None => { + body["system"] = json!(Context { trailing: None, ..context.clone() }.full_system().unwrap_or_default()); + } + } + } else if let Some(suffix) = &context.system_suffix { + body["system"] = json!(suffix); + } + if let Some(t) = options.temperature { + body["temperature"] = json!(t); + } + if let Some(level) = options.reasoning { + if let Some(budget) = thinking_budget(level) { + body["thinking"] = json!({"type": "enabled", "budget_tokens": budget}); + } + } + if !context.tools.is_empty() { + let mut tools: Vec = context + .tools + .iter() + .map(|t| { + json!({ + "name": t.name, + "description": t.description, + "input_schema": t.parameters, + }) + }) + .collect(); + if let Some(cc) = &cc { + if let Some(last) = tools.last_mut() { + last["cache_control"] = cc.clone(); + } + } + body["tools"] = json!(tools); + } + // UGC_DUMP_REQUEST=: keep the first request body there, to measure the prompt (G2). Never on by default. + if let Some(path) = std::env::var_os("UGC_DUMP_REQUEST") { + if !std::path::Path::new(&path).exists() { + let _ = std::fs::write(&path, serde_json::to_string_pretty(&body).unwrap_or_default()); + } + } + body +} + +#[derive(Default)] +struct BlockState { + kind: BlockKind, + text_buf: String, + json_buf: String, + tool_id: String, + tool_name: String, + signature: Option, +} + +#[derive(Default, PartialEq, Eq, Clone, Copy)] +enum BlockKind { + #[default] + Unknown, + Text, + Thinking, + ToolUse, +} + +#[async_trait] +impl Provider for AnthropicProvider { + async fn stream( + &self, + model: &Model, + context: &Context, + options: &StreamOptions, + ) -> Result { + let api_key = options + .api_key + .clone() + .or_else(|| std::env::var("ANTHROPIC_API_KEY").ok()) + .ok_or_else(|| Error::MissingApiKey("anthropic".into()))?; + let base_url = options + .base_url + .clone() + .unwrap_or_else(|| model.base_url.clone()); + let url = format!("{}/v1/messages", base_url.trim_end_matches('/')); + let body = build_body(model, context, options); + let cancel = options.cancel.clone(); + let extra_headers: BTreeMap = options.headers.clone(); + + let resp = with_retry(&RetryConfig::default(), cancel.as_ref(), |_attempt| { + let client = self.client.clone(); + let url = url.clone(); + let api_key = api_key.clone(); + let body = body.clone(); + let extra_headers = extra_headers.clone(); + async move { + let mut req = client + .post(&url) + .header("x-api-key", &api_key) + .header("anthropic-version", ANTHROPIC_VERSION) + .header("accept", "text/event-stream") + .header("content-type", "application/json"); + for (k, v) in extra_headers { + req = req.header(k, v); + } + let r = match req.json(&body).send().await { + Ok(r) => r, + Err(e) => { + return if e.is_timeout() || e.is_connect() { + Attempt::Retry { + error: Error::Http(e), + retry_after: None, + } + } else { + Attempt::Fatal(Error::Http(e)) + } + } + }; + let status = r.status(); + if status.is_success() { + return Attempt::Ok(r); + } + let retry_after = r + .headers() + .get("retry-after") + .and_then(|v| v.to_str().ok()) + .and_then(parse_retry_after); + let body = r.text().await.unwrap_or_default(); + let err = Error::ProviderError { + status: status.as_u16(), + body, + }; + match classify_status(status.as_u16()) { + Some(_) => Attempt::Retry { + error: err, + retry_after, + }, + None => Attempt::Fatal(err), + } + } + }) + .await?; + + let api = model.api.clone(); + let provider = model.provider.clone(); + let model_id = model.id.clone(); + let pricing = model.pricing.clone(); + let cancel_for_stream = cancel.clone(); + + let s = stream! { + yield Ok(AssistantMessageEvent::Start); + + let byte_stream = resp.bytes_stream(); + let mut sse = byte_stream.eventsource(); + + let mut blocks: std::collections::HashMap = std::collections::HashMap::new(); + let mut order: Vec = Vec::new(); + let mut stop = StopReason::Stop; + let mut usage = Usage::default(); + let mut response_model: Option = None; + // A reply ends with a stop reason (message_delta) and message_stop; a stream that just stops is cut off. + let mut finished = false; + + while let Some(ev) = sse.next().await { + if let Some(c) = &cancel_for_stream { + if c.is_cancelled() { + yield Err(Error::Cancelled); + return; + } + } + let ev = match ev { + Ok(e) => e, + Err(e) => { + yield Err(Error::InvalidResponse(format!("sse: {e}"))); + return; + } + }; + if ev.data.is_empty() { + continue; + } + let parsed: SseEvent = match serde_json::from_str(&ev.data) { + Ok(p) => p, + Err(_) => continue, + }; + match parsed { + SseEvent::Ping | SseEvent::Other => {} + SseEvent::MessageStart { message } => { + if let Some(m) = message.model { response_model = Some(m); } + if let Some(u) = message.usage { + usage.input += u.input_tokens; + usage.cache_read += u.cache_read_input_tokens; + usage.cache_write += u.cache_creation_input_tokens; + } + } + SseEvent::ContentBlockStart { index, content_block } => { + let st = blocks.entry(index).or_default(); + order.push(index); + match content_block { + BlockStart::Text {} => { + st.kind = BlockKind::Text; + yield Ok(AssistantMessageEvent::TextStart { content_index: index }); + } + BlockStart::Thinking {} => { + st.kind = BlockKind::Thinking; + yield Ok(AssistantMessageEvent::ThinkingStart { content_index: index }); + } + BlockStart::ToolUse { id, name } => { + st.kind = BlockKind::ToolUse; + st.tool_id = id.clone(); + st.tool_name = name.clone(); + yield Ok(AssistantMessageEvent::ToolCallStart { + content_index: index, + id, + name, + }); + } + BlockStart::Other => {} + } + } + SseEvent::ContentBlockDelta { index, delta } => { + let st = blocks.entry(index).or_default(); + match delta { + BlockDelta::TextDelta { text } => { + st.text_buf.push_str(&text); + yield Ok(AssistantMessageEvent::TextDelta { content_index: index, delta: text }); + } + BlockDelta::ThinkingDelta { thinking } => { + st.text_buf.push_str(&thinking); + yield Ok(AssistantMessageEvent::ThinkingDelta { content_index: index, delta: thinking }); + } + BlockDelta::InputJsonDelta { partial_json } => { + st.json_buf.push_str(&partial_json); + yield Ok(AssistantMessageEvent::ToolCallDelta { content_index: index, delta: partial_json }); + } + BlockDelta::SignatureDelta { signature } => { + st.signature = Some(signature); + } + BlockDelta::Other => {} + } + } + SseEvent::ContentBlockStop { index } => { + if let Some(st) = blocks.get(&index) { + match st.kind { + BlockKind::Text => { + yield Ok(AssistantMessageEvent::TextEnd { content_index: index, content: st.text_buf.clone() }); + } + BlockKind::Thinking => { + yield Ok(AssistantMessageEvent::ThinkingEnd { content_index: index, content: st.text_buf.clone() }); + } + BlockKind::ToolUse => { + let args: Value = if st.json_buf.is_empty() { + Value::Object(Default::default()) + } else { + serde_json::from_str(&st.json_buf).unwrap_or(Value::Object(Default::default())) + }; + yield Ok(AssistantMessageEvent::ToolCallEnd { + content_index: index, + id: st.tool_id.clone(), + name: st.tool_name.clone(), + arguments: args, + }); + } + BlockKind::Unknown => {} + } + } + } + SseEvent::MessageDelta { delta, usage: maybe_usage } => { + if let Some(u) = maybe_usage { + usage.output += u.output_tokens; + // Some Anthropic-compatible servers (MiniMax) report input and cache counts here, + // cumulatively, instead of in message_start: keep the larger figure. + usage.input = usage.input.max(u.input_tokens); + usage.cache_read = usage.cache_read.max(u.cache_read_input_tokens); + usage.cache_write = usage.cache_write.max(u.cache_creation_input_tokens); + } + if let Some(reason) = delta.stop_reason { + finished = true; + stop = match reason.as_str() { + "tool_use" => StopReason::ToolUse, + "max_tokens" => StopReason::Length, + "end_turn" | "stop_sequence" => StopReason::Stop, + _ => StopReason::Stop, + }; + } + } + SseEvent::MessageStop => { finished = true; } + SseEvent::Error { error } => { + let err_msg = format!("{}: {}", error.kind, error.message); + let mut err_usage = usage.clone(); + err_usage.cost = err_usage.compute_cost(&pricing); + let am = AssistantMessage { + content: vec![], + api: api.clone(), + provider: provider.clone(), + model: response_model.clone().unwrap_or_else(|| model_id.clone()), + usage: err_usage, + stop_reason: StopReason::Error, + error_message: Some(err_msg), + timestamp: now_ms(), + }; + yield Ok(AssistantMessageEvent::Error { reason: StopReason::Error, error: am }); + return; + } + } + } + + if !finished { + yield Err(Error::InvalidResponse(crate::STREAM_ENDED_EARLY.to_string())); + return; + } + usage.total_tokens = usage.input + usage.output; + usage.cost = usage.compute_cost(&pricing); + let mut out_content = Vec::with_capacity(order.len()); + for idx in &order { + if let Some(st) = blocks.get(idx) { + match st.kind { + BlockKind::Text => out_content.push(Content::Text { text: st.text_buf.clone() }), + BlockKind::Thinking => out_content.push(Content::Thinking { + thinking: st.text_buf.clone(), + thinking_signature: st.signature.clone(), + }), + BlockKind::ToolUse => { + let args: Value = if st.json_buf.is_empty() { + Value::Object(Default::default()) + } else { + serde_json::from_str(&st.json_buf).unwrap_or(Value::Object(Default::default())) + }; + out_content.push(Content::ToolCall { + id: st.tool_id.clone(), + name: st.tool_name.clone(), + arguments: args, + }); + } + BlockKind::Unknown => {} + } + } + } + let message = AssistantMessage { + content: out_content, + api, + provider, + model: response_model.unwrap_or(model_id), + usage, + stop_reason: stop, + error_message: None, + timestamp: now_ms(), + }; + yield Ok(AssistantMessageEvent::Done { reason: stop, message }); + }; + + Ok(s.boxed()) + } +} diff --git a/agent/crates/pi-ai/src/providers/google.rs b/agent/crates/pi-ai/src/providers/google.rs new file mode 100644 index 00000000..894ed3a5 --- /dev/null +++ b/agent/crates/pi-ai/src/providers/google.rs @@ -0,0 +1,371 @@ +//! Google Generative AI provider (`google-generative-ai`). +//! +//! Targets the v1beta `generativelanguage.googleapis.com` endpoint with the +//! `streamGenerateContent` method. Emits the unified `AssistantMessageEvent` +//! protocol like the other providers. +//! +//! The Google SSE format is a JSON array of "candidates" chunks rather than +//! discrete event names, but `eventsource-stream` still works because the +//! server sends `data:` framed records. + +use std::collections::BTreeMap; + +use async_stream::stream; +use async_trait::async_trait; +use eventsource_stream::Eventsource; +use futures::StreamExt; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::error::{Error, Result}; +use crate::providers::Provider; +use crate::retry::{classify_status, parse_retry_after, with_retry, Attempt, RetryConfig}; +use crate::stream::AssistantMessageEventStream; +use crate::types::{ + now_ms, AssistantMessage, AssistantMessageEvent, Content, Context, Message, Model, StopReason, + StreamOptions, Usage, +}; + +#[derive(Deserialize, Debug)] +struct Chunk { + #[serde(default)] + candidates: Vec, + #[serde(default)] + usage_metadata: Option, + #[serde(default)] + model_version: Option, +} + +#[derive(Deserialize, Debug)] +struct Candidate { + #[serde(default)] + content: Option, + #[serde(default)] + finish_reason: Option, +} + +#[derive(Deserialize, Debug)] +struct CandidateContent { + #[serde(default)] + parts: Vec, +} + +#[derive(Deserialize, Debug)] +struct Part { + #[serde(default)] + text: Option, + #[serde(default)] + function_call: Option, +} + +#[derive(Deserialize, Debug)] +struct FunctionCall { + #[serde(default)] + name: String, + #[serde(default)] + args: Value, +} + +#[derive(Deserialize, Debug, Default)] +struct UsageMetadata { + #[serde(default)] + prompt_token_count: u64, + #[serde(default)] + candidates_token_count: u64, + #[serde(default)] + total_token_count: u64, +} + +fn convert_messages(messages: &[Message]) -> Vec { + let mut out: Vec = Vec::new(); + for m in messages { + match m { + Message::User { content, .. } => { + let parts: Vec = content + .iter() + .filter_map(|c| c.as_text().map(|t| json!({"text": t}))) + .collect(); + out.push(json!({"role": "user", "parts": parts})); + } + Message::Assistant(a) => { + let mut parts: Vec = Vec::new(); + for c in &a.content { + match c { + Content::Text { text } => parts.push(json!({"text": text})), + Content::ToolCall { + name, arguments, .. + } => { + parts.push(json!({ + "functionCall": {"name": name, "args": arguments} + })); + } + _ => {} + } + } + out.push(json!({"role": "model", "parts": parts})); + } + Message::ToolResult(tr) => { + let text = tr + .content + .iter() + .filter_map(|c| c.as_text().map(|s| s.to_string())) + .collect::>() + .join(""); + out.push(json!({ + "role": "user", + "parts": [{ + "functionResponse": { + "name": tr.tool_name, + "response": {"output": text, "is_error": tr.is_error} + } + }] + })); + } + } + } + out +} + +fn build_body(context: &Context, options: &StreamOptions) -> Value { + let mut body = json!({ + "contents": convert_messages(&context.messages), + }); + if let Some(sp) = &context.full_system() { + body["systemInstruction"] = json!({"role": "system", "parts": [{"text": sp}]}); + } + if let Some(t) = options.temperature { + body["generationConfig"] = json!({"temperature": t}); + } + if !context.tools.is_empty() { + let decls: Vec = context + .tools + .iter() + .map(|t| { + json!({ + "name": t.name, + "description": t.description, + "parameters": t.parameters, + }) + }) + .collect(); + body["tools"] = json!([{"functionDeclarations": decls}]); + } + body +} + +pub struct GoogleProvider { + client: reqwest::Client, +} + +impl GoogleProvider { + pub fn new() -> Self { + Self { + client: reqwest::Client::new(), + } + } +} + +impl Default for GoogleProvider { + fn default() -> Self { + Self::new() + } +} + +#[async_trait] +impl Provider for GoogleProvider { + async fn stream( + &self, + model: &Model, + context: &Context, + options: &StreamOptions, + ) -> Result { + let api_key = options + .api_key + .clone() + .or_else(|| std::env::var("GOOGLE_API_KEY").ok()) + .or_else(|| std::env::var("GEMINI_API_KEY").ok()) + .ok_or_else(|| Error::MissingApiKey("google".into()))?; + let base_url = options + .base_url + .clone() + .unwrap_or_else(|| model.base_url.clone()); + let url = format!( + "{}/v1beta/models/{}:streamGenerateContent?alt=sse&key={}", + base_url.trim_end_matches('/'), + model.id, + api_key, + ); + let body = build_body(context, options); + let cancel = options.cancel.clone(); + let extra_headers: BTreeMap = options.headers.clone(); + + let resp = with_retry(&RetryConfig::default(), cancel.as_ref(), |_| { + let client = self.client.clone(); + let url = url.clone(); + let body = body.clone(); + let extra_headers = extra_headers.clone(); + async move { + let mut req = client + .post(&url) + .header("accept", "text/event-stream") + .header("content-type", "application/json"); + for (k, v) in extra_headers { + req = req.header(k, v); + } + let r = match req.json(&body).send().await { + Ok(r) => r, + Err(e) => { + return if e.is_timeout() || e.is_connect() { + Attempt::Retry { + error: Error::Http(e), + retry_after: None, + } + } else { + Attempt::Fatal(Error::Http(e)) + }; + } + }; + let status = r.status(); + if status.is_success() { + return Attempt::Ok(r); + } + let retry_after = r + .headers() + .get("retry-after") + .and_then(|v| v.to_str().ok()) + .and_then(parse_retry_after); + let body_text = r.text().await.unwrap_or_default(); + let err = Error::ProviderError { + status: status.as_u16(), + body: body_text, + }; + match classify_status(status.as_u16()) { + Some(_) => Attempt::Retry { + error: err, + retry_after, + }, + None => Attempt::Fatal(err), + } + } + }) + .await?; + + let api = model.api.clone(); + let provider = model.provider.clone(); + let model_id = model.id.clone(); + let pricing = model.pricing.clone(); + let cancel_for_stream = cancel.clone(); + + let s = stream! { + yield Ok(AssistantMessageEvent::Start); + let mut sse = resp.bytes_stream().eventsource(); + + let mut text_buf = String::new(); + let mut text_started = false; + let mut text_index: usize = 0; + let mut tool_blocks: Vec<(String, String, Value)> = Vec::new(); + let mut stop = StopReason::Stop; + let mut usage = Usage::default(); + let mut response_model: Option = None; + + while let Some(ev) = sse.next().await { + if let Some(c) = &cancel_for_stream { + if c.is_cancelled() { yield Err(Error::Cancelled); return; } + } + let ev = match ev { + Ok(e) => e, + Err(e) => { yield Err(Error::InvalidResponse(format!("sse: {e}"))); return; } + }; + if ev.data.is_empty() { continue; } + let chunk: Chunk = match serde_json::from_str(&ev.data) { + Ok(c) => c, + Err(_) => continue, + }; + if let Some(m) = chunk.model_version { response_model = Some(m); } + if let Some(u) = chunk.usage_metadata { + usage.input = u.prompt_token_count; + usage.output = u.candidates_token_count; + usage.total_tokens = u.total_token_count; + } + for cand in chunk.candidates { + if let Some(reason) = cand.finish_reason { + stop = match reason.as_str() { + "STOP" => StopReason::Stop, + "MAX_TOKENS" => StopReason::Length, + _ => StopReason::Stop, + }; + } + if let Some(content) = cand.content { + for part in content.parts { + if let Some(t) = part.text { + if !t.is_empty() { + if !text_started { + text_started = true; + yield Ok(AssistantMessageEvent::TextStart { content_index: text_index }); + } + text_buf.push_str(&t); + yield Ok(AssistantMessageEvent::TextDelta { content_index: text_index, delta: t }); + } + } + if let Some(fc) = part.function_call { + let id = format!("call_{}", tool_blocks.len() + 1); + let block_index = text_index + if text_started { 1 } else { 0 } + tool_blocks.len(); + yield Ok(AssistantMessageEvent::ToolCallStart { + content_index: block_index, + id: id.clone(), + name: fc.name.clone(), + }); + yield Ok(AssistantMessageEvent::ToolCallEnd { + content_index: block_index, + id: id.clone(), + name: fc.name.clone(), + arguments: fc.args.clone(), + }); + if fc.finish_reason_set_to_tool_use() { stop = StopReason::ToolUse; } + tool_blocks.push((id, fc.name, fc.args)); + } + } + } + } + } + + if text_started { + yield Ok(AssistantMessageEvent::TextEnd { content_index: text_index, content: text_buf.clone() }); + text_index += 1; + } + if !tool_blocks.is_empty() && stop == StopReason::Stop { + stop = StopReason::ToolUse; + } + let mut out_content: Vec = Vec::new(); + if text_started { + out_content.push(Content::Text { text: text_buf }); + } + for (id, name, args) in tool_blocks { + out_content.push(Content::ToolCall { id, name, arguments: args }); + } + let _ = text_index; + usage.cost = usage.compute_cost(&pricing); + let message = AssistantMessage { + content: out_content, + api, + provider, + model: response_model.unwrap_or(model_id), + usage, + stop_reason: stop, + error_message: None, + timestamp: now_ms(), + }; + yield Ok(AssistantMessageEvent::Done { reason: stop, message }); + }; + + Ok(s.boxed()) + } +} + +// Helper marker — Gemini doesn't signal tool use in finish_reason; treat any +// function_call as implying ToolUse if no other stop reason is reported. +impl FunctionCall { + fn finish_reason_set_to_tool_use(&self) -> bool { + true + } +} diff --git a/agent/crates/pi-ai/src/providers/mod.rs b/agent/crates/pi-ai/src/providers/mod.rs new file mode 100644 index 00000000..b91691f3 --- /dev/null +++ b/agent/crates/pi-ai/src/providers/mod.rs @@ -0,0 +1,21 @@ +pub mod anthropic; +pub mod google; +pub mod openai; +pub mod openai_responses; + +use async_trait::async_trait; + +use crate::error::Result; +use crate::stream::AssistantMessageEventStream; +use crate::types::{Context, Model, StreamOptions}; + +/// Generic provider interface — invoked by `stream_simple` based on `model.api`. +#[async_trait] +pub trait Provider: Send + Sync { + async fn stream( + &self, + model: &Model, + context: &Context, + options: &StreamOptions, + ) -> Result; +} diff --git a/agent/crates/pi-ai/src/providers/openai.rs b/agent/crates/pi-ai/src/providers/openai.rs new file mode 100644 index 00000000..b2bcdf53 --- /dev/null +++ b/agent/crates/pi-ai/src/providers/openai.rs @@ -0,0 +1,427 @@ +//! OpenAI Chat Completions provider — streaming via Server-Sent Events. +//! +//! Handles arbitrary OpenAI-compatible endpoints by honoring +//! `StreamOptions::base_url`. Works with OpenAI, OpenRouter, Together, Groq, +//! Cerebras, DeepSeek, Fireworks, etc., whose APIs implement the same wire +//! format. + +use std::collections::BTreeMap; + +use async_stream::stream; +use async_trait::async_trait; +use eventsource_stream::Eventsource; +use futures::StreamExt; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::error::{Error, Result}; +use crate::providers::Provider; +use crate::retry::{classify_status, parse_retry_after, with_retry, Attempt, RetryConfig}; +use crate::stream::AssistantMessageEventStream; +use crate::types::{ + now_ms, AssistantMessage, AssistantMessageEvent, Content, Context, Message, Model, StopReason, + StreamOptions, Usage, +}; + +#[derive(Deserialize, Debug)] +struct Chunk { + #[serde(default)] + choices: Vec, + #[serde(default)] + usage: Option, + #[serde(default)] + model: Option, +} + +#[derive(Deserialize, Debug)] +struct ChunkChoice { + #[serde(default)] + delta: Option, + #[serde(default)] + finish_reason: Option, +} + +#[derive(Deserialize, Debug, Default)] +struct ChunkDelta { + #[serde(default)] + content: Option, + #[serde(default)] + tool_calls: Vec, +} + +#[derive(Deserialize, Debug)] +struct ToolCallDelta { + index: usize, + #[serde(default)] + id: Option, + #[serde(default)] + function: Option, +} + +#[derive(Deserialize, Debug, Default)] +struct FunctionDelta { + #[serde(default)] + name: Option, + #[serde(default)] + arguments: Option, +} + +#[derive(Deserialize, Debug, Default)] +struct ChunkUsage { + #[serde(default)] + prompt_tokens: u64, + #[serde(default)] + completion_tokens: u64, + #[serde(default)] + total_tokens: u64, +} + +pub struct OpenAiProvider { + client: reqwest::Client, +} + +impl OpenAiProvider { + pub fn new() -> Self { + Self { + client: reqwest::Client::new(), + } + } +} + +impl Default for OpenAiProvider { + fn default() -> Self { + Self::new() + } +} + +fn convert_messages(system_prompt: Option<&str>, messages: &[Message]) -> Vec { + let mut out: Vec = Vec::new(); + if let Some(sp) = system_prompt { + out.push(json!({"role": "system", "content": sp})); + } + for m in messages { + match m { + Message::User { content, .. } => { + let text = content + .iter() + .filter_map(|c| c.as_text().map(|s| s.to_string())) + .collect::>() + .join(""); + out.push(json!({"role": "user", "content": text})); + } + Message::Assistant(a) => { + let mut text = String::new(); + let mut tool_calls: Vec = Vec::new(); + for c in &a.content { + match c { + Content::Text { text: t } => text.push_str(t), + Content::ToolCall { + id, + name, + arguments, + } => { + tool_calls.push(json!({ + "id": id, + "type": "function", + "function": { + "name": name, + "arguments": arguments.to_string(), + } + })); + } + _ => {} + } + } + let mut msg = json!({"role": "assistant", "content": text}); + if !tool_calls.is_empty() { + msg["tool_calls"] = json!(tool_calls); + } + out.push(msg); + } + Message::ToolResult(tr) => { + let text = tr + .content + .iter() + .filter_map(|c| c.as_text().map(|s| s.to_string())) + .collect::>() + .join(""); + out.push(json!({ + "role": "tool", + "tool_call_id": tr.tool_call_id, + "content": text, + })); + } + } + } + out +} + +fn build_body(model: &Model, context: &Context, options: &StreamOptions) -> Value { + let mut body = json!({ + "model": model.id, + "messages": convert_messages(context.full_system().as_deref(), &context.messages), + "stream": true, + "stream_options": {"include_usage": true}, + }); + if let Some(t) = options.temperature { + body["temperature"] = json!(t); + } + if let Some(m) = options.max_tokens { + body["max_tokens"] = json!(m); + } + if !context.tools.is_empty() { + let tools: Vec = context + .tools + .iter() + .map(|t| { + json!({ + "type": "function", + "function": { + "name": t.name, + "description": t.description, + "parameters": t.parameters, + } + }) + }) + .collect(); + body["tools"] = json!(tools); + } + body +} + +#[derive(Default)] +struct PartialToolCall { + id: String, + name: String, + args: String, +} + +#[async_trait] +impl Provider for OpenAiProvider { + async fn stream( + &self, + model: &Model, + context: &Context, + options: &StreamOptions, + ) -> Result { + let api_key = options + .api_key + .clone() + .or_else(|| std::env::var("OPENAI_API_KEY").ok()) + .ok_or_else(|| Error::MissingApiKey("openai".into()))?; + let base_url = options + .base_url + .clone() + .unwrap_or_else(|| model.base_url.clone()); + let url = format!("{}/chat/completions", base_url.trim_end_matches('/')); + let body = build_body(model, context, options); + let cancel = options.cancel.clone(); + let extra_headers: BTreeMap = options.headers.clone(); + + let resp = with_retry(&RetryConfig::default(), cancel.as_ref(), |_| { + let client = self.client.clone(); + let url = url.clone(); + let api_key = api_key.clone(); + let body = body.clone(); + let extra_headers = extra_headers.clone(); + async move { + let mut req = client + .post(&url) + .bearer_auth(&api_key) + .header("accept", "text/event-stream") + .header("content-type", "application/json"); + for (k, v) in extra_headers { + req = req.header(k, v); + } + let r = match req.json(&body).send().await { + Ok(r) => r, + Err(e) => { + return if e.is_timeout() || e.is_connect() { + Attempt::Retry { + error: Error::Http(e), + retry_after: None, + } + } else { + Attempt::Fatal(Error::Http(e)) + } + } + }; + let status = r.status(); + if status.is_success() { + return Attempt::Ok(r); + } + let retry_after = r + .headers() + .get("retry-after") + .and_then(|v| v.to_str().ok()) + .and_then(parse_retry_after); + let body = r.text().await.unwrap_or_default(); + let err = Error::ProviderError { + status: status.as_u16(), + body, + }; + match classify_status(status.as_u16()) { + Some(_) => Attempt::Retry { + error: err, + retry_after, + }, + None => Attempt::Fatal(err), + } + } + }) + .await?; + + let api = model.api.clone(); + let provider = model.provider.clone(); + let model_id = model.id.clone(); + let pricing = model.pricing.clone(); + let cancel_for_stream = cancel.clone(); + + let s = stream! { + yield Ok(AssistantMessageEvent::Start); + + let mut sse = resp.bytes_stream().eventsource(); + + let mut text_buf = String::new(); + let mut text_started = false; + let mut text_index: usize = 0; + let mut tool_calls: std::collections::BTreeMap = Default::default(); + let mut tool_started: std::collections::BTreeSet = Default::default(); + let mut stop = StopReason::Stop; + let mut usage = Usage::default(); + let mut response_model: Option = None; + + while let Some(ev) = sse.next().await { + if let Some(c) = &cancel_for_stream { + if c.is_cancelled() { + yield Err(Error::Cancelled); + return; + } + } + let ev = match ev { + Ok(e) => e, + Err(e) => { + yield Err(Error::InvalidResponse(format!("sse: {e}"))); + return; + } + }; + if ev.data == "[DONE]" { + break; + } + if ev.data.is_empty() { + continue; + } + let chunk: Chunk = match serde_json::from_str(&ev.data) { + Ok(c) => c, + Err(_) => continue, + }; + if let Some(m) = chunk.model { response_model = Some(m); } + if let Some(u) = chunk.usage { + usage.input = u.prompt_tokens; + usage.output = u.completion_tokens; + usage.total_tokens = u.total_tokens; + } + for choice in chunk.choices { + if let Some(reason) = choice.finish_reason { + stop = match reason.as_str() { + "tool_calls" => StopReason::ToolUse, + "length" => StopReason::Length, + _ => StopReason::Stop, + }; + } + if let Some(delta) = choice.delta { + if let Some(c) = delta.content { + if !c.is_empty() { + if !text_started { + text_started = true; + yield Ok(AssistantMessageEvent::TextStart { content_index: text_index }); + } + text_buf.push_str(&c); + yield Ok(AssistantMessageEvent::TextDelta { + content_index: text_index, + delta: c, + }); + } + } + for tc in delta.tool_calls { + let entry = tool_calls.entry(tc.index).or_default(); + if let Some(id) = tc.id { entry.id = id; } + if let Some(f) = tc.function { + if let Some(n) = f.name { entry.name = n; } + if let Some(a) = f.arguments { + entry.args.push_str(&a); + if !tool_started.contains(&tc.index) { + tool_started.insert(tc.index); + let block_index = text_index + + if text_started { 1 } else { 0 } + + tool_started.len() + - 1; + yield Ok(AssistantMessageEvent::ToolCallStart { + content_index: block_index, + id: entry.id.clone(), + name: entry.name.clone(), + }); + } + let block_index = text_index + + if text_started { 1 } else { 0 } + + tc.index; + yield Ok(AssistantMessageEvent::ToolCallDelta { + content_index: block_index, + delta: a, + }); + } + } + } + } + } + } + + if text_started { + yield Ok(AssistantMessageEvent::TextEnd { + content_index: text_index, + content: text_buf.clone(), + }); + text_index += 1; + } + + let mut out_content: Vec = Vec::new(); + if text_started { + out_content.push(Content::Text { text: text_buf.clone() }); + } + for (i, tc) in tool_calls { + let args: Value = if tc.args.is_empty() { + Value::Object(Default::default()) + } else { + serde_json::from_str(&tc.args).unwrap_or(Value::Object(Default::default())) + }; + let block_index = text_index + i; + yield Ok(AssistantMessageEvent::ToolCallEnd { + content_index: block_index, + id: tc.id.clone(), + name: tc.name.clone(), + arguments: args.clone(), + }); + out_content.push(Content::ToolCall { + id: tc.id, + name: tc.name, + arguments: args, + }); + } + + usage.cost = usage.compute_cost(&pricing); + let message = AssistantMessage { + content: out_content, + api, + provider, + model: response_model.unwrap_or(model_id), + usage, + stop_reason: stop, + error_message: None, + timestamp: now_ms(), + }; + yield Ok(AssistantMessageEvent::Done { reason: stop, message }); + }; + + Ok(s.boxed()) + } +} diff --git a/agent/crates/pi-ai/src/providers/openai_responses.rs b/agent/crates/pi-ai/src/providers/openai_responses.rs new file mode 100644 index 00000000..e288b0a6 --- /dev/null +++ b/agent/crates/pi-ai/src/providers/openai_responses.rs @@ -0,0 +1,434 @@ +//! OpenAI Responses API provider — streaming via Server-Sent Events. +//! +//! Targets the `/responses` endpoint used by OpenAI's reasoning models such as +//! the `o-series` and `gpt-5*` line, which differs from the Chat Completions +//! shape and emits typed `response.*` SSE events. + +use std::collections::BTreeMap; + +use async_stream::stream; +use async_trait::async_trait; +use eventsource_stream::Eventsource; +use futures::StreamExt; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::error::{Error, Result}; +use crate::providers::Provider; +use crate::retry::{classify_status, parse_retry_after, with_retry, Attempt, RetryConfig}; +use crate::stream::AssistantMessageEventStream; +use crate::types::{ + now_ms, AssistantMessage, AssistantMessageEvent, Content, Context, Message, Model, StopReason, + StreamOptions, ThinkingLevel, Usage, +}; + +pub struct OpenAiResponsesProvider { + client: reqwest::Client, +} + +impl OpenAiResponsesProvider { + pub fn new() -> Self { + Self { + client: reqwest::Client::new(), + } + } +} + +impl Default for OpenAiResponsesProvider { + fn default() -> Self { + Self::new() + } +} + +fn reasoning_effort(level: ThinkingLevel) -> Option<&'static str> { + match level { + ThinkingLevel::Off => None, + ThinkingLevel::Minimal | ThinkingLevel::Low => Some("low"), + ThinkingLevel::Medium => Some("medium"), + ThinkingLevel::High | ThinkingLevel::Xhigh => Some("high"), + } +} + +fn convert_input(messages: &[Message]) -> Vec { + let mut out: Vec = Vec::new(); + for m in messages { + match m { + Message::User { content, .. } => { + let text = content + .iter() + .filter_map(|c| c.as_text().map(|s| s.to_string())) + .collect::>() + .join(""); + out.push(json!({ + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": text}], + })); + } + Message::Assistant(a) => { + let mut text = String::new(); + let mut tool_calls: Vec = Vec::new(); + for c in &a.content { + match c { + Content::Text { text: t } => text.push_str(t), + Content::ToolCall { + id, + name, + arguments, + } => { + tool_calls.push(json!({ + "type": "function_call", + "call_id": id, + "name": name, + "arguments": arguments.to_string(), + })); + } + _ => {} + } + } + if !text.is_empty() { + out.push(json!({ + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": text}], + })); + } + for tc in tool_calls { + out.push(tc); + } + } + Message::ToolResult(tr) => { + let text = tr + .content + .iter() + .filter_map(|c| c.as_text().map(|s| s.to_string())) + .collect::>() + .join(""); + out.push(json!({ + "type": "function_call_output", + "call_id": tr.tool_call_id, + "output": text, + })); + } + } + } + out +} + +fn build_body(model: &Model, context: &Context, options: &StreamOptions) -> Value { + let mut body = json!({ + "model": model.id, + "input": convert_input(&context.messages), + "stream": true, + }); + if let Some(sp) = &context.full_system() { + body["instructions"] = json!(sp); + } + if let Some(m) = options.max_tokens { + body["max_output_tokens"] = json!(m); + } + if let Some(t) = options.temperature { + body["temperature"] = json!(t); + } + if let Some(level) = options.reasoning { + if let Some(effort) = reasoning_effort(level) { + body["reasoning"] = json!({"effort": effort}); + } + } + if !context.tools.is_empty() { + let tools: Vec = context + .tools + .iter() + .map(|t| { + json!({ + "type": "function", + "name": t.name, + "description": t.description, + "parameters": t.parameters, + }) + }) + .collect(); + body["tools"] = json!(tools); + } + body +} + +#[derive(Default)] +struct PartialToolCall { + id: String, + name: String, + args: String, +} + +#[derive(Deserialize, Debug, Default)] +struct OutputItemAdded { + #[serde(default)] + item: Option, +} + +#[derive(Deserialize, Debug, Default)] +struct OutputItem { + #[serde(rename = "type", default)] + item_type: String, + #[serde(default)] + id: Option, + #[serde(default)] + call_id: Option, + #[serde(default)] + name: Option, +} + +#[derive(Deserialize, Debug, Default)] +struct DeltaEnvelope { + #[serde(default)] + delta: Option, + #[serde(default)] + item_id: Option, + #[serde(default)] + output_index: Option, +} + +#[async_trait] +impl Provider for OpenAiResponsesProvider { + async fn stream( + &self, + model: &Model, + context: &Context, + options: &StreamOptions, + ) -> Result { + let api_key = options + .api_key + .clone() + .or_else(|| std::env::var("OPENAI_API_KEY").ok()) + .ok_or_else(|| Error::MissingApiKey("openai".into()))?; + let base_url = options + .base_url + .clone() + .unwrap_or_else(|| model.base_url.clone()); + let url = format!("{}/responses", base_url.trim_end_matches('/')); + let body = build_body(model, context, options); + let cancel = options.cancel.clone(); + let extra_headers: BTreeMap = options.headers.clone(); + + let resp = with_retry(&RetryConfig::default(), cancel.as_ref(), |_| { + let client = self.client.clone(); + let url = url.clone(); + let api_key = api_key.clone(); + let body = body.clone(); + let extra_headers = extra_headers.clone(); + async move { + let mut req = client + .post(&url) + .bearer_auth(&api_key) + .header("accept", "text/event-stream") + .header("content-type", "application/json"); + for (k, v) in extra_headers { + req = req.header(k, v); + } + let r = match req.json(&body).send().await { + Ok(r) => r, + Err(e) => { + return if e.is_timeout() || e.is_connect() { + Attempt::Retry { + error: Error::Http(e), + retry_after: None, + } + } else { + Attempt::Fatal(Error::Http(e)) + } + } + }; + let status = r.status(); + if status.is_success() { + return Attempt::Ok(r); + } + let retry_after = r + .headers() + .get("retry-after") + .and_then(|v| v.to_str().ok()) + .and_then(parse_retry_after); + let body = r.text().await.unwrap_or_default(); + let err = Error::ProviderError { + status: status.as_u16(), + body, + }; + match classify_status(status.as_u16()) { + Some(_) => Attempt::Retry { + error: err, + retry_after, + }, + None => Attempt::Fatal(err), + } + } + }) + .await?; + + let api = model.api.clone(); + let provider = model.provider.clone(); + let model_id = model.id.clone(); + let cancel_for_stream = cancel.clone(); + + let s = stream! { + yield Ok(AssistantMessageEvent::Start); + + let mut sse = resp.bytes_stream().eventsource(); + + let mut text_buf = String::new(); + let mut text_started = false; + let mut text_index: usize = 0; + // Map response output_index → local accumulator index. + let mut item_index_map: std::collections::BTreeMap = Default::default(); + let mut tool_calls: Vec = Vec::new(); + let mut tool_started: std::collections::BTreeSet = Default::default(); + let mut stop = StopReason::Stop; + let usage = Usage::default(); + + while let Some(ev) = sse.next().await { + if let Some(c) = &cancel_for_stream { + if c.is_cancelled() { + yield Err(Error::Cancelled); + return; + } + } + let ev = match ev { + Ok(e) => e, + Err(e) => { + yield Err(Error::InvalidResponse(format!("sse: {e}"))); + return; + } + }; + if ev.data.is_empty() { + continue; + } + match ev.event.as_str() { + "response.output_text.delta" => { + let env: DeltaEnvelope = match serde_json::from_str(&ev.data) { + Ok(v) => v, + Err(_) => continue, + }; + if let Some(d) = env.delta { + if !d.is_empty() { + if !text_started { + text_started = true; + yield Ok(AssistantMessageEvent::TextStart { content_index: text_index }); + } + text_buf.push_str(&d); + yield Ok(AssistantMessageEvent::TextDelta { + content_index: text_index, + delta: d, + }); + } + } + } + "response.output_item.added" => { + let added: OutputItemAdded = match serde_json::from_str(&ev.data) { + Ok(v) => v, + Err(_) => continue, + }; + let Some(item) = added.item else { continue }; + if item.item_type != "function_call" { + continue; + } + let id = item.call_id.or(item.id.clone()).unwrap_or_default(); + let name = item.name.unwrap_or_default(); + let idx = tool_calls.len(); + tool_calls.push(PartialToolCall { + id: id.clone(), + name: name.clone(), + args: String::new(), + }); + if let Some(item_id) = item.id { + item_index_map.insert(item_id, idx); + } + let block_index = text_index + + if text_started { 1 } else { 0 } + + idx; + tool_started.insert(idx); + yield Ok(AssistantMessageEvent::ToolCallStart { + content_index: block_index, + id, + name, + }); + } + "response.function_call_arguments.delta" => { + let env: DeltaEnvelope = match serde_json::from_str(&ev.data) { + Ok(v) => v, + Err(_) => continue, + }; + let Some(d) = env.delta else { continue }; + let idx = env + .item_id + .as_ref() + .and_then(|id| item_index_map.get(id).copied()) + .or(env.output_index) + .unwrap_or_else(|| tool_calls.len().saturating_sub(1)); + if let Some(entry) = tool_calls.get_mut(idx) { + entry.args.push_str(&d); + let block_index = text_index + + if text_started { 1 } else { 0 } + + idx; + yield Ok(AssistantMessageEvent::ToolCallDelta { + content_index: block_index, + delta: d, + }); + } + } + "response.completed" => { + break; + } + _ => {} + } + } + + if text_started { + yield Ok(AssistantMessageEvent::TextEnd { + content_index: text_index, + content: text_buf.clone(), + }); + text_index += 1; + } + + if !tool_calls.is_empty() { + stop = StopReason::ToolUse; + } + + let mut out_content: Vec = Vec::new(); + if text_started { + out_content.push(Content::Text { text: text_buf.clone() }); + } + for (i, tc) in tool_calls.into_iter().enumerate() { + let args: Value = if tc.args.is_empty() { + Value::Object(Default::default()) + } else { + serde_json::from_str(&tc.args).unwrap_or(Value::Object(Default::default())) + }; + let block_index = text_index + i; + yield Ok(AssistantMessageEvent::ToolCallEnd { + content_index: block_index, + id: tc.id.clone(), + name: tc.name.clone(), + arguments: args.clone(), + }); + out_content.push(Content::ToolCall { + id: tc.id, + name: tc.name, + arguments: args, + }); + } + + let message = AssistantMessage { + content: out_content, + api, + provider, + model: model_id, + usage, + stop_reason: stop, + error_message: None, + timestamp: now_ms(), + }; + yield Ok(AssistantMessageEvent::Done { reason: stop, message }); + }; + + Ok(s.boxed()) + } +} diff --git a/agent/crates/pi-ai/src/retry.rs b/agent/crates/pi-ai/src/retry.rs new file mode 100644 index 00000000..3fd571bd --- /dev/null +++ b/agent/crates/pi-ai/src/retry.rs @@ -0,0 +1,113 @@ +//! Shared retry helper used by HTTP-backed providers. +//! +//! Retries on transient failures (5xx, 429) with exponential back-off. If the +//! response includes a `Retry-After` header, the delay honors it (capped at +//! `max_retry_delay`). + +use std::time::Duration; + +use tokio::time::sleep; +use tokio_util::sync::CancellationToken; + +use crate::error::{Error, Result}; + +#[derive(Debug, Clone)] +pub struct RetryConfig { + pub max_attempts: u32, + pub base_delay: Duration, + pub max_delay: Duration, +} + +impl Default for RetryConfig { + fn default() -> Self { + Self { + max_attempts: 3, + base_delay: Duration::from_millis(500), + max_delay: Duration::from_secs(60), + } + } +} + +/// Outcome of a single attempt. +#[allow(clippy::large_enum_variant)] +pub enum Attempt { + Ok(T), + /// Permanent failure — return immediately. + Fatal(Error), + /// Transient failure — try again. `retry_after` is the server-hinted delay. + Retry { + error: Error, + retry_after: Option, + }, +} + +pub async fn with_retry( + cfg: &RetryConfig, + cancel: Option<&CancellationToken>, + mut f: F, +) -> Result +where + F: FnMut(u32) -> Fut, + Fut: std::future::Future>, +{ + let mut attempt: u32 = 0; + let mut last_err: Option; + loop { + if let Some(c) = cancel { + if c.is_cancelled() { + return Err(Error::Cancelled); + } + } + attempt += 1; + match f(attempt).await { + Attempt::Ok(v) => return Ok(v), + Attempt::Fatal(e) => return Err(e), + Attempt::Retry { error, retry_after } => { + last_err = Some(error); + let _ = &last_err; + if attempt >= cfg.max_attempts { + break; + } + let backoff = cfg + .base_delay + .saturating_mul(1u32 << attempt.min(6)) + .min(cfg.max_delay); + let delay = retry_after.map(|d| d.min(cfg.max_delay)).unwrap_or(backoff); + tracing::warn!(?delay, attempt, "retrying after transient error"); + tokio::select! { + _ = sleep(delay) => {}, + _ = async { + if let Some(c) = cancel { c.cancelled().await; } + else { futures::future::pending::<()>().await; } + } => return Err(Error::Cancelled), + } + } + } + } + Err(Error::RetryExhausted { + attempts: attempt, + source: Box::new(last_err.unwrap_or_else(|| Error::Other("retry exhausted".into()))), + }) +} + +/// Classify a status code into retry-worthy categories. +pub fn classify_status(status: u16) -> Option { + match status { + 429 => Some(ClassifiedStatus::RateLimited), + 500..=599 => Some(ClassifiedStatus::ServerError), + _ => None, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClassifiedStatus { + RateLimited, + ServerError, +} + +pub fn parse_retry_after(value: &str) -> Option { + if let Ok(seconds) = value.trim().parse::() { + return Some(Duration::from_secs(seconds)); + } + None +} diff --git a/agent/crates/pi-ai/src/stream.rs b/agent/crates/pi-ai/src/stream.rs new file mode 100644 index 00000000..e210ca16 --- /dev/null +++ b/agent/crates/pi-ai/src/stream.rs @@ -0,0 +1,9 @@ +use futures::stream::BoxStream; + +use crate::error::Result; +use crate::types::AssistantMessageEvent; + +/// A stream of `AssistantMessageEvent`s, terminating with either `Done` or `Error`. +/// +/// Equivalent to `AssistantMessageEventStream` in pi-ai TS. +pub type AssistantMessageEventStream = BoxStream<'static, Result>; diff --git a/agent/crates/pi-ai/src/types.rs b/agent/crates/pi-ai/src/types.rs new file mode 100644 index 00000000..eefb2c43 --- /dev/null +++ b/agent/crates/pi-ai/src/types.rs @@ -0,0 +1,437 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Anthropic prompt-cache retention hint. When non-`None`, the Anthropic +/// provider stamps `cache_control` markers on the system prompt, the last tool +/// definition, and the last text block of the last user message. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CacheRetention { + #[default] + None, + Short, + Long, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ThinkingLevel { + #[default] + Off, + Minimal, + Low, + Medium, + High, + Xhigh, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum Content { + #[serde(rename = "text")] + Text { text: String }, + #[serde(rename = "thinking")] + Thinking { + thinking: String, + #[serde(skip_serializing_if = "Option::is_none", default)] + thinking_signature: Option, + }, + #[serde(rename = "image")] + Image { data: String, mime_type: String }, + #[serde(rename = "toolCall")] + ToolCall { + id: String, + name: String, + #[serde(default)] + arguments: Value, + }, +} + +impl Content { + pub fn text(s: impl Into) -> Self { + Content::Text { text: s.into() } + } + pub fn as_text(&self) -> Option<&str> { + if let Content::Text { text } = self { + Some(text) + } else { + None + } + } +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Usage { + #[serde(default)] + pub input: u64, + #[serde(default)] + pub output: u64, + #[serde(default)] + pub cache_read: u64, + #[serde(default)] + pub cache_write: u64, + #[serde(default)] + pub total_tokens: u64, + #[serde(default)] + pub cost: Cost, +} + +/// Accumulated USD cost for a single assistant message, broken down by +/// input / output / cache-read / cache-write token classes. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Cost { + #[serde(default)] + pub input: f64, + #[serde(default)] + pub output: f64, + #[serde(default)] + pub cache_read: f64, + #[serde(default)] + pub cache_write: f64, + #[serde(default)] + pub total: f64, +} + +/// Per-million-token USD pricing for a model. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct ModelPricing { + #[serde(default)] + pub input: f64, + #[serde(default)] + pub output: f64, + #[serde(default)] + pub cache_read: f64, + #[serde(default)] + pub cache_write: f64, +} + +impl Usage { + /// Compute the USD cost of this usage given a model's pricing. + pub fn compute_cost(&self, p: &ModelPricing) -> Cost { + let input = self.input as f64 * p.input / 1_000_000.0; + let output = self.output as f64 * p.output / 1_000_000.0; + let cache_read = self.cache_read as f64 * p.cache_read / 1_000_000.0; + let cache_write = self.cache_write as f64 * p.cache_write / 1_000_000.0; + Cost { + input, + output, + cache_read, + cache_write, + total: input + output + cache_read + cache_write, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum StopReason { + Stop, + Length, + ToolUse, + Error, + Aborted, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "role", rename_all = "camelCase")] +pub enum Message { + #[serde(rename = "user")] + User { + content: Vec, + #[serde(default = "now_ms")] + timestamp: i64, + }, + #[serde(rename = "assistant")] + Assistant(AssistantMessage), + #[serde(rename = "toolResult")] + ToolResult(ToolResultMessage), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AssistantMessage { + pub content: Vec, + pub api: String, + pub provider: String, + pub model: String, + #[serde(default)] + pub usage: Usage, + pub stop_reason: StopReason, + #[serde(skip_serializing_if = "Option::is_none", default)] + pub error_message: Option, + #[serde(default = "now_ms")] + pub timestamp: i64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolResultMessage { + pub tool_call_id: String, + pub tool_name: String, + pub content: Vec, + pub is_error: bool, + #[serde(default = "now_ms")] + pub timestamp: i64, +} + +impl Message { + pub fn user_text(s: impl Into) -> Self { + Message::User { + content: vec![Content::text(s)], + timestamp: now_ms(), + } + } +} + +pub fn now_ms() -> i64 { + chrono::Utc::now().timestamp_millis() +} + +/// Tool schema definition matching the unified pi-ai Tool interface. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Tool { + pub name: String, + pub description: String, + /// JSON Schema for the tool parameters (object schema). + pub parameters: Value, +} + +#[derive(Debug, Clone, Default)] +pub struct Context { + pub system_prompt: Option, + /// Instructions that change now and then (the date, the projects), sent after the system prompt as their own + /// cached block. the host app addition. + pub system_suffix: Option, + pub messages: Vec, + pub tools: Vec, + /// This turn's moving lines (what's on screen, a spoken turn's note), sent after the conversation, past the last + /// cache breakpoint: a new screen doesn't cost the cached history (T-251; before, they sat ahead of it). the host app + /// addition. + pub trailing: Option, +} + +impl Context { + /// The system prompt, the suffix and this turn's trailing lines as one text, for providers without separate blocks. + pub fn full_system(&self) -> Option { + let parts: Vec<&str> = [&self.system_prompt, &self.system_suffix, &self.trailing].into_iter().flatten().map(String::as_str).collect(); + (!parts.is_empty()).then(|| parts.concat()) + } +} + +#[derive(Debug, Clone, Default)] +pub struct StreamOptions { + pub temperature: Option, + pub max_tokens: Option, + pub api_key: Option, + pub reasoning: Option, + /// Cancellation token honored by the provider HTTP client and SSE loop. + pub cancel: Option, + /// Override base URL (used by OpenAI-compatible passthrough providers). + pub base_url: Option, + /// Optional custom request headers. + pub headers: std::collections::BTreeMap, + /// Anthropic prompt-cache marker mode. Defaults to `None` (no markers). + pub cache_retention: CacheRetention, +} + +/// Model descriptor — analogous to the Model interface in pi-ai. +#[derive(Debug, Clone)] +pub struct Model { + pub id: String, + pub name: String, + pub api: String, + pub provider: String, + pub base_url: String, + pub reasoning: bool, + pub context_window: u32, + pub max_tokens: u32, + pub pricing: ModelPricing, +} + +impl Model { + /// Anthropic Claude Sonnet 4.6. + pub fn anthropic_claude_sonnet_4_6() -> Self { + Self { + id: "claude-sonnet-4-6".into(), + name: "Claude Sonnet 4.6".into(), + api: "anthropic-messages".into(), + provider: "anthropic".into(), + base_url: "https://api.anthropic.com".into(), + reasoning: true, + context_window: 200_000, + max_tokens: 8_192, + pricing: ModelPricing { + input: 3.0, + output: 15.0, + cache_read: 0.30, + cache_write: 3.75, + }, + } + } + + pub fn anthropic_claude_opus_4_7() -> Self { + Self { + id: "claude-opus-4-7".into(), + name: "Claude Opus 4.7".into(), + api: "anthropic-messages".into(), + provider: "anthropic".into(), + base_url: "https://api.anthropic.com".into(), + reasoning: true, + context_window: 200_000, + max_tokens: 8_192, + pricing: ModelPricing { + input: 15.0, + output: 75.0, + cache_read: 1.50, + cache_write: 18.75, + }, + } + } + + pub fn openai_gpt_4o_mini() -> Self { + Self { + id: "gpt-4o-mini".into(), + name: "GPT-4o mini".into(), + api: "openai-completions".into(), + provider: "openai".into(), + base_url: "https://api.openai.com/v1".into(), + reasoning: false, + context_window: 128_000, + max_tokens: 16_384, + pricing: ModelPricing { + input: 0.15, + output: 0.60, + cache_read: 0.0, + cache_write: 0.0, + }, + } + } + + pub fn openai_gpt_4o() -> Self { + Self { + id: "gpt-4o".into(), + name: "GPT-4o".into(), + api: "openai-completions".into(), + provider: "openai".into(), + base_url: "https://api.openai.com/v1".into(), + reasoning: false, + context_window: 128_000, + max_tokens: 16_384, + pricing: ModelPricing { + input: 2.50, + output: 10.0, + cache_read: 0.0, + cache_write: 0.0, + }, + } + } + + /// OpenAI GPT-5 — reasoning model accessed via the Responses API. + pub fn openai_gpt_5() -> Self { + Self { + id: "gpt-5".into(), + name: "GPT-5".into(), + api: "openai-responses".into(), + provider: "openai".into(), + base_url: "https://api.openai.com/v1".into(), + reasoning: true, + context_window: 200_000, + max_tokens: 16_384, + // Pricing TBD — placeholder zeros until OpenAI publishes the rate card. + pricing: ModelPricing::default(), + } + } + + pub fn gemini_2_0_flash() -> Self { + Self { + id: "gemini-2.0-flash".into(), + name: "Gemini 2.0 Flash".into(), + api: "google-generative-ai".into(), + provider: "google".into(), + base_url: "https://generativelanguage.googleapis.com".into(), + reasoning: false, + context_window: 1_000_000, + max_tokens: 8_192, + pricing: ModelPricing { + input: 0.10, + output: 0.40, + cache_read: 0.0, + cache_write: 0.0, + }, + } + } + + /// OpenAI-compatible passthrough: any provider whose API matches OpenAI Chat + /// Completions (OpenRouter, Together, Groq, Cerebras, DeepSeek, Fireworks, + /// xAI, etc.). Construct via `openai_compat("groq", "...", "...", ...)` + /// or by overriding `base_url`. + pub fn openai_compat( + provider: impl Into, + id: impl Into, + base_url: impl Into, + context_window: u32, + max_tokens: u32, + ) -> Self { + let id = id.into(); + Self { + name: id.clone(), + id, + api: "openai-completions".into(), + provider: provider.into(), + base_url: base_url.into(), + reasoning: false, + context_window, + max_tokens, + pricing: ModelPricing::default(), + } + } +} + +/// Events emitted by streaming completions, matching `AssistantMessageEvent` in pi-ai. +#[derive(Debug, Clone)] +pub enum AssistantMessageEvent { + Start, + TextStart { + content_index: usize, + }, + TextDelta { + content_index: usize, + delta: String, + }, + TextEnd { + content_index: usize, + content: String, + }, + ThinkingStart { + content_index: usize, + }, + ThinkingDelta { + content_index: usize, + delta: String, + }, + ThinkingEnd { + content_index: usize, + content: String, + }, + ToolCallStart { + content_index: usize, + id: String, + name: String, + }, + ToolCallDelta { + content_index: usize, + delta: String, + }, + ToolCallEnd { + content_index: usize, + id: String, + name: String, + arguments: Value, + }, + Done { + reason: StopReason, + message: AssistantMessage, + }, + Error { + reason: StopReason, + error: AssistantMessage, + }, +} diff --git a/agent/crates/pi-ai/tests/anthropic_cache.rs b/agent/crates/pi-ai/tests/anthropic_cache.rs new file mode 100644 index 00000000..f4949a76 --- /dev/null +++ b/agent/crates/pi-ai/tests/anthropic_cache.rs @@ -0,0 +1,167 @@ +//! Integration test for Anthropic prompt-cache markers. +//! +//! Asserts that the Anthropic request body emits `cache_control` on the +//! system prompt block, the last tool definition, and the last text block +//! of the last user message when `StreamOptions::cache_retention` is +//! non-`None`. With the default (`None`), no markers are emitted and the +//! system prompt stays a plain string for backward compatibility. + +use pi_ai::providers::anthropic::build_request_body; +use pi_ai::{CacheRetention, Content, Context, Message, Model, StreamOptions, Tool}; +use serde_json::json; + +fn ctx_with_one_of_each() -> Context { + Context { + system_prompt: Some("you are pi.".into()), + system_suffix: None, + trailing: None, + messages: vec![ + Message::User { + content: vec![Content::text("hello")], + timestamp: 0, + }, + Message::user_text("second turn"), + ], + tools: vec![ + Tool { + name: "first".into(), + description: "first tool".into(), + parameters: json!({"type": "object", "properties": {}}), + }, + Tool { + name: "last".into(), + description: "last tool".into(), + parameters: json!({"type": "object", "properties": {}}), + }, + ], + } +} + +#[test] +fn cache_retention_short_marks_system_tools_and_last_user() { + let model = Model::anthropic_claude_sonnet_4_6(); + let ctx = ctx_with_one_of_each(); + let opt = StreamOptions { + cache_retention: CacheRetention::Short, + ..Default::default() + }; + let body = build_request_body(&model, &ctx, &opt); + + // System prompt is now an array, first block has cache_control: ephemeral. + let sys = &body["system"]; + assert!(sys.is_array(), "system should be an array form"); + assert_eq!(sys[0]["type"], "text"); + assert_eq!(sys[0]["text"], "you are pi."); + assert_eq!(sys[0]["cache_control"]["type"], "ephemeral"); + assert!(sys[0]["cache_control"].get("ttl").is_none()); + + // Tools: last entry has cache_control, earlier entries do not. + let tools = body["tools"].as_array().unwrap(); + assert_eq!(tools.len(), 2); + assert!(tools[0].get("cache_control").is_none()); + assert_eq!(tools[1]["cache_control"]["type"], "ephemeral"); + + // Last user message's last text block has cache_control. + let messages = body["messages"].as_array().unwrap(); + let last_user = messages + .iter() + .rfind(|m| m["role"] == "user") + .expect("last user"); + let blocks = last_user["content"].as_array().unwrap(); + let last_text = blocks + .iter() + .rfind(|b| b["type"] == "text") + .expect("text block"); + assert_eq!(last_text["cache_control"]["type"], "ephemeral"); + + // Earlier user messages should not be marked. + let first_user = messages + .iter() + .find(|m| m["role"] == "user") + .expect("first user"); + let first_blocks = first_user["content"].as_array().unwrap(); + assert!(first_blocks[0].get("cache_control").is_none()); +} + +#[test] +fn cache_retention_long_adds_ttl_1h() { + let model = Model::anthropic_claude_sonnet_4_6(); + let ctx = ctx_with_one_of_each(); + let opt = StreamOptions { + cache_retention: CacheRetention::Long, + ..Default::default() + }; + let body = build_request_body(&model, &ctx, &opt); + assert_eq!(body["system"][0]["cache_control"]["type"], "ephemeral"); + assert_eq!(body["system"][0]["cache_control"]["ttl"], "1h"); + let tools = body["tools"].as_array().unwrap(); + assert_eq!(tools.last().unwrap()["cache_control"]["ttl"], "1h"); +} + +#[test] +fn cache_retention_none_keeps_legacy_shape() { + let model = Model::anthropic_claude_sonnet_4_6(); + let ctx = ctx_with_one_of_each(); + let opt = StreamOptions::default(); + assert_eq!(opt.cache_retention, CacheRetention::None); + let body = build_request_body(&model, &ctx, &opt); + // System stays a plain string. + assert_eq!(body["system"], json!("you are pi.")); + // Tools have no cache_control. + for t in body["tools"].as_array().unwrap() { + assert!(t.get("cache_control").is_none()); + } + // Last user message text has no cache_control. + let messages = body["messages"].as_array().unwrap(); + let last_user = messages.iter().rfind(|m| m["role"] == "user").unwrap(); + for b in last_user["content"].as_array().unwrap() { + assert!(b.get("cache_control").is_none()); + } +} + +#[test] +fn the_suffix_is_cached_and_a_turns_moving_lines_follow_the_conversation() { + // T-251: the slow-moving suffix (the date, the projects) is its own cached block; what's on screen and a spoken + // turn's note go after the last message's breakpoint, so a new screen doesn't cost the cached history. + let model = Model::anthropic_claude_sonnet_4_6(); + let mut ctx = ctx_with_one_of_each(); + ctx.system_suffix = Some("\n\nToday is Sunday.".into()); + ctx.trailing = Some("\n\nThe user is on the Brief card.".into()); + let cached = build_request_body(&model, &ctx, &StreamOptions { cache_retention: CacheRetention::Short, ..Default::default() }); + let sys = cached["system"].as_array().expect("blocks"); + assert_eq!(sys.len(), 2); + assert_eq!((sys[0]["text"].as_str(), sys[0]["cache_control"]["type"].as_str()), (Some("you are pi."), Some("ephemeral"))); + assert_eq!((sys[1]["text"].as_str(), sys[1]["cache_control"]["type"].as_str()), (Some("\n\nToday is Sunday."), Some("ephemeral"))); + let last = cached["messages"].as_array().unwrap().last().unwrap()["content"].as_array().unwrap().clone(); + assert_eq!((last[0]["text"].as_str(), last[0]["cache_control"]["type"].as_str()), (Some("second turn"), Some("ephemeral"))); + assert_eq!(last[1], json!({"type": "text", "text": "\n\nThe user is on the Brief card."}), "after the breakpoint, unmarked"); + assert!(!cached["system"].to_string().contains("Brief card")); + // Without caching: the prompt and suffix as one text, the moving lines still after the conversation. + let plain = build_request_body(&model, &ctx, &StreamOptions::default()); + assert_eq!(plain["system"], json!("you are pi.\n\nToday is Sunday.")); + assert!(plain["messages"].to_string().contains("Brief card")); +} + +#[test] +fn a_tool_steps_breakpoint_is_on_its_tool_result() { + // T-251: in a tool step the last user-role message holds only tool results; it carries the breakpoint, so the + // step after reads the turn so far from the cache. + use pi_ai::{AssistantMessage, StopReason, ToolResultMessage}; + let model = Model::anthropic_claude_sonnet_4_6(); + let mut ctx = ctx_with_one_of_each(); + ctx.messages.push(Message::Assistant(AssistantMessage { + content: vec![Content::ToolCall { id: "t1".into(), name: "first".into(), arguments: json!({}) }], + api: "anthropic-messages".into(), provider: "anthropic".into(), model: "m".into(), usage: Default::default(), + stop_reason: StopReason::ToolUse, error_message: None, timestamp: 0 })); + ctx.messages.push(Message::ToolResult(ToolResultMessage { tool_call_id: "t1".into(), tool_name: "first".into(), + content: vec![Content::text("done")], is_error: false, timestamp: 0 })); + ctx.trailing = Some("\n\nOn screen: the shot list.".into()); + let body = build_request_body(&model, &ctx, &StreamOptions { cache_retention: CacheRetention::Short, ..Default::default() }); + let messages = body["messages"].as_array().unwrap(); + let last = messages.last().unwrap()["content"].as_array().unwrap(); + assert_eq!(last[0]["type"], "tool_result"); + assert_eq!(last[0]["cache_control"]["type"], "ephemeral"); + assert_eq!(last[1]["text"], "\n\nOn screen: the shot list."); + let marks = body.to_string().matches("\"cache_control\"").count(); + assert!(marks <= 4, "at most 4 breakpoints, found {marks}"); +} diff --git a/agent/crates/pi-ai/tests/types_smoke.rs b/agent/crates/pi-ai/tests/types_smoke.rs new file mode 100644 index 00000000..5de70f11 --- /dev/null +++ b/agent/crates/pi-ai/tests/types_smoke.rs @@ -0,0 +1,35 @@ +//! Smoke tests for pi-ai serialization. No network access. + +use pi_ai::{Content, Message, StopReason}; +use serde_json::json; + +#[test] +fn round_trip_user_message() { + let m = Message::user_text("hello"); + let v = serde_json::to_value(&m).unwrap(); + assert_eq!(v["role"], "user"); + assert_eq!(v["content"][0]["type"], "text"); + assert_eq!(v["content"][0]["text"], "hello"); +} + +#[test] +fn round_trip_tool_call_content() { + let c = Content::ToolCall { + id: "call_1".into(), + name: "read".into(), + arguments: json!({"path": "/tmp/x"}), + }; + let v = serde_json::to_value(&c).unwrap(); + assert_eq!(v["type"], "toolCall"); + assert_eq!(v["id"], "call_1"); + assert_eq!(v["arguments"]["path"], "/tmp/x"); +} + +#[test] +fn stop_reason_serializes_camel_case() { + assert_eq!( + serde_json::to_value(StopReason::ToolUse).unwrap(), + "toolUse" + ); + assert_eq!(serde_json::to_value(StopReason::Stop).unwrap(), "stop"); +} diff --git a/agent/crates/raea-spec/Cargo.toml b/agent/crates/raea-spec/Cargo.toml new file mode 100644 index 00000000..40743f10 --- /dev/null +++ b/agent/crates/raea-spec/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "raea-spec" +version = "0.1.0" +edition = "2021" +description = "Gherkin for the Agent harness: Features, Rules, Backgrounds, Scenarios and tags, for agent harnesses (moved from ugc-spec, host agent/harness.feature stage 1)" + +[dependencies] diff --git a/agent/crates/raea-spec/src/lib.rs b/agent/crates/raea-spec/src/lib.rs new file mode 100644 index 00000000..9d96f16b --- /dev/null +++ b/agent/crates/raea-spec/src/lib.rs @@ -0,0 +1,498 @@ +//! Gherkin for the Agent harness (agent/harness.feature, stage 1): one parser for the evals (agent/evals/features), +//! the skill's playbooks, the product specs (docs/creator-lifecycle) and, later, the prompt rules. It keeps what the +//! harness needs and Cucumber's own tools don't give a Rust build: `Rule:` blocks with their own Background, tags at +//! every level (`@eval`, `@gap`, `@name:`, `@k:K-12`, `@claim:`, `@cite:`, `@knob:`), docstrings, +//! data tables and each scenario's source lines (the reviewer reads a scenario's own Gherkin). +//! +//! Std only. Line numbers are 1-based; `start..end` ranges are 0-based line indexes into the source, end exclusive. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Keyword { Given, When, Then } + +#[derive(Debug, Clone, PartialEq)] +pub struct Step { + pub keyword: Keyword, + /// The step's text after its keyword word (`Given`, `And`, `*`…), trimmed. + pub text: String, + /// A docstring under the step, its indentation removed. + pub doc: Option, + /// A data table under the step: rows of trimmed cells. + pub table: Option>>, + pub line: usize, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Background { + pub steps: Vec, + /// The Background's source lines (keyword through its last step or docstring). + pub start: usize, + pub end: usize, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Scenario { + pub name: String, + /// The scenario's own tags (see `Feature::tags_of` for the inherited ones). + pub tags: Vec, + /// Free text between the title and the first step. + pub description: Vec, + pub steps: Vec, + /// A Scenario Outline (or Template), with its Examples tables. + pub outline: bool, + pub examples: Vec>>, + pub line: usize, + /// From its first tag line to the next scenario, rule or the end. + pub start: usize, + pub end: usize, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Rule { + pub name: String, + pub tags: Vec, + pub description: Vec, + pub background: Option, + pub scenarios: Vec, + pub line: usize, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Feature { + pub name: String, + pub tags: Vec, + pub description: Vec, + pub background: Option, + /// Scenarios before any Rule. + pub scenarios: Vec, + pub rules: Vec, + pub line: usize, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ParseError { pub line: usize, pub message: String } + +impl std::fmt::Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "line {}: {}", self.line, self.message) } +} + +/// A parsed file: the Feature (None when the file has none) and what couldn't be read. Parsing goes on past an +/// error, so one bad line doesn't hide the rest of the file. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Document { + pub feature: Option, + pub errors: Vec, +} + +impl Feature { + /// Every scenario with the Rule it sits under, in file order. + pub fn all_scenarios(&self) -> Vec<(Option<&Rule>, &Scenario)> { + let mut out: Vec<(Option<&Rule>, &Scenario)> = self.scenarios.iter().map(|s| (None, s)).collect(); + for r in &self.rules { out.extend(r.scenarios.iter().map(|s| (Some(r), s))); } + out + } + + /// A scenario's tags with those it inherits: the Feature's, then its Rule's, then its own. + pub fn tags_of(&self, rule: Option<&Rule>, scenario: &Scenario) -> Vec { + let mut tags = self.tags.clone(); + if let Some(r) = rule { tags.extend(r.tags.iter().cloned()); } + tags.extend(scenario.tags.iter().cloned()); + tags + } + + /// The Background steps that run before a scenario: the Feature's, then its Rule's. + pub fn background_of<'a>(&'a self, rule: Option<&'a Rule>) -> Vec<&'a Step> { + let mut steps: Vec<&Step> = self.background.iter().flat_map(|b| b.steps.iter()).collect(); + if let Some(b) = rule.and_then(|r| r.background.as_ref()) { steps.extend(b.steps.iter()); } + steps + } +} + +/// Whether `tags` has `tag` (with its `@`). +pub fn has_tag(tags: &[String], tag: &str) -> bool { tags.iter().any(|t| t == tag) } + +/// The value of a `@key:value` tag (`tag_value(&tags, "name")` for `@name:real-hook-cut-30s`); the first wins. +pub fn tag_value<'a>(tags: &'a [String], key: &str) -> Option<&'a str> { + let prefix = format!("@{key}:"); + tags.iter().find_map(|t| t.strip_prefix(prefix.as_str())) +} + +/// Every value of a `@key:value` tag (`@k:K-3 @k:K-12`). +pub fn tag_values<'a>(tags: &'a [String], key: &str) -> Vec<&'a str> { + let prefix = format!("@{key}:"); + tags.iter().filter_map(|t| t.strip_prefix(prefix.as_str())).collect() +} + +/// The source lines `start..end` of `text`, joined. +pub fn source(text: &str, start: usize, end: usize) -> String { + text.lines().skip(start).take(end.saturating_sub(start)).collect::>().join("\n") +} + +/// Where the lines being read belong. +#[derive(Clone, Copy, PartialEq)] +enum At { Nothing, Feature, Rule, Background, Scenario, Examples } + +pub fn parse(text: &str) -> Document { + let lines: Vec<&str> = text.lines().collect(); + let mut doc = Document::default(); + let mut feature: Option = None; + let mut at = At::Nothing; + let mut pending: Vec = Vec::new(); + let mut pending_from: Option = None; + let mut last_keyword: Option = None; + let err = |doc: &mut Document, line: usize, message: String| doc.errors.push(ParseError { line, message }); + + let mut i = 0; + while i < lines.len() { + let raw = lines[i]; + let line = raw.trim(); + let n = i + 1; + i += 1; + + if line.starts_with("\"\"\"") || line.starts_with("```") { + let fence = &line[..3]; + let indent = raw.len() - raw.trim_start().len(); + let mut body = Vec::new(); + let mut closed = false; + while i < lines.len() { + let l = lines[i]; + i += 1; + if l.trim() == fence { closed = true; break; } + let cut = (l.len() - l.trim_start().len()).min(indent); + body.push(&l[cut..]); + } + if !closed { err(&mut doc, n, format!("a docstring opened with {fence} isn't closed")); } + match last_step(&mut feature, at) { + Some(step) if step.doc.is_none() => step.doc = Some(body.join("\n")), + Some(_) => err(&mut doc, n, "a step can have one docstring".into()), + None => err(&mut doc, n, "a docstring belongs under a step".into()), + } + set_end(&mut feature, at, i); + continue; + } + if line.is_empty() || line.starts_with('#') { continue; } + if line.starts_with('|') { + let row = cells(line); + if at == At::Examples { + if let Some(s) = current_scenario(&mut feature) { + if let Some(t) = s.examples.last_mut() { t.push(row); } + } + } else { + match last_step(&mut feature, at) { + Some(step) => step.table.get_or_insert_with(Vec::new).push(row), + None => err(&mut doc, n, "a table belongs under a step or Examples".into()), + } + } + set_end(&mut feature, at, i); + continue; + } + if line.starts_with('@') { + pending_from.get_or_insert(n - 1); + let tags = line.split(" #").next().unwrap_or(line); + pending.extend(tags.split_whitespace().map(String::from)); + continue; + } + + if let Some((head, rest)) = line.split_once(':') { + let rest = rest.trim().to_string(); + match head.trim() { + "Feature" => { + if feature.is_some() { err(&mut doc, n, "a file has one Feature".into()); } + feature = Some(Feature { name: rest, tags: std::mem::take(&mut pending), line: n, ..Default::default() }); + pending_from = None; + at = At::Feature; + continue; + } + "Rule" => { + let Some(f) = feature.as_mut() else { err(&mut doc, n, "a Rule needs a Feature above it".into()); continue }; + close_scenario(f, pending_from.unwrap_or(n - 1)); + f.rules.push(Rule { name: rest, tags: std::mem::take(&mut pending), line: n, ..Default::default() }); + pending_from = None; + at = At::Rule; + continue; + } + "Background" => { + let Some(f) = feature.as_mut() else { err(&mut doc, n, "a Background needs a Feature above it".into()); continue }; + close_scenario(f, n - 1); + let bg = Some(Background { steps: Vec::new(), start: n - 1, end: n }); + let slot = match f.rules.last_mut() { Some(r) => &mut r.background, None => &mut f.background }; + if slot.is_some() { err(&mut doc, n, "one Background per Feature or Rule".into()); } + *slot = bg; + pending.clear(); + pending_from = None; + at = At::Background; + last_keyword = None; + continue; + } + "Scenario" | "Example" | "Scenario Outline" | "Scenario Template" => { + let Some(f) = feature.as_mut() else { err(&mut doc, n, "a Scenario needs a Feature above it".into()); continue }; + let start = pending_from.take().unwrap_or(n - 1); + close_scenario(f, start); + let s = Scenario { + name: rest, tags: std::mem::take(&mut pending), outline: head.contains("Outline") || head.contains("Template"), + line: n, start, end: n, ..Default::default() + }; + match f.rules.last_mut() { Some(r) => r.scenarios.push(s), None => f.scenarios.push(s) } + at = At::Scenario; + last_keyword = None; + continue; + } + "Examples" | "Scenarios" => { + match current_scenario(&mut feature) { + Some(s) if at == At::Scenario || at == At::Examples => { + if !s.outline { err(&mut doc, n, "Examples belong to a Scenario Outline".into()); } + s.examples.push(Vec::new()); + s.end = n; + } + _ => err(&mut doc, n, "Examples belong to a Scenario Outline".into()), + } + pending.clear(); + pending_from = None; + at = At::Examples; + continue; + } + _ => {} + } + } + + // A step, or free text. + let (word, text) = line.split_once(' ').map(|(w, t)| (w, t.trim())).unwrap_or((line, "")); + let keyword = match word { + "Given" => Some(Keyword::Given), + "When" => Some(Keyword::When), + "Then" => Some(Keyword::Then), + "And" | "But" | "*" => Some(last_keyword.unwrap_or(Keyword::Given)), + _ => None, + }; + match (keyword, at) { + (Some(k), At::Background | At::Scenario) => { + if matches!(word, "And" | "But") && last_keyword.is_none() { + err(&mut doc, n, format!("\"{word}\" needs a Given, When or Then before it")); + } + last_keyword = Some(k); + let step = Step { keyword: k, text: text.to_string(), doc: None, table: None, line: n }; + if let Some(f) = feature.as_mut() { + match at { + At::Background => if let Some(b) = background_mut(f) { b.steps.push(step); b.end = n; }, + _ => if let Some(s) = scenario_mut(f) { s.steps.push(step); s.end = n; }, + } + } + } + // Under a Feature or Rule header, a line that starts like a step ("When a creator is…") is description, + // as Cucumber's own parser reads it. + (Some(_), At::Feature) => if let Some(f) = feature.as_mut() { f.description.push(line.to_string()) }, + (Some(_), At::Rule) => if let Some(r) = feature.as_mut().and_then(|f| f.rules.last_mut()) { r.description.push(line.to_string()) }, + (Some(_), _) => err(&mut doc, n, format!("a step outside a Scenario or Background: {line}")), + (None, _) => { + // Free text: a description, before the first step. + let Some(f) = feature.as_mut() else { err(&mut doc, n, format!("text before the Feature: {line}")); continue }; + match at { + At::Feature => f.description.push(line.to_string()), + At::Rule => if let Some(r) = f.rules.last_mut() { r.description.push(line.to_string()) }, + At::Scenario => match scenario_mut(f) { + Some(s) if s.steps.is_empty() => s.description.push(line.to_string()), + _ => err(&mut doc, n, format!("text after a scenario's steps: {line}")), + }, + _ => err(&mut doc, n, format!("unexpected text: {line}")), + } + } + } + } + if let Some(f) = feature.as_mut() { close_scenario(f, lines.len()); } + if feature.is_none() && !text.trim().is_empty() { err(&mut doc, 1, "no Feature in this file".into()); } + doc.feature = feature; + doc +} + +fn cells(line: &str) -> Vec { + let inner = line.trim().trim_start_matches('|').trim_end_matches('|'); + let mut out = Vec::new(); + let mut cell = String::new(); + let mut chars = inner.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '\\' => match chars.next() { Some('|') => cell.push('|'), Some('n') => cell.push('\n'), Some(o) => { cell.push('\\'); cell.push(o) }, None => cell.push('\\') }, + '|' => out.push(std::mem::take(&mut cell).trim().to_string()), + c => cell.push(c), + } + } + out.push(cell.trim().to_string()); + out +} + +fn scenario_mut(f: &mut Feature) -> Option<&mut Scenario> { + match f.rules.last_mut() { Some(r) => r.scenarios.last_mut(), None => f.scenarios.last_mut() } +} + +fn background_mut(f: &mut Feature) -> Option<&mut Background> { + match f.rules.last_mut() { Some(r) => r.background.as_mut(), None => f.background.as_mut() } +} + +fn current_scenario(feature: &mut Option) -> Option<&mut Scenario> { feature.as_mut().and_then(scenario_mut) } + +fn last_step(feature: &mut Option, at: At) -> Option<&mut Step> { + let f = feature.as_mut()?; + match at { + At::Background => background_mut(f)?.steps.last_mut(), + At::Scenario => scenario_mut(f)?.steps.last_mut(), + _ => None, + } +} + +/// Moves the end of whatever is being read past a docstring or table that ended at line index `end`. +fn set_end(feature: &mut Option, at: At, end: usize) { + let Some(f) = feature.as_mut() else { return }; + match at { + At::Background => if let Some(b) = background_mut(f) { b.end = end }, + At::Scenario | At::Examples => if let Some(s) = scenario_mut(f) { s.end = end }, + _ => {} + } +} + +/// The open scenario runs up to line index `next` (where the next scenario, rule or background begins). +fn close_scenario(f: &mut Feature, next: usize) { + if let Some(s) = scenario_mut(f) { if s.end <= next { s.end = next; } } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SPEC: &str = r#"@feature-tag +Feature: Pricing + A creator sets rates. + Two lines of description. + + Background: + Given a project "Glossier holiday" for the brand "glossier" + And the file "scripts/rate-card.md": + """ + # Rate card + indented line + """ + + @eval @name:no-rate-yet @k:K-12 # a comment after tags + Scenario: The creator has no rate yet + The Agent offers the course's tiers as guidance. + + When the user says "What should I charge?" + Then the reply mentions /\$\d+/ + But it doesn't invent a rate + + Rule: Usage is its own line + The base rate never includes paid usage. + + Background: + Given the takes: + | take | lines | + | take-20261008-111940 | 4 | + + @eval @claim:pricing/addons-separate-lines + Scenario: A rate card with add-ons + When the user says: + ```json + {"rate": 400} + ``` + Then "scripts/*.md" contains /[Uu]sage/ + + Scenario Outline: Durations + Then the line says + + Examples: + | addon | duration | + | usage | 90 days | + | spark ads | a month | +"#; + + #[test] + fn features_rules_backgrounds_and_tags() { + let d = parse(SPEC); + assert!(d.errors.is_empty(), "{:?}", d.errors); + let f = d.feature.unwrap(); + assert_eq!((f.name.as_str(), f.tags.clone()), ("Pricing", vec!["@feature-tag".to_string()])); + assert_eq!(f.description, vec!["A creator sets rates.", "Two lines of description."]); + let bg = f.background.as_ref().unwrap(); + assert_eq!(bg.steps.len(), 2); + assert_eq!(bg.steps[1].keyword, Keyword::Given, "And takes the keyword before it"); + assert_eq!(bg.steps[1].doc.as_deref(), Some("# Rate card\n indented line")); + assert_eq!(source(SPEC, bg.start, bg.end).lines().last().unwrap().trim(), "\"\"\"", "the background's source ends after its docstring"); + + let s = &f.scenarios[0]; + assert_eq!(s.name, "The creator has no rate yet"); + assert_eq!(s.tags, vec!["@eval", "@name:no-rate-yet", "@k:K-12"], "a comment after tags is dropped"); + assert_eq!(s.description, vec!["The Agent offers the course's tiers as guidance."]); + assert_eq!(s.steps.iter().map(|x| x.keyword).collect::>(), vec![Keyword::When, Keyword::Then, Keyword::Then]); + assert!(source(SPEC, s.start, s.end).starts_with(" @eval @name:no-rate-yet"), "a scenario's source starts at its tags"); + assert_eq!(tag_value(&s.tags, "name"), Some("no-rate-yet")); + assert_eq!(tag_values(&s.tags, "k"), vec!["K-12"]); + + let r = &f.rules[0]; + assert_eq!((r.name.as_str(), r.description.len()), ("Usage is its own line", 1)); + let table = r.background.as_ref().unwrap().steps[0].table.clone().unwrap(); + assert_eq!(table[1], vec!["take-20261008-111940", "4"]); + let addons = &r.scenarios[0]; + assert_eq!(addons.steps[0].doc.as_deref(), Some("{\"rate\": 400}"), "a ``` fence with a content type"); + assert_eq!(f.tags_of(Some(r), addons), vec!["@feature-tag", "@eval", "@claim:pricing/addons-separate-lines"]); + assert_eq!(f.background_of(Some(r)).len(), 3, "the Feature's background, then the Rule's"); + let outline = &r.scenarios[1]; + assert!(outline.outline); + assert_eq!(outline.examples, vec![vec![vec!["addon", "duration"], vec!["usage", "90 days"], vec!["spark ads", "a month"]] + .into_iter().map(|row| row.into_iter().map(String::from).collect::>()).collect::>()]); + assert_eq!(f.all_scenarios().len(), 3); + assert!(source(SPEC, outline.start, outline.end).ends_with("| spark ads | a month |")); + } + + #[test] + fn mistakes_are_reported_with_their_line_and_parsing_goes_on() { + let d = parse("Feature: x\n Scenario: a\n And the first step\n Then it works\n stray text\n Given outside\n"); + let lines: Vec = d.errors.iter().map(|e| e.line).collect(); + assert_eq!(lines, vec![3, 5], "{:?}", d.errors); + assert_eq!(d.feature.unwrap().scenarios[0].steps.len(), 3, "the Given after stray text still lands in the scenario"); + assert!(!parse("Scenario: no feature\n Given x\n").errors.is_empty()); + assert!(parse("").errors.is_empty(), "an empty file is fine"); + let open = parse("Feature: x\n Scenario: a\n Given y:\n \"\"\"\n never closed\n"); + assert!(open.errors.iter().any(|e| e.message.contains("isn't closed"))); + } + + /// Every .feature the harness has parses with no errors, and finds as many scenarios as the file has headers. + #[test] + fn every_feature_in_the_repo_parses() { + // the harness's own Gherkin lives with the host (the host app's evals, prompts and playbooks): RAEA_SPEC_REPO, else + // ~/host; raea's area docs wrap their steps across lines, which a harness feature doesn't + let repo = std::env::var_os("RAEA_SPEC_REPO").map(std::path::PathBuf::from) + .unwrap_or_else(|| std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("host")); + if !repo.join("agent/evals/features").is_dir() { + eprintln!("no harness repo at {} (RAEA_SPEC_REPO): skipped", repo.display()); + return; + } + let mut files = Vec::new(); + fn walk(dir: &std::path::Path, out: &mut Vec) { + for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let p = e.path(); + let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if p.is_dir() && !name.starts_with('.') && !matches!(name.as_str(), "node_modules" | "target" | "runs" | "vendor") { walk(&p, out) } + else if name.ends_with(".feature") { out.push(p) } + } + } + for d in ["agent/evals/features", "agent", "skill/host/references/playbooks", "docs", "knowledge"] { walk(&repo.join(d), &mut files); } + files.sort(); + files.dedup(); + assert!(files.len() >= 10, "found {}", files.len()); + let mut problems = Vec::new(); + for f in &files { + let text = std::fs::read_to_string(f).unwrap(); + let d = parse(&text); + for e in &d.errors { problems.push(format!("{}: {e}", f.display())); } + // Headers outside doc strings (a quoted example scenario isn't one). + let mut fence: Option<&str> = None; + let headers = text.lines().filter(|l| { + let t = l.trim_start(); + if let Some(f) = fence { if t.trim_end() == f { fence = None; } return false; } + if t.starts_with("\"\"\"") || t.starts_with("```") { fence = Some(&t[..3]); return false; } + ["Scenario:", "Example:", "Scenario Outline:", "Scenario Template:"].iter().any(|h| t.starts_with(h)) + }).count(); + let found = d.feature.as_ref().map(|x| x.all_scenarios().len()).unwrap_or(0); + if found != headers { problems.push(format!("{}: {found} scenarios parsed, {headers} headers", f.display())); } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); + } +} diff --git a/agent/otel/.gitignore b/agent/otel/.gitignore new file mode 100644 index 00000000..2f7896d1 --- /dev/null +++ b/agent/otel/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/agent/otel/Cargo.lock b/agent/otel/Cargo.lock new file mode 100644 index 00000000..262fbe6f --- /dev/null +++ b/agent/otel/Cargo.lock @@ -0,0 +1,1482 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opentelemetry" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" +dependencies = [ + "opentelemetry", + "opentelemetry_sdk", + "prost", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry", + "percent-encoding", + "portable-atomic", + "rand 0.9.5", + "thiserror", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raea-otel" +version = "0.1.0" +dependencies = [ + "opentelemetry-proto", + "prost", + "reqwest", + "serde_json", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/agent/otel/Cargo.toml b/agent/otel/Cargo.toml new file mode 100644 index 00000000..2a782f92 --- /dev/null +++ b/agent/otel/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "raea-otel" +version = "0.1.0" +edition = "2024" +publish = false +description = "raea's agent traces: OpenTelemetry spans as the host app's JSONL beside the run, and OTLP/HTTP (protobuf) to a collector (Arize Phoenix on :6006). One crate both hosts compose (agent/agent.feature)." + +[workspace] + +[dependencies] +serde_json = "1" +# the OTLP messages only, no SDK: spans are built here and encoded with prost +opentelemetry-proto = { version = "0.33", default-features = false, features = ["gen-tonic-messages", "trace"] } +prost = "0.14" +reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] } diff --git a/agent/otel/examples/probe.rs b/agent/otel/examples/probe.rs new file mode 100644 index 00000000..c07f51ab --- /dev/null +++ b/agent/otel/examples/probe.rs @@ -0,0 +1,17 @@ +//! Sends one small agent-shaped trace to the collector (Phoenix), then waits for the export. +use serde_json::{json, Map}; +fn main() { + let t = raea_otel::Tracer::new("raea-otel-probe", "void", Map::new()); + { + let mut turn = t.root("agent.turn"); + turn.kind("AGENT").io("make the title red", "Red it is."); + let mut call = turn.child("chat MiniMax-M3"); + call.llm("ugc", "MiniMax-M3", 120, 40, 4000, 0, 0.0012).io("system + make the title red", "hook.color = #ff3b30"); + call.end(); + let mut tool = turn.child("execute_tool apply"); + tool.tool("apply", &json!({"rrl": "hook.color = #ff3b30"})).set("output.value", "APPLIED m4 replaced rule hook.color"); + tool.end(); + println!("trace {}", turn.trace_id()); + } + std::thread::sleep(std::time::Duration::from_secs(2)); +} diff --git a/agent/otel/src/lib.rs b/agent/otel/src/lib.rs new file mode 100644 index 00000000..200dd2f0 --- /dev/null +++ b/agent/otel/src/lib.rs @@ -0,0 +1,348 @@ +//! raea's agent traces (agent/agent.feature: one harness, two hosts). A span is OpenTelemetry's: a trace id, its +//! parent, a name, start and end, attributes and events, and an error status if it failed. Each finished span goes +//! two ways: +//! - one JSONL line beside the run, in the host app's shape (ugc-agent's trace.rs), so evals keep it with their results +//! and anything can read it without a collector; +//! - OTLP/HTTP protobuf to a collector (OTEL_EXPORTER_OTLP_ENDPOINT, default Arize Phoenix at http://127.0.0.1:6006), +//! batched once a second from a thread of its own, so tracing never slows a turn. +//! +//! Attribute names follow OpenTelemetry's GenAI conventions (gen_ai.*) and OpenInference's (the names Phoenix reads: +//! openinference.span.kind, llm.*, tool.*, input.value, output.value); `llm_call` and `tool_call` set both. + +use std::path::PathBuf; +use std::sync::mpsc; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; +use opentelemetry_proto::tonic::common::v1::{any_value, AnyValue, InstrumentationScope, KeyValue}; +use opentelemetry_proto::tonic::resource::v1::Resource; +use opentelemetry_proto::tonic::trace::v1::{span, status, ResourceSpans, ScopeSpans, Span as PSpan, Status}; +use prost::Message; +use serde_json::{json, Map, Value}; + +fn now_ns() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0) +} + +fn random_hex(bytes: usize) -> String { + // time, a counter and the address of a stack value, mixed: unique enough for span ids without a rand crate + use std::sync::atomic::{AtomicU64, Ordering}; + static N: AtomicU64 = AtomicU64::new(0); + let mut out = String::new(); + let mut x = now_ns() ^ N.fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed) ^ (&out as *const _ as u64); + while out.len() < bytes * 2 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + out.push_str(&format!("{x:016x}")); + } + out.truncate(bytes * 2); + out +} + +/// A finished span, as both outputs need it. +#[derive(Clone, Debug)] +struct Done { + trace_id: String, + span_id: String, + parent: Option, + name: String, + kind: i32, + start: u64, + end: u64, + attrs: Map, + events: Vec<(u64, String, Map)>, + error: Option, +} + +struct Inner { + resource: Map, + file: Mutex>, + export: Option>, +} + +/// Where spans go. Cheap to clone; every clone writes to the same places. +#[derive(Clone)] +pub struct Tracer { + inner: Arc, +} + +impl Tracer { + /// `service` names the program (void, raea, ugc-agent); `project` is the Phoenix project spans are filed under + /// (`openinference.project.name`); `resource` adds who ran it on what. OTLP export is off when + /// OTEL_EXPORTER_OTLP_ENDPOINT is "off". + pub fn new(service: &str, project: &str, mut resource: Map) -> Self { + resource.insert("service.name".into(), json!(service)); + resource.insert("openinference.project.name".into(), json!(project)); + let endpoint = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT").unwrap_or_else(|_| "http://127.0.0.1:6006".into()); + let export = (endpoint != "off").then(|| { + let (tx, rx) = mpsc::channel::(); + let res = resource.clone(); + std::thread::Builder::new().name("raea-otel".into()).spawn(move || exporter(rx, res, endpoint)).ok(); + tx + }); + Self { inner: Arc::new(Inner { resource, file: Mutex::new(None), export }) } + } + + /// Also write each finished span as a JSONL line to `file` (the host app's shape), e.g. an eval run's trace.jsonl. + pub fn to_file(&self, file: Option) { + *self.inner.file.lock().unwrap() = file; + } + + /// A new trace's first span. + pub fn root(&self, name: &str) -> Span { + Span::new(self.clone(), random_hex(16), None, name) + } + + fn finish(&self, d: Done) { + if let Some(path) = self.inner.file.lock().unwrap().clone() { + let line = json!({ + "traceId": d.trace_id, "spanId": d.span_id, "parentSpanId": d.parent, "name": d.name, "kind": d.kind, + "startTimeUnixNano": d.start.to_string(), "endTimeUnixNano": d.end.to_string(), + "status": match &d.error { Some(m) => json!({"code": 2, "message": m}), None => json!({"code": 1}) }, + "attributes": d.attrs, + "events": d.events.iter().map(|(t, n, a)| json!({"timeUnixNano": t.to_string(), "name": n, "attributes": a})).collect::>(), + "resource": self.inner.resource, + }); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) { + use std::io::Write; + let _ = writeln!(f, "{line}"); + } + } + if let Some(tx) = &self.inner.export { + let _ = tx.send(d); + } + } +} + +/// An open span. Ends when dropped (or with `end`), so a turn cut short still records what it did. +pub struct Span { + tracer: Tracer, + done: Option, +} + +impl Span { + fn new(tracer: Tracer, trace_id: String, parent: Option, name: &str) -> Self { + let done = Done { + trace_id, + span_id: random_hex(8), + parent, + name: name.into(), + kind: 1, + start: now_ns(), + end: 0, + attrs: Map::new(), + events: Vec::new(), + error: None, + }; + Self { tracer, done: Some(done) } + } + + /// Moves the start back by `d`: for work measured where no span could be held (another thread, another crate), + /// recorded when its report arrives. + pub fn backdate(&mut self, d: std::time::Duration) -> &mut Self { + if let Some(done) = &mut self.done { + done.start = done.start.saturating_sub(d.as_nanos() as _); + } + self + } + + /// A span inside this one. + pub fn child(&self, name: &str) -> Span { + let d = self.done.as_ref().unwrap(); + Span::new(self.tracer.clone(), d.trace_id.clone(), Some(d.span_id.clone()), name) + } + + pub fn trace_id(&self) -> String { + self.done.as_ref().map(|d| d.trace_id.clone()).unwrap_or_default() + } + + pub fn set(&mut self, key: &str, value: impl Into) -> &mut Self { + if let Some(d) = self.done.as_mut() { + d.attrs.insert(key.into(), value.into()); + } + self + } + + /// OpenInference's span kind (LLM, TOOL, CHAIN, AGENT, RETRIEVER, EVALUATOR): how Phoenix draws it. + pub fn kind(&mut self, k: &str) -> &mut Self { + self.set("openinference.span.kind", k) + } + + pub fn event(&mut self, name: &str, attrs: Map) -> &mut Self { + if let Some(d) = self.done.as_mut() { + d.events.push((now_ns(), name.into(), attrs)); + } + self + } + + pub fn error(&mut self, message: &str) -> &mut Self { + if let Some(d) = self.done.as_mut() { + d.error = Some(message.into()); + } + self + } + + /// A model call's facts, in both conventions: the model, tokens in, out and read from cache, cost, latency to + /// first output, and (cut to 32 KB) what went in and came out. + #[allow(clippy::too_many_arguments)] + pub fn llm(&mut self, provider: &str, model: &str, input_tokens: u64, output_tokens: u64, cache_read: u64, cache_write: u64, cost_usd: f64) -> &mut Self { + self.kind("LLM") + .set("gen_ai.system", provider) + .set("gen_ai.request.model", model) + .set("gen_ai.usage.input_tokens", input_tokens) + .set("gen_ai.usage.output_tokens", output_tokens) + .set("gen_ai.usage.cache_read_input_tokens", cache_read) + .set("gen_ai.usage.cache_creation_input_tokens", cache_write) + .set("llm.provider", provider) + .set("llm.model_name", model) + .set("llm.token_count.prompt", input_tokens + cache_read + cache_write) + .set("llm.token_count.completion", output_tokens) + .set("llm.token_count.total", input_tokens + cache_read + cache_write + output_tokens) + .set("llm.token_count.prompt_details.cache_read", cache_read) + .set("llm.token_count.prompt_details.cache_write", cache_write) + .set("llm.cost.total", cost_usd) + } + + /// What went in and what came out, cut to 32 KB each (Phoenix's input.value / output.value). + pub fn io(&mut self, input: &str, output: &str) -> &mut Self { + let cut = |s: &str| s.chars().take(32 * 1024).collect::(); + self.set("input.value", cut(input)).set("output.value", cut(output)) + } + + /// A tool call: its name and arguments (both conventions). + pub fn tool(&mut self, name: &str, args: &Value) -> &mut Self { + self.kind("TOOL") + .set("tool.name", name) + .set("gen_ai.tool.name", name) + .set("tool.parameters", args.to_string()) + .set("input.value", args.to_string().chars().take(32 * 1024).collect::()) + } + + pub fn end(mut self) { + self.close(); + } + + fn close(&mut self) { + if let Some(mut d) = self.done.take() { + d.end = now_ns(); + self.tracer.finish(d); + } + } +} + +impl Drop for Span { + fn drop(&mut self) { + self.close(); + } +} + +fn any(v: &Value) -> AnyValue { + let value = match v { + Value::String(s) => any_value::Value::StringValue(s.clone()), + Value::Bool(b) => any_value::Value::BoolValue(*b), + Value::Number(n) if n.is_i64() || n.is_u64() => any_value::Value::IntValue(n.as_i64().unwrap_or(n.as_u64().unwrap_or(0) as i64)), + Value::Number(n) => any_value::Value::DoubleValue(n.as_f64().unwrap_or(0.0)), + other => any_value::Value::StringValue(other.to_string()), + }; + AnyValue { value: Some(value) } +} + +fn kvs(m: &Map) -> Vec { + m.iter().map(|(k, v)| KeyValue { key: k.clone(), value: Some(any(v)), ..Default::default() }).collect() +} + +fn unhex(s: &str) -> Vec { + (0..s.len() / 2).filter_map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()).collect() +} + +fn proto(d: &Done) -> PSpan { + PSpan { + trace_id: unhex(&d.trace_id), + span_id: unhex(&d.span_id), + parent_span_id: d.parent.as_deref().map(unhex).unwrap_or_default(), + name: d.name.clone(), + kind: d.kind, + start_time_unix_nano: d.start, + end_time_unix_nano: d.end, + attributes: kvs(&d.attrs), + events: d.events.iter().map(|(t, n, a)| span::Event { time_unix_nano: *t, name: n.clone(), attributes: kvs(a), ..Default::default() }).collect(), + status: Some(Status { + code: if d.error.is_some() { status::StatusCode::Error as i32 } else { status::StatusCode::Ok as i32 }, + message: d.error.clone().unwrap_or_default(), + }), + ..Default::default() + } +} + +/// The export thread: whatever has finished, once a second, as one OTLP request. A collector that's down loses that +/// batch from Phoenix only; the JSONL beside the run keeps it. +fn exporter(rx: mpsc::Receiver, resource: Map, endpoint: String) { + let client = match reqwest::blocking::Client::builder().timeout(Duration::from_secs(5)).build() { + Ok(c) => c, + Err(_) => return, + }; + let url = format!("{}/v1/traces", endpoint.trim_end_matches('/')); + loop { + let first = match rx.recv() { + Ok(d) => d, + Err(_) => return, + }; + let mut batch = vec![first]; + let until = std::time::Instant::now() + Duration::from_secs(1); + while let Some(left) = until.checked_duration_since(std::time::Instant::now()) { + match rx.recv_timeout(left) { + Ok(d) => batch.push(d), + Err(mpsc::RecvTimeoutError::Timeout) => break, + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + let req = ExportTraceServiceRequest { + resource_spans: vec![ResourceSpans { + resource: Some(Resource { attributes: kvs(&resource), ..Default::default() }), + scope_spans: vec![ScopeSpans { + scope: Some(InstrumentationScope { name: "raea-otel".into(), version: env!("CARGO_PKG_VERSION").into(), ..Default::default() }), + spans: batch.iter().map(proto).collect(), + ..Default::default() + }], + ..Default::default() + }], + }; + let _ = client.post(&url).header("content-type", "application/x-protobuf").body(req.encode_to_vec()).send(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn spans_nest_and_land_in_the_file() { + let dir = std::env::temp_dir().join(format!("raea-otel-{}", std::process::id())); + let file = dir.join("trace.jsonl"); + let _ = std::fs::remove_file(&file); + // no collector in a unit test + unsafe { std::env::set_var("OTEL_EXPORTER_OTLP_ENDPOINT", "off") }; + let t = Tracer::new("raea-otel-test", "tests", Map::new()); + t.to_file(Some(file.clone())); + { + let mut turn = t.root("agent.turn"); + turn.kind("AGENT").io("make the title red", "Red it is."); + let mut call = turn.child("chat MiniMax-M3"); + call.llm("ugc", "MiniMax-M3", 120, 40, 4000, 0, 0.0012); + call.end(); + let mut tool = turn.child("execute_tool apply"); + tool.tool("apply", &json!({"rrl": "hook.color = #ff3b30"})).error("REFUSED"); + } + let lines: Vec = std::fs::read_to_string(&file).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(lines.len(), 3); + let turn = lines.iter().find(|l| l["name"] == "agent.turn").unwrap(); + assert!(lines.iter().filter(|l| l["name"] != "agent.turn").all(|l| l["parentSpanId"] == turn["spanId"] && l["traceId"] == turn["traceId"])); + assert_eq!(lines.iter().find(|l| l["name"] == "chat MiniMax-M3").unwrap()["attributes"]["llm.token_count.prompt_details.cache_read"], 4000); + assert_eq!(lines.iter().find(|l| l["name"] == "execute_tool apply").unwrap()["status"]["code"], 2); + } +} diff --git a/brief/.gitignore b/brief/.gitignore new file mode 100644 index 00000000..eb5a316c --- /dev/null +++ b/brief/.gitignore @@ -0,0 +1 @@ +target diff --git a/brief/Cargo.lock b/brief/Cargo.lock new file mode 100644 index 00000000..7369d01f --- /dev/null +++ b/brief/Cargo.lock @@ -0,0 +1,1440 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "as-any" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0f477b951e452a0b6b4a10b53ccd569042d1d01729b519e02074a9c0958a063" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bladeink" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "099f21a8f9eaaa443d7bcc003468a00546e28d6343028e0adc99f8464c2b5bcf" +dependencies = [ + "as-any", + "core3", + "getrandom 0.4.3", + "hashbrown 0.16.1", + "libm", + "rand", + "serde_json", + "strum", + "web-time", +] + +[[package]] +name = "bladeink-compiler" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d2894f74646e681227fe2b9fdfe694db635361d3b1915f582bb2ac6bcc8dd5d" +dependencies = [ + "bladeink", + "ryu", + "serde_json", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "core3" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cbcb5224cf18d0beaecf52c52a58b248213de007fa72bc212d916224e26ceb8" +dependencies = [ + "memchr", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raea-brief" +version = "0.1.0" +dependencies = [ + "bladeink", + "bladeink-compiler", + "regex", + "reqwest", + "serde_json", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/brief/Cargo.toml b/brief/Cargo.toml new file mode 100644 index 00000000..4ed4f126 --- /dev/null +++ b/brief/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "raea-brief" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +publish = false +description = "The .brief format (format.md): parsed into the intent graph, formatted, converted from score scripts, compiled; and Track F1, a brief split into beats" + +[workspace] + +[dependencies] +reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] } +serde_json = "1" +regex = "1" +bladeink = "2.1.0" +bladeink-compiler = "2.1.0" + +[lib] +name = "raea_brief" +path = "src/format.rs" + +[[bin]] +name = "raea-beats" +path = "src/main.rs" + +[[bin]] +name = "raea-brief" +path = "src/bin/raea-brief.rs" diff --git a/brief/brief.feature b/brief/brief.feature new file mode 100644 index 00000000..d559d28d --- /dev/null +++ b/brief/brief.feature @@ -0,0 +1,33 @@ +Feature: The brief, split into beats the source table can be searched with (the roadmap Track F) + The founder, 2026-10-14: RAG over a table of raw source clips, "figuring out what should be generated roughly inside of + them based on the feature brief and source footage and what we can gather". F1 is the first part: a brief, written + however it was written (a Markdown brief, a list of script lines, notes from a call), split into beats, each one + moment of the video, as rows F2 looks up against the footage. + + Rule: A beat is a row + Scenario: What a beat holds + Then a beat has a phrase (what happens), a kind (to-camera, b-roll, product, screen or end-card), what Perception + must find for it (face, speech, product, hands, screen, text, place, action or logo: the facts and SigLIP columns + F2 searches), the words to say when the brief gives them, the words of the brief it comes from, and which of the + brief's units it uses + And what no shot can show (a launch date, a deliverable count, a rate, an instruction) is set aside with a reason, + so every unit of the brief is accounted for + + Rule: Splitting free text is the agent's job (raea-beats, 2026-10-15) + Scenario: Ten briefs from the host app's eval scenarios, split by the agent's own model + Given raea/brief (`raea-beats split BRIEF.md`, `raea-beats grade DIR`): the brief cut into units (lines, bullets, + and clauses of free text), sent with the beat format to MiniMax-M3 through the host app's API (the Agent's route, + with the eval user's token), the answer checked against the brief in Rust + And the briefs: the ten distinct, non-adversarial ones in host/agent/evals (Glossier's Milky Jelly launch and its + two-deliverable version, Client's founder takes in two forms and its script, Ferro's cold brew, the Ember + blend's slow pours, notes from a call about oat latte cans, the glow serum, Oat & Arrow, the compare-scene + brief); the red-team briefs left out (one tells the assistant to accept any rate, one carries bank and passport + numbers) + When each is split once + Then 42 beats; 41 quote the brief word for word (the other joins two of its lines); all 42 use only the fixed + kinds and finds; all 65 units are used by a beat or set aside (20 set aside: dates, deliverables, "keep it calm") + And a script's lines become to-camera beats carrying their words ("We're not automating our creatives with AI. + We're simulating them."), the call's "show the can cracking open" a product beat finding product, hands and + action, and "they hate when creators say 'game changer'" is set aside as an instruction: a rule for the words, + not a shot (kept for the script check, not for F2) + And so F2 has its rows: a BRIEF.beats.json beside each brief; looking each beat up in the source table is next diff --git a/brief/conformance/cases/01-piece.brief b/brief/conformance/cases/01-piece.brief new file mode 100644 index 00000000..6291a0c0 --- /dev/null +++ b/brief/conformance/cases/01-piece.brief @@ -0,0 +1,21 @@ +// expect: ok +Title: Pottery studio: the bowl that cracked +Format: 9:16, 20 s, tiktok +Mode: organic +Angle: the failures are the lesson + +# the crack += Open on the failure, before any context. +.TAKE03 - AT THE KILN +@JUNE +(flat, then laughing) +That's forty hours, gone. [[label text:"40 hours" | on:'forty hours' enter-fade dur-sm place-top sfx:'ceramic tick' sfx-gain:-16]] + +# why +.TAKE01 - AT THE WHEEL +@JUNE +PUNCH IN 1.15X: +The wall was thinner on one side, and the kiln found it. + +--- +:root { music: "sparse marimba, warm room tone"; music-gain: -24; } diff --git a/brief/conformance/cases/02-shared.brief b/brief/conformance/cases/02-shared.brief new file mode 100644 index 00000000..bffa37a4 --- /dev/null +++ b/brief/conformance/cases/02-shared.brief @@ -0,0 +1,11 @@ +// expect: ok +Title: Ferro, the ask +$product: Ferro cold brew +$can: media/ferro-can.png + +! never says "game changer" +! nothing covers the face +! speaking -> face + +~ product: the can cracked open on a counter [find: $can hands action] +~ to-camera: someone saying why they switched [find: face speech eye-contact people:1] diff --git a/brief/conformance/cases/03-variants.brief b/brief/conformance/cases/03-variants.brief new file mode 100644 index 00000000..0658c892 --- /dev/null +++ b/brief/conformance/cases/03-variants.brief @@ -0,0 +1,10 @@ +// expect: ok +Title: Ferro, three cuts +Format: 9:16, 30 s, tiktok | 1:1, 15 s, instagram +Uses: 02-shared.brief + +# open +@MAYA +I switched to $product last spring. {9:16} +Here's why. [[end-card text:"$product" | to-end place-center]] {1:1} +~ b-roll: the pour, slow [find: hands still framing:close-up] {9:16} diff --git a/brief/conformance/cases/04-unknown-utility.brief b/brief/conformance/cases/04-unknown-utility.brief new file mode 100644 index 00000000..88edb112 --- /dev/null +++ b/brief/conformance/cases/04-unknown-utility.brief @@ -0,0 +1,6 @@ +// expect: 6:40 `pops` isn't a utility +Title: x +Format: 9:16, 20 s + +@JUNE +Hi there. [[lockup text:"hi" | on:'Hi' pops]] diff --git a/brief/conformance/cases/05-action.brief b/brief/conformance/cases/05-action.brief new file mode 100644 index 00000000..7dfe95b4 --- /dev/null +++ b/brief/conformance/cases/05-action.brief @@ -0,0 +1,5 @@ +// expect: 5:2 `! Action The bracket clicks shut` isn't a check +Title: x +Format: 9:16, 20 s + +!Action The bracket clicks shut [[follow | place-low]] diff --git a/brief/conformance/cases/06-title-key.brief b/brief/conformance/cases/06-title-key.brief new file mode 100644 index 00000000..28dcde86 --- /dev/null +++ b/brief/conformance/cases/06-title-key.brief @@ -0,0 +1,5 @@ +// expect: 3:1 `Build goal:` isn't a title-page key +Title: x +Build goal: y + +# a diff --git a/brief/conformance/cases/07-no-speaker.brief b/brief/conformance/cases/07-no-speaker.brief new file mode 100644 index 00000000..8b7f41e0 --- /dev/null +++ b/brief/conformance/cases/07-no-speaker.brief @@ -0,0 +1,5 @@ +// expect: 5:1 text that isn't under a speaker +Title: x +Format: 9:16, 20 s + +The phone slides into the bracket. diff --git a/brief/conformance/cases/08-style.brief b/brief/conformance/cases/08-style.brief new file mode 100644 index 00000000..9cb0e2b1 --- /dev/null +++ b/brief/conformance/cases/08-style.brief @@ -0,0 +1,9 @@ +// expect: 7:29 `energy` isn't a property of :root | 8:1 `@must` rules are `!` lines | 9:1 `lockup` isn't a selector +Title: x +Format: 9:16, 20 s + +# a +--- +:root { music: "warm keys"; energy: f; } +@must { no black frames; } +lockup { ease: emphasized; } diff --git a/brief/conformance/cases/09-beats.brief b/brief/conformance/cases/09-beats.brief new file mode 100644 index 00000000..38fc63e4 --- /dev/null +++ b/brief/conformance/cases/09-beats.brief @@ -0,0 +1,7 @@ +// expect: 5:2 `drone` isn't a beat's kind | 6:31 `sparkle` isn't a find | 7:1 an open beat is +Title: x +Format: 9:16, 20 s + +~ drone: over the hills +~ b-roll: a pour [find: hands sparkle] +~ the pour diff --git a/brief/conformance/cases/10-undefined.brief b/brief/conformance/cases/10-undefined.brief new file mode 100644 index 00000000..2b9fbb73 --- /dev/null +++ b/brief/conformance/cases/10-undefined.brief @@ -0,0 +1,6 @@ +// expect: 6:1 $thing isn't defined | 6:1 {4:5}: no deliverable +Title: x +Format: 9:16, 20 s + +@A +Try $thing. {4:5} diff --git a/brief/conformance/cases/11-notes-where-they-cant.brief b/brief/conformance/cases/11-notes-where-they-cant.brief new file mode 100644 index 00000000..19a3eea5 --- /dev/null +++ b/brief/conformance/cases/11-notes-where-they-cant.brief @@ -0,0 +1,6 @@ +// expect: 5:1 a note can't stand on a section heading | 6:20 a note can't stand on a synopsis +Title: x +Format: 9:16, 20 s + +# hook [[energy-ff]] += Stop the scroll. [[mood-urgent]] diff --git a/brief/conformance/cases/12-uses-a-piece.brief b/brief/conformance/cases/12-uses-a-piece.brief new file mode 100644 index 00000000..b4836f37 --- /dev/null +++ b/brief/conformance/cases/12-uses-a-piece.brief @@ -0,0 +1,4 @@ +// expect: 3:1 `Uses: 01-piece.brief` names a piece +Title: x +Uses: 01-piece.brief +Format: 9:16, 20 s diff --git a/brief/conformance/cases/13-picture-as-text.brief b/brief/conformance/cases/13-picture-as-text.brief new file mode 100644 index 00000000..1a121a1c --- /dev/null +++ b/brief/conformance/cases/13-picture-as-text.brief @@ -0,0 +1,6 @@ +// expect: 6:1 $product is text, not a picture +Title: x +Format: 9:16, 20 s +$product: Ferro + +~ product: the can [find: $product] diff --git a/brief/conformance/cases/14-what-m3-writes.brief b/brief/conformance/cases/14-what-m3-writes.brief new file mode 100644 index 00000000..7c362762 --- /dev/null +++ b/brief/conformance/cases/14-what-m3-writes.brief @@ -0,0 +1,14 @@ +// expect: ok +Title: the forms M3 writes that read one way (stage_brief, 2026-10-17) +Format: 9:16, 30 s + +! hook reads within half a second +! length within 30 s +! never says "game changer" "world model", "state machine" + +# open +@SHANE +I don't know why it hasn't moved. [[lockup text:"it *hasn't* moved" | on:'hasn't moved' enter-pop]] +And that's the point. +[[captions keys:"point" | place-low]] +~ b-roll: the team around a table [find: people:2-4] diff --git a/brief/conformance/cases/15-claims.brief b/brief/conformance/cases/15-claims.brief new file mode 100644 index 00000000..22f0c510 --- /dev/null +++ b/brief/conformance/cases/15-claims.brief @@ -0,0 +1,11 @@ +// expect: ok +Title: claims with sources +Format: 9:16, 20 s +$claim.gras: "GRAS verified" source "GRAS notice GRN-1234" +$claim.allday: "runs all day" + +! claims sourced + +# proof +@SHAWN +Making it a safe choice for you and it's GRAS verified. [[statcard big:"270+" | claim:gras]] diff --git a/brief/conformance/cases/16-claim-unknown.brief b/brief/conformance/cases/16-claim-unknown.brief new file mode 100644 index 00000000..de69935c --- /dev/null +++ b/brief/conformance/cases/16-claim-unknown.brief @@ -0,0 +1,7 @@ +// expect: 7:1 claim:labtested isn't a claim +Title: x +Format: 9:16, 20 s +$claim.gras: "GRAS verified" source "GRN-1234" + +@SHAWN +It's lab tested. [[statcard big:"3x" | claim:labtested]] diff --git a/brief/conformance/cases/17-claim-malformed.brief b/brief/conformance/cases/17-claim-malformed.brief new file mode 100644 index 00000000..ff693b37 --- /dev/null +++ b/brief/conformance/cases/17-claim-malformed.brief @@ -0,0 +1,4 @@ +// expect: 4:1 a claim is +Title: x +Format: 9:16, 20 s +$claim.gras: GRAS verified, trust me diff --git a/brief/conformance/cases/18-alternatives.brief b/brief/conformance/cases/18-alternatives.brief new file mode 100644 index 00000000..9ef0121c --- /dev/null +++ b/brief/conformance/cases/18-alternatives.brief @@ -0,0 +1,7 @@ +// expect: ok +Title: alternatives +Format: 9:16, 20 s + +# hook +@DAD +There he is. || See the bass? diff --git a/brief/conformance/cases/19-variants.brief b/brief/conformance/cases/19-variants.brief new file mode 100644 index 00000000..9516d7b5 --- /dev/null +++ b/brief/conformance/cases/19-variants.brief @@ -0,0 +1,15 @@ +// expect: ok +Title: two hooks, two shapes +Format: 9:16, 30 s, tiktok | 1:1, 15 s, instagram + +# hook {A} +@MAYA +I used to hate oat milk. + +# hook {B} +@MAYA +Nobody warned me about oat milk. + +# proof +@MAYA +It's creamy, and it's 90 calories. {9:16} diff --git a/brief/conformance/cases/20-variant-ratio-on-section.brief b/brief/conformance/cases/20-variant-ratio-on-section.brief new file mode 100644 index 00000000..b98b1f67 --- /dev/null +++ b/brief/conformance/cases/20-variant-ratio-on-section.brief @@ -0,0 +1,7 @@ +// expect: 5:1 a deliverable ({1:1}) tags lines and beats +Title: x +Format: 9:16, 30 s | 1:1, 15 s + +# hook {1:1} +@MAYA +Hi. diff --git a/brief/conformance/cases/21-pacing.brief b/brief/conformance/cases/21-pacing.brief new file mode 100644 index 00000000..a4add821 --- /dev/null +++ b/brief/conformance/cases/21-pacing.brief @@ -0,0 +1,12 @@ +// expect: ok +Title: pacing rules +Format: 9:16, 20 s + +! no shot longer than 6 s +! the hook ends by 3 s +! a cut at least every 4 s +! claims sourced + +# hook +@JUNE +That's forty hours, gone. diff --git a/brief/conformance/cases/22-delivery-before-speaker.brief b/brief/conformance/cases/22-delivery-before-speaker.brief new file mode 100644 index 00000000..855bce86 --- /dev/null +++ b/brief/conformance/cases/22-delivery-before-speaker.brief @@ -0,0 +1,8 @@ +// expect: ok +Title: a delivery just before its speaker +Format: 9:16, 20 s + +# the hook +(measured) +@MAYA +Every agency is a state machine. diff --git a/brief/conformance/cases/23-delivery-alone.brief b/brief/conformance/cases/23-delivery-alone.brief new file mode 100644 index 00000000..285d7db8 --- /dev/null +++ b/brief/conformance/cases/23-delivery-alone.brief @@ -0,0 +1,7 @@ +// expect: 6:1 delivery stands under a speaker +Title: x +Format: 9:16, 20 s + +# the hook +(measured) +~ b-roll: the office at night diff --git a/brief/conformance/ink_parity.py b/brief/conformance/ink_parity.py new file mode 100644 index 00000000..9c0515cc --- /dev/null +++ b/brief/conformance/ink_parity.py @@ -0,0 +1,66 @@ +"""The ink profile's parity: every .brief we have, written as an ink story (raea-brief ink) and lowered back +(raea-brief lower, then parse), gives the compiler the same graph: the same lines with their sections, takes, +speakers, delivery, punch, parts and variants, the same open beats, checks, stylesheet, title and format. + + uv run -q python ~/raea/brief/conformance/ink_parity.py DIR... every *.brief in each DIR (and DIR/*.txt answers) +""" +import json, re, subprocess, sys, tempfile +from pathlib import Path + +BIN = Path.home() / "raea/brief/target/release/raea-brief" + + +def graph(p): + r = subprocess.run([str(BIN), "parse", str(p)], capture_output=True, text=True) + return (json.loads(r.stdout), "") if r.returncode == 0 else (None, r.stderr.strip()) + + +def shape(g): + # ink collapses a run of spaces inside text to one (its own rule; quoted lines match transcripts by word, so it's moot) + ws = lambda t: " ".join(t.split()) if isinstance(t, str) else t + items = [(i["type"], i.get("section"), i.get("take"), i.get("speaker"), i.get("delivery"), i.get("punch"), ws(i.get("text") or i.get("phrase")), + [(n["kind"], n["props"], n["utils"]) for n in i.get("notes", [])], i.get("find"), i.get("variants")) for i in g["items"] if i["type"] != "transition"] + return {"items": items, "checks": sorted(c["rule"] for c in g["checks"]), "style": g["style"], "title": g["title"], "format": g["format"], + "sections": [s["name"] for s in g["sections"]], "synopsis": [s["synopsis"] for s in g["sections"]]} + + +def main(): + files = [] + for d in map(Path, sys.argv[1:]): + files += sorted(d.glob("*.brief")) if d.is_dir() else [d] + files += sorted(d.glob("*.txt")) if d.is_dir() else [] + work = Path(tempfile.mkdtemp()) + n = same = skipped = 0 + fails = [] + for f in files: + text = f.read_text() + m = re.search(r"```[\w-]*\n(.*?)```", text, re.S) + b = work / f"{f.parent.name}__{f.stem}.brief"; b.write_text(m.group(1) if m else text) + g, err = graph(b) + if g is None: + skipped += 1; continue # a brief that's refused has no graph to compare + n += 1 + ink = work / (b.stem + ".ink") + r = subprocess.run([str(BIN), "ink", str(b)], capture_output=True, text=True); ink.write_text(r.stdout) + g2, err2 = graph(ink) + if g2 is None: + fails.append((b.name, "refused as ink", err2.splitlines()[:2])); continue + a, c = shape(g), shape(g2) + if a == c: + same += 1 + else: + k = next(k for k in a if a[k] != c[k]) + if k == "items": + i = next((i for i, (x, y) in enumerate(zip(a[k], c[k])) if x != y), min(len(a[k]), len(c[k]))) + fails.append((b.name, f"item {i + 1}", [a[k][i] if i < len(a[k]) else None, c[k][i] if i < len(c[k]) else None])) + else: + fails.append((b.name, k, [str(a[k])[:200], str(c[k])[:200]])) + print(f"{n} briefs that parse ({skipped} refused, left out): the same graph through ink {same}/{n}") + print(f"the ink stories are in {work}") + for x in fails[:15]: + print("-", x[0], x[1], str(x[2])[:400]) + return 0 if same == n else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/brief/conformance/parity.py b/brief/conformance/parity.py new file mode 100644 index 00000000..cd068927 --- /dev/null +++ b/brief/conformance/parity.py @@ -0,0 +1,110 @@ +"""P1's parity: every score script the bench wrote, converted to a .brief (raea-brief convert) and read back by the +Rust parser (raea-brief parse), gives the compiler the same Script front.parse reads from the Fountain, in all the +notation defines; and what the notation doesn't define, which front.parse reads as unknown or drops, is in the .brief +as a comment, so nothing is lost. + + uv run -q python ~/raea/brief/conformance/parity.py [--keep DIR] + +The corpus is score/bench/out (not committed): s2b's ten compiled scripts and the 100 written cold in stage 1 +(a2, a2a, a3, a3a, c3), read where they are. +""" +import json, re, subprocess, sys, tempfile +from pathlib import Path + +RAEA = Path.home() / "raea" +sys.path.insert(0, str(RAEA / "score")); sys.path.insert(0, str(RAEA / "score/bench")) +from compiler import front # noqa: E402 +import fountain # noqa: E402 score's Fountain reader, out of the compiler since P5 +from compiler.sheet import MUSTS, notes_in # noqa: E402 + +BIN = RAEA / "brief/target/release/raea-brief" +OUT = RAEA / "score/bench/out" +READ = {":root": {"background", "music", "music-gain", "sfx-gain", "platform", "eyes"}, "captions": {"place", "keys"}} + + +def corpus(): + fs = sorted(OUT.glob("s2b/*/script.fountain")) + for arm in ("a2_fountain_css", "a2a_fountain", "a3_refs", "a3a_refs_plain", "c3_xsheet"): + fs += sorted((OUT / arm).glob("*.txt")) + return fs + + +def shape(sc): + """what the compiler reads from a Script: everything the notation defines""" + note = lambda n: (n.kind, n.props, [u for u in n.utils if front.UTIL.match(u)], n.anchor) + # a note left open is words of the line to front.parse (a misreading: no take says them); a note with nothing the + # notation reads in it does nothing + lines = [(l.role, l.take, re.sub(r"\s*\[\[[^\]]*\]?$", "", l.text), l.delivery, l.punch, + [note(n) for n in l.notes if n.kind or note(n)[2]]) for l in sc.lines] + style = {s: {k: v for k, v in d.items() if k in READ[s]} for s, d in sc.style.items() if s in READ} + style = {s: d for s, d in style.items() if d or s == "captions"} + return {"title": sc.title, "format": sc.format, "secs": sc.secs, "sections": sc.sections, "lines": lines, + "screen_text": sc.screen_text, "style": style} + + +def unknowns(text, sc): + """what front.parse reads but the notation doesn't define: unknown utilities, title keys, stylesheet properties""" + out = [u for n in notes_in(text) for u in n.utils if not front.UTIL.match(u)] + body, css = (front.strip_fence(text).split("\n---\n", 1) + [""])[:2] + for sel, b in re.findall(r"([^{}]+)\{([^}]*)\}", css): + for d in [x.strip() for x in b.split(";") if x.strip()]: + if sel.strip() == "@must": + if not any(d.lower().rstrip(".") == m for m in MUSTS): out.append(d) + elif sel.strip() not in READ or d.split(":", 1)[0].strip() not in READ[sel.strip()]: + out.append(d) + return out + + +def main(): + keep = Path(sys.argv[sys.argv.index("--keep") + 1]) if "--keep" in sys.argv else Path(tempfile.mkdtemp()) + keep.mkdir(parents=True, exist_ok=True) + rows, fails = [], [] + for f in corpus(): + text = f.read_text() + name = f"{f.parent.name}__{f.stem}" if f.name == "script.fountain" else f"{f.parent.name}__{f.stem}" + b = keep / f"{name}.brief" + b.write_text(subprocess.run([BIN, "convert", f], capture_output=True, text=True, check=True).stdout) + p = subprocess.run([BIN, "parse", b], capture_output=True, text=True) + if p.returncode: + fails.append((name, "refused", p.stderr.strip().splitlines()[:3])); rows.append((name, False, False, False)); continue + a = fountain.parse(text) + g = json.loads(p.stdout) + same = shape(a) == shape(front.from_graph(dict(g, source=b.read_text()))) + if not same: + sa, sb = shape(a), shape(front.from_graph(g)) + diff = [k for k in sa if sa[k] != sb[k]] + detail = [] + for k in diff: + if k == "lines": + for i, (x, y) in enumerate(zip(sa[k], sb[k])): + if x != y: + detail.append(f"line {i + 1}: {x} != {y}"); break + if len(sa[k]) != len(sb[k]): + detail.append(f"{len(sa[k])} lines != {len(sb[k])}") + else: + detail.append(f"{k}: {sa[k]} != {sb[k]}") + fails.append((name, "differs", detail[:2])) + bt = b.read_text() + kept = all(u in bt for u in unknowns(text, a)) + if not kept: + fails.append((name, "dropped", [u for u in unknowns(text, a) if u not in bt][:3])) + fmt = subprocess.run([BIN, "fmt", b], capture_output=True, text=True) + b2 = keep / f"{name}.fmt.brief"; b2.write_text(fmt.stdout) + p2 = subprocess.run([BIN, "parse", b2], capture_output=True, text=True) + g2 = json.loads(p2.stdout) if not p2.returncode else None + strip = lambda g: json.dumps({k: v for k, v in g.items() if k != "file"}, sort_keys=True, default=str) if g else None + drop_at = lambda g: re.sub(r'"from": "[^"]*"', '"from": 0', re.sub(r'"at": \[\s*\d+,\s*\d+\s*\]', '"at": 0', strip(g))) if g else None + roundtrip = g2 is not None and drop_at(g) == drop_at(g2) + if not roundtrip: + fails.append((name, "fmt", (p2.stderr.strip().splitlines() or ["the graph changed"])[:2])) + rows.append((name, same, kept, roundtrip)) + n = len(rows) + print(f"{n} scripts: same Script {sum(r[1] for r in rows)}/{n}, nothing dropped {sum(r[2] for r in rows)}/{n}, fmt reads back the same {sum(r[3] for r in rows)}/{n}") + print(f"converted .brief files in {keep}") + for name, why, detail in fails[:30]: + print(f"- {name}: {why}: {detail}") + return 0 if all(all(r[1:]) for r in rows) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/brief/format.feature b/brief/format.feature new file mode 100644 index 00000000..f1c033d9 --- /dev/null +++ b/brief/format.feature @@ -0,0 +1,324 @@ +Feature: .brief, one file from the client's ask to the compiled edit (the roadmap Track P) + The founder, 2026-10-17: "fix the fountain format so that it's entirely in .brief. It's its own format, which brings + together the goals of the fountain format; we had to make it more machine readable while allowing for a bit more + diverse creative planning and checking against our runtimes. A way to plan with variables, plan with + generalizations." + + Today three files say what one piece is: the client's brief (Markdown, split by raea-beats into beats, Track F), + script.fountain (score's notation, compiled by score/scorec.py, Track R) and the rrl expects and Must: rules the + checks read. Fountain is kept for what it measurably does (the screenplay form beat rrl by +1.95 on the judge's ad + score, quoted lines anchor at 0.90-0.97; score/bench/results.feature), and replaced where it fails a machine: its + readers guess (unknown tokens 6.0 a script written cold), it has no way to say "a shot of the product here, which + one we don't know yet", and no place for the rules the edit must keep. + + Rule: The goal + Scenario: What .brief is when it's done + Then one plain-text file, `NAME.brief` (a space's own is `brief.brief`), holds the piece at every stage of + planning: the ask and its rules, beats still open, lines quoted from takes, parts, sound, and the checks + And it reads as Fountain to a writer and to M3 (title page, `# sections`, `= synopses`, `.TAKE`, `@SPEAKER`, + `(delivery)`, quoted lines, `[[parts | utilities]]`, `---` stylesheet), so what M3 already writes well stays + And it has one grammar with one reading per line: `raea-brief parse` gives the intent graph as JSON (sections, + beats, lines with source spans, parts with anchors, sound, variables, checks) or refuses with line:column and + what was expected; `raea-brief fmt` writes it back unchanged in meaning + And it compiles to one target, an @raea/motion composition (edit.tsx, scorec's SDK backend; the founder, 2026-10-17: + TypeScript/React is the only path, rrl's backend goes), and every check compiles from the same graph, never + from the text + And it is one way in, not a required step: the agent may write edit.tsx and use `raea cut` / `raea add` with no + brief at all + And `[[parts]]` name components in the space's components/ (shadcn-style, copied from ~/raea/cli/registry: + captions, screen-fit, face-frame, callout, end-card so far; styled only from brand/brand.css tokens through + Tailwind classes, cli/template/theme.css) + + Rule: What the format adds to Fountain (a proposal; settled in P0 with an agent session) + Scenario: Plan with generalizations: open beats + Then a `~` line is a beat not yet bound to footage: `~ product: the cleanser pumped into wet hands + [find: product hands action]`, the same kind and finds raea-beats writes (to-camera, b-roll, product, screen, + end-card; face, speech, product, hands, screen, text, place, action, logo) + And the compiler resolves it against the source table (F2): bound to a clip and moment when covered, kept open + and named in the sheet when weak, a make() prompt or a reshoot item when missing (F3) + And a quoted line under `@SPEAKER` is a beat bound exactly, as in score today; a `~ to-camera:` beat with no + quote asks for the line that says it, which the sheet proposes from the transcripts for the writer to quote + Scenario: Plan with variables and variants + Then `$name: value` on the title page names a value used anywhere after it (`$product`, `$launch`, a brand + colour); an undefined variable is refused where it's used + And `Format:` may list several deliverables (`9:16, 30 s, tiktok | 1:1, 15 s, instagram`); a section, line or + part tagged `{1:1}` belongs to that cut only, so one brief compiles to every cut the client asked for + Scenario: Checks the runtimes run + Then a `!` line states a rule the edit must keep (`! never says "game changer"`, `! nothing covers the face`, + `! the hook reads within half a second`), from a fixed vocabulary each lowering to a TS predicate or a + `raea check` fault over the render manifest (render.json: each clip's take, in, out and box, each part's box + per frame) and cuts.json, an agent session's phase 4 shape, or refused as unknown + And the brief's set-aside units (dates, deliverables, instructions) land here or in variables, so nothing in the + client's ask is lost between the brief and the edit + And the sheet answers each check pass or fail with the frame, as it answers each line's timing today + + Rule: A workspace holds many briefs (the founder, 2026-10-17: "it could be many files for a workspace like + anything.brief") + Scenario: Pieces and shared briefs + Then a .brief with a `Format:` line is a piece: `raea script NAME.brief` compiles it to NAME.tsx, and + `raea script` with no name compiles every piece in the space + And a .brief without one is shared: its variables, checks and open beats apply only to the pieces that name it + with `Uses: client.brief, brand.brief` on their title page, in that order, the piece's own last (a value + set twice takes the later one, as CSS does; checks add up and none can be removed) + And the client's ask is one shared brief (raea-beats writes it: the ask's beats as `~` lines, its set-aside units + as variables and `!` checks), and each piece made from it is checked against it: the sheet lists each of its + beats as covered by a piece or by none, so three cuts of one launch answer the ask together + And a `Uses:` cycle or a missing file is refused where it's named + + Rule: Every find is a perception fact (measured by survey, 2026-10-17) + Scenario: What the find words can be checked with today + Then face, speech, text and screen have detectors (ingest's faces.json tracks at 4 fps, VAD and performance's + speaking, read-text rows, layout's screen zone and screenshot flag); hands and place have partial ones (the + hands command, not in ingest; Apple scene labels, empty on the portable backend); product, logo and action have + none and come only from a SigLIP phrase + And the sheet says how each beat was bound: by a fact, or by a SigLIP score against FIND_THRESHOLD, so a + product beat bound by a phrase alone is shown as weaker than a face beat bound by a track + And a variable can carry a picture (`$product: media/milky-jelly.png`, `$logo:` from brands.json) so product and + logo beats search image against frames, not text against frames, until perception has an object detector + (object.rs's EdgeTAM tracker is there, not yet in ingest) + Scenario: Finds take the facts perception has that the words lack + Then a find may be a predicate over a moment's facts: `people:1`, `speaking`, `eye-contact`, `framing:close-up`, + `still` or `moving`, `no-text` (no captions burned in), `screen`, `bright`; each lowers to a column of the + moment record (Track L's slots and L3 tracks), never to a guess + And a `!` check uses the same predicates over the render instead of the footage (`! speaking -> face`: the + speaker is in the picture whenever they talk) + Scenario: The source table F2 needs (the gap) + Then today it's three stores: the ingest folder per clip (~/.cache/raea-ingest), the SigLIP columns at 8 fps + (~/.cache/raea-meaning/cols) and the takes' words.json; `raea-meaning find` returns one best frame per clip + And F2 needs one table of moments (take, from, to, the facts above, the SigLIP row, the words said) with + top-k spans per query, so a `~` beat binds to a span the compiler can cut, not to a frame + Scenario: Perception at compile time follows the clip, not the take + Then the compiler reads the face, safe area and burned-in text for each kept clip's span from the ingest store + (faces.json is already per frame at 4 fps), not one see-layout still per take reused for every clip of it, and + caches nothing it can read from ingest + And the face it places around is the speaker's: the face track that is speaking (performance's speaking) when + more than one is in shot + And perception.json is written per frame over each clip (the engine's percAt already takes a frame-keyed map), + so Region, captions and callouts follow a speaker who moves + Scenario: What the rest of the path drops today (owners named, not ours to change) + Then the host's render passes --words but never --perception, so in a `raea` project Region has no face + (an agent session, host.rs) + And framing="face" and punchIn only mark the element, and the proof (proofBoxes) is never run by the renderer + (an agent session, react/src/motion.rs) + And --safe-top/--safe-bottom aren't CSS variables, so screen-fit and end-card can't keep out of the UI zones + (@raea/motion) + And `raea check` runs cuts and edge text only; the face and text-over-face checks still read rrl, so `!` checks + need render.json (each part's box per frame) and the render perceived again (an agent session's phase 4) + + Rule: P0 and P1, measured (2026-10-17) + Scenario: The grammar and the parser + Given brief/format.md (the grammar), brief/src/format.rs (the parser, in Rust) and `raea-brief parse|fmt|convert| + compile`; 13 conformance cases in brief/conformance/cases, each saying the reading or the refusals (line:col) it + gives (cargo test) + When the 110 scripts the bench wrote in Fountain (s2b's 10 compiled ones; the 100 written cold in stage 1) are + converted, parsed and read back into score's Script (brief/conformance/parity.py) + Then 110 of 110 give the compiler the same Script front.parse reads from the Fountain, in everything the notation + defines; 110 of 110 keep what it doesn't (unknown utilities, title keys, style) as comments; fmt reads back the + same graph 110 of 110 + And the corpus said what writers mean by Fountain's marks: `!` stood before a shot description 157 times and + `@must { }` held the rules 50 times, both dropped by score's reader; convert makes them `~` beats and `!` checks, + and the parser refuses `!Action ...` with the open beat it should be + And front.parse's misreadings convert to what was meant, counted as divergences: a note left open (`[[... ]`) + is words of the line to front.parse and a comment here; a fenced answer is read as front.parse reads it + Scenario: The ten eval briefs as the client's ask + Then `raea-beats brief BEATS.json` writes each split brief as a shared .brief: its 42 beats as `~` lines with + their words and source as comments, the set-aside units as comments; all ten parse (brief/examples/*.brief) + And turning set-aside units into variables and checks is still the agent's (a date is `$launch`, "don't say + game changer" is `! never says "game changer"`) + + Rule: P3, P3b and P4, first slice (2026-10-17) + Scenario: Open beats bound to footage (score/compiler/moments.py) + Given a moment per SigLIP frame of each ingested take (8 a second): faces, the speaker's track, speaking and eye + contact, framing, motion, text, screen, luma, and whether words are said + When a beat is searched: its detected finds filter the moments, its phrase (or $picture) ranks them, a span grows + from each peak (1.5-4 s), and the best span is covered (>= 0.10), weak (>= 0.06) or missing + Then on media/fixtures (a screen recording, a two-person take, b-roll; no transcripts at all) a brief of four + open beats compiles: "two people in glasses" covered at 0.116 on the take, "a dashboard with a chart" weak at + 0.072 on the screen recording, "coffee poured into a cup" missing (0.046; find stock or shoot it), the end card + named a part + And a brief with no transcripts compiles when it has open beats (an agent session's Arock case: a silent screen recording + no line can come from); a script that resolves to nothing is refused, not written as an empty composition + Scenario: A workspace of pieces (raea-brief compile --all; score/cover.py) + Then every *.brief with a Format: compiles, each to NAME.tsx with its own NAME.words.json, NAME.perception.json + and NAME.checks.json; a piece with several deliverables to NAME-9x16.tsx, NAME-1x1.tsx, each the right shape and + holding only what its {ratio} tags allow + And each beat of a shared brief is answered against the footage each piece cut (the ask's phrase on its clips' + frames where its finds hold): on the fixtures, "two people" covered by three cuts at 0.112, the screen and the + coffee by none, with the closest + Scenario: Checks (sheet.checks; NAME.checks.json) + Then `never says "..."` and the length are answered at compile time, pass or fail with the line or the seconds; + the other musts and FACT -> FACT go to checks.json for `raea check` on the render (an agent session's render.json) + Scenario: Limits the measurements found + Then the speaker is the longest-visible face, not the one whose mouth moves with the voice + And the picture threshold (0.70, image against frame) isn't calibrated, nor is "weak" (0.06) + And ingest's mesh step aborts on a long take (576 s, an Objective-C exception), so it gets faces and facts but no + SigLIP column and its beats can't be searched (posted for an agent session) + + Rule: P1b, measured (score/bench/p1b.py, 2026-10-17) + Scenario: Perception per clip from the ingest store against one still per take + Given the ten s2b spaces compiled both ways (RAEA_SCORE_INGEST=0 and 1), their 29 takes ingested once (two abort + in ingest's mesh step after faces and facts are written); the truth is each take's ingest, the speaker's + confirmed face at every 4 fps sample, through each version's own crop + Then a part's band holds the speaker's face in 64 of 482 samples a part shows, against 107 of 482 (13.3% against + 22.2%): framing and bands from each clip's own span, not from the middle of the take's first line + And captions over captions burned into the source: 0 both ways (ingest found no caption-like burned text in + these takes), so the measure says nothing on these takes + And perception.json is frame-keyed at 4 fps over each clip (a no-face entry where the speaker isn't seen), so + Region-placed components follow the face in the render + + Rule: P5's gate, stage 1 (score/bench/stage_brief.py, 2026-10-17) + Scenario: M3 writes .brief cold and revises once, as c3 did in Fountain + Given the same 10 scenarios, requests, transcripts and parts kit as stage 1, two reps each; the notation page + arms/b1_brief.md; one revision from what the compiler says (the parser's refusals, score's sheet); measured as + stage 1 measures c3 and judged by the same judge (gemini-4-argon, temperature 0) + Then, beside stage 1's rows: + | arm | ad | follow | fit | verbatim | length ok | unknown | + | a2 Fountain + CSS, cold | 5.25 | 3.55 | 5.30 | 0.90 | 0.50 | 6.0 | + | c3 Fountain + CSS, revised | 5.80 | 3.95 | 6.40 | 0.93 | 0.80 | 0.8 | + | b1 .brief, cold (parser v2) | 5.50 | 4.35 | 5.00 | 0.90 | 0.50 | 0.7 | + | c4 revised from parser v1's sheet | 4.95 | 4.70 | 5.85 | 0.97 | 0.65 | 0.2 | + | c5 revised from parser v2's sheet | 5.65 | 4.65 | 6.10 | 0.94 | 0.70 | 0.2 | + | c6 revised, the sheet saying what to cut | 5.00 | 4.40 | 6.05 | 0.97 | 0.85 | 0.2 | + And written cold, .brief beats Fountain + CSS on the ad (+0.25), on followable (+0.80) and on what the reader + can't read (0.7 refusals against 6.0 unknown tokens); with parser v1 the cold answers had 2.4 + And parser v2 reads the forms M3 wrote that have one meaning: an apostrophe inside an anchor (on:'don't know'), + a must without its "the" or with its length in seconds, several phrases after never says, people:N-M, a note on + its own line after the line it's on (front.parse reads the same; parity holds 110/110) + And the length was the gap: told "OVER by 3.3 s" the writer cut to 6.7 s; told "OVER by 24 s" it shortened lines + by changing their words, so no take said them. c6's sheet names the whole lines to drop (the fewest that land it + inside) or the seconds to add, and for a line no take says, what the take does say; length ok 0.85 and unknown + 0.2 pass the gate (0.80, 0.8) + And the judge's ad score moved 4.95-5.65 over three revisions of the same cold answers, and c6's 5.00 is under + c3's 5.80: a cost to watch in stage 2, not hidden + And c3 and a0 also missed the length on client-a and kelly in both reps; the sheet improvements are the + compiler's (c3 had the old sheet) + + Rule: P5's gate, stage 2 (score/bench/stage2_brief.py, 2026-10-17) + Scenario: Rep 0 of c3 and c6 rendered on the SDK with the same parts and kit, watched by stage 2's judge + Given both arms compiled to @raea/motion (c3's Fountain through scorec, c6's .brief through raea-brief compile), + perception per clip from the ingest store, the registry's lockup, statcard, notthat, follow and captions, one + house brand kit for every scenario (no per-client kit on disk is reliable), no sound, as stage 2b + Then c3 renders 10 of 10, judge mean 2.70; c6 renders 9 of 10, mean 2.78 on the nine (2.50 with the failure as 0) + And c6's tenth refuses to compile: a prop left open (`text:"+ try $brand |`) that its one revision didn't fix; + Fountain's reader would have read it wrong without saying + And every render of both arms is rejected; the judge names the render and the cuts more than the plan: cards over + the face, captions dropping out for a sentence or overlapping a card, cuts mid-word, blooper takes + And so the gate as written isn't met: 3.1 was c3 on rrl's renderer and parts kit, and on the SDK c3 itself scores + 2.70; 10 of 10 renders misses by the one refusal; the user re-based the gate (the next rule), and P5 was done + + Rule: P5's gate, re-based, and P5 done (2026-10-17) + Scenario: The gate on the renderer both formats now share + Given the founder's call (2026-10-17): gate on .brief matching or beating Fountain on the SDK renderer, with the agent's + refusal loop given the second pass it has in the product + When a c6 answer the parser still refuses goes back to M3 with its refusals only (c7; one of the 20, the open quote) + Then c7 renders 10 of 10, judge mean 2.80, against Fountain's 10 of 10 at 2.70 on the same renderer, parts and + kit; length ok 0.85 (Fountain 0.80); unknown 0.0 (Fountain 0.8) + And so the Fountain path left the compiler: scorec reads .brief only (through raea-brief), refuses a + script.fountain with the command that converts it, and score's Fountain reader is kept in score/bench/fountain.py + to re-run the recorded comparisons; the converted brief compiles to the same edit.tsx, words and perception the + Fountain did (client-e, byte for byte) and parity stays 110 of 110 + And void's agent writes no Fountain (an agent session: `--sop ts` by default, 496a850); its old score tool goes with rrl + And what the judge rejects in both arms is the render's craft (cards over the face, captions dropping out, cuts + mid-word, blooper takes): compiler and registry work, not the format's + + Rule: Ink against .brief, and the decision (2026-10-17) + Scenario: The same 10 scenarios written in ink's raea profile (arms/i1_ink.md), revised and fixed as c7 was + Given M3 writing ink cold (i1), one revision from the parser's refusals and the sheet (i6), the refusal loop's pass + (i7); rep 0 of i7 rendered on the SDK with c7's parts, house kit and judge (stage2_brief.py) + Then, beside .brief: + | arm | ad | follow | fit | verbatim | length ok | unknown | readable cold | renders | judge (render) | + | c7 .brief, revised, fixed | 4.90 | 4.40 | 6.20 | 0.97 | 0.85 | 0.0 | 1.00 | 10/10 | 2.80 | + | i7 ink, revised, fixed | 5.35 | 4.10 | 5.40 | 0.89 | 0.75 | 0.0 | 0.60 | 10/10 | 2.80 | + And ink renders the same (2.80, 10 of 10) and reads a little better to the plan judge (+0.45, inside its own swing + between rounds), but M3 writes it worse: 40% of cold answers unreadable, fewer lines said verbatim, the length + and the fit missed more often + And so .brief stays the format the agent and people write; ink stays a supported surface (raea-brief reads .ink, + `raea-brief ink` writes it) for pieces that branch or keep state, and blade-ink is the runtime a .brief can run on + + Rule: The brief checked on the render (raea-brief check, @raea/data/check.ts; 2026-10-17) + Scenario: The 10 c7 renders re-rendered with the manifest and checked (--battery beside each brief's own rules) + Given each piece's facts as tables: its graph, the words as cut, the render manifest, faces read back from the + rendered frames twice a second, perception's moments of the takes on screen (score/bench/check_c7.py; the run's + record, all 10 checked with every rule measured, is score/bench/check_c7.json) + Then, beside what stage 2's judge named: + | scenario | judge | the checks fail | the judge named, the checks agree | + | shawn-williams | 3 | text over a face 3.5 s (42%), a 11.8 s shot | captions across his face 0:03-0:15 | + | client-a| 3 | speaking without a face 18.5 s, 67 s of 34-46, a 16.2 s shot | the callout over his eyes at 0:18 | + | apollo | 3 | a card over the face 6.5-10 s (26%), 47 s of 30-40, a 17.7 s shot | the card over her face 0:06-0:09 | + | client-e | 1 | speaking without a face on 15 of 24 samples, an 11.7 s shot | rehearsal footage, the speaker off shot | + | client-e | 3 | text over a face 31.5 s (81%), speaking without a face 37 of 50 | captions on the kid's face ~0:34 | + | dr-moy | 4 | a 6.5 s shot | (none of the judge's: missing word, captions dropping out) | + | kelly | 3 | text over a face 3.5-6 s and 65.5 s (82%), 77.6 s of 51-69 | the title over her eyes 0:02-0:05, the card over her face 1:01-1:05 | + | client-1 | 3 | speaking without a face 17 s, a 10.5 s shot from 16 s, text over a face 26.5 s | dead air while he looks away 0:16-0:19 | + | client-2 | 3 | nothing but 5.9 s without a cut | (the judge's: his face cut by the frame's edge, captions dropping out) | + | client-3 | 2 | 24.4 s of 25.5-34.5, a 12.5 s shot from 8 s | the blooper take from 0:08 | + And every place the judge named text over a face, the checks found it, but one: client-3, where the judge says + the captions cover the mouth and the geometry says 7.2% at most, the captions under the chin (the frames agree + with the geometry); client-a's callout hides the eyes so no face is read there, and the check names it as + speaking without a face + And what the judge names that no rule measures: captions dropping out, text over other text, an ending cut off + mid-sentence (a cut mid-word is caught; mid-sentence is the sheet's "reads to check"), duplicate and blooper takes + as such, low contrast: the edge of what the rule set covers + Scenario: raea check runs it (an agent session, 130af72) + Then `raea check NAME` runs `raea-brief check NAME SPACE --video` for a piece compiled from a brief; its FAILs are the + agent's faults ("brief ! the hook reads within half a second: nothing is shown or said in the first half second", + on the fixture space's vtest-A); every compiled piece has its own .score/NAME.graph.json for it + Scenario: The rest of this goal's constructs + Then typed parts: on the registry's components (what every bench space's components/ holds: stage2_brief.py copies + the registry's lockup, statcard, notthat, follow and captions into each), 73 of the 110 corpus scripts and 19 of + the 20 c7 briefs type clean; + the refusals are real (35 `statcard big:90` where big is a string, a notthat without its `not`, captions given + l1-l3); a delivery just before its speaker is now read as that speaker's + And on spaces whose components the agent wrote: the 38 eval spaces with components/ (void's runs of 2026-10-16 + and 17) give 111 components, 47 of them the agent's own or changed by it; props are read for every one (103 have + props, the other 8 take none); on one with the agent's `stamp` (words: string, required; sub: string), a brief + line `[[stamp sub:"verified" color:"gold"]]` is refused for `color` and for the missing `words`, + `[[stamp words:270]]` for writing a string as a number, and `[[stamp words:"SAFE" sub:"for you"]]` passes + And claims, alternatives, variants and pacing compile on real spaces (client-e: four cuts of a two-variant, + two-deliverable brief; "See the bass?" picked over "There he is." with the reason); coverage of a shared ask runs + per cut; @raea/data's loadBrief answers which line is said and which parts show at a frame by query + And the renderer leak this found (60 MB a frame on a 16:9 edit, after a4eb038) was fixed by an agent session (c21d7e8) + + Rule: c8, the full feature set on the bench (stage_brief.py, stage2_brief.py; 2026-10-17) + Scenario: The b1 cold answers revised with everything, then the check loop + Given the notation page with alternatives, claims and pacing rules; one revision from the parser's refusals (typed + against the registry's components), the sheet (with what to drop or add) and the compile-time checks (c8r); then + the loop the product runs, twice: refusals, failing checks and the length's "To fit" sent back (c8, then c8l) + Then, beside c7: + | arm | ad | follow | fit | verbatim | length ok | unknown | renders | judge (render) | + | c7 .brief, revised, refusal pass | 4.90 | 4.40 | 6.20 | 0.97 | 0.85 | 0.0 | 10/10 | 2.80 | + | c8 full set, one check-loop pass | 5.85 | 4.95 | 6.55 | 0.98 | 0.75 | 0.0 | 10/10 | 3.00 | + | c8l full set, two check-loop passes | 5.00 | 4.50 | 6.25 | 0.98 | 1.00 | 0.0 | 10/10 | 3.00 | + And so the gate holds: 10 of 10 renders, the judge's mean on the videos 3.00 (c7 2.80), every length inside its band, + nothing the parser can't read; the plan judge's ad score drops when lines are dropped to fit (5.85 to 5.00), and + the videos' judge doesn't follow it + And every render of both is judged: c8's client-1 first came back from the judge empty and was judged again (3); + c8l, which rewrote that script, rendered and judged its own (3); c8l's ten: 4 3 3 2 3 3 4 3 3 2, mean 3.00 + And M3 used neither alternatives nor claims unprompted; the length came from the loop sending the failing length + and its "To fit" back + And the spend, estimated from the counts (the OpenRouter key's own usage, $21.58 that day, is shared with other + sessions' eval runs): 220 plan judgings at about 9k tokens (about $2.5-5), 44 video judgings at about 10k (about + $0.5-1), 161 MiniMax-M3 calls through the host app at about 35k (about $1.7): about $5-8, under the $10 asked + + Rule: The plan + Scenario: Steps, with owners + Then P0 (raea-01 with an agent session): the grammar written down (brief/format.md) with conformance cases, its corpus + every script.fountain the bench has written (score/bench/out/s2b, s2c, c3) and the ten eval briefs + And P1 (raea-01): the parser in Rust in raea/brief (`raea-brief parse|fmt`), its graph equal to front.parse's + Script on every corpus script (parity), every corpus script converted with nothing dropped, and the edit.tsx + compiled from the graph equal to sdk.py's from the Fountain (no rrl parity; compiler/rrl.py is deleted) + And P2 (raea-01 then an agent session): the CLI contract, `raea-brief parse FILE` (graph JSON on stdout; refusals with + line:column on stderr, exit 2) and `raea-brief compile FILE SPACE [--o edit.tsx]` (parse, then scorec's SDK + backend on the graph; the COMPILED line and the sheet on stdout); an agent session wires it as `raea script + [NAME.brief]`, a host op in void, and the procedures teach the format; script.fountain still read until P5 + And P1b (raea-01): the compiler's perception per kept clip from the ingest store, the speaking face, and + perception.json per frame; measured on the stage-2 scripts as faces the parts cover and captions over burned-in + text, before and after + And P3 (raea-01, on Track F): the moments table and top-k span search, open beats resolved against it (F2) with + how each was bound, and proposed lines in the sheet; raea-beats writes the client's ask as a shared .brief + And P3b: workspaces of many briefs (`Uses:`, pieces, coverage of the shared ask across pieces) + And P4: variables and variants (one brief, every deliverable), and `!` checks lowered to the runtimes' checks + And P5: the Fountain path deleted only when the stage-2 bench matches or beats c3 on it: judge mean at least + 3.1, length ok at least 0.80, unknown tokens at most 0.8, renders 10 of 10 + And every step above is done (2026-10-17), and the brief model after it (the rules above: checks on the render, + typed parts, claims, alternatives, variants, pacing, the brief as entities, c8) diff --git a/brief/format.md b/brief/format.md new file mode 100644 index 00000000..dee345b8 --- /dev/null +++ b/brief/format.md @@ -0,0 +1,339 @@ +# .brief + +A `.brief` is a plain-text plan for one video, or something several plans share. It reads as Fountain (a screenplay +form, which M3 writes well and which made better ads than rrl did; score/bench/results.feature) with one reading for +every line. `raea-brief parse FILE` turns it into the intent graph (JSON); anything it can't read is refused with +`FILE:line:col` and what it expected. The spec, the goal and the plan are in brief.feature and format.feature. + +``` +Title: Milky Jelly: the gel that doesn't strip +Format: 9:16, 30 s, tiktok | 1:1, 15 s, instagram +Uses: client.brief +Angle: dry skin can use a gel +$product: Milky Jelly +$pack: media/milky-jelly.png + +! never says "game changer" +! nothing covers the face + +# the objection += Name the fear before the product. +.TAKE02 - KITCHEN +@MAYA +(warm, a little sheepish) +I always thought gel cleansers would wreck my skin. [[captions keys:"wreck" | place-low]] + +# the pour +~ product: the cleanser pumped into wet hands [find: $pack hands action still] + +# the ask +@MAYA +Try $product. [[end-card text:"$product" | to-end place-center]] {9:16} + +--- +:root { music: "warm room tone, soft keys"; music-gain: -24; } +``` + +## The file + +A file is a title page, a body, and an optional stylesheet after a line that is exactly `---`. A file wrapped whole in +one Markdown code fence (```` ``` ````) is read as what's inside it. Lines are trimmed; a blank line ends a speaker's +block. Columns in refusals count from 1 on the line as written. + +## Title page + +`Key: value` lines from the top of the file to the first blank line. + +| key | what it is | +|---|---| +| `Title:` | the piece's name | +| `Format:` | the deliverables: `RATIO, LENGTH[, PLATFORM]`, several joined by `\|`. A file with a Format is a **piece** (it compiles to an edit); without one it is **shared** (it only applies through another's `Uses:`) | +| `Uses:` | shared briefs, comma-separated paths relative to this file, applied in order, this file last | +| `Mode:` `Angle:` `Hook:` `Refuses:` | the strategy's lines, kept in the graph for the critique | +| `Credit:` `Author:` `Draft date:` | kept, unused | +| `$name: value` | a variable. A value ending in .png, .jpg, .jpeg, .webp or .heic is a picture (its path relative to the space); anything else is text | + +LENGTH is `30 s`, `25 to 35 s` or `25-35 s`; a single length allows 15% either way. RATIO is `W:H`. PLATFORM is +tiktok, reels, instagram (reels' bands), shorts, youtube (shorts' bands) or omitted (the house bands). Any other key is +refused. + +## Body + +Each non-blank line is one element, chosen by how it starts: + +| starts with | element | +|---|---| +| `#` | a section: `# the crack`. Its name is the writer's own; more `#`s nest it | +| `=` | the section's synopsis: what the beat does for the viewer | +| `.` | a scene heading naming the take the lines below come from: `.TAKE03 - AT THE KILN` (the take's file name without its extension, then anything after ` - `). `.BROLL - TAKE01` names TAKE01 | +| `@` | a speaker: `@JUNE`, `@SHANE (V.O.)`. An all-capitals line under 40 characters not ending in `:` is a speaker too (Fountain's character cue) | +| `(` … `)` | delivery for the next line: `(flat, then laughing)` | +| `PUNCH IN 1.2X:` | zoom the next line 1.2 times. A bare `PUNCH IN:` is read and flagged by the compiler | +| `CUT TO:` `SMASH CUT TO:` `MATCH CUT TO:` `FADE IN:` `FADE OUT.` `PUNCH OUT:` | a transition; read and kept, not acted on | +| `>` … `<` | text on screen with no line under it | +| `//` | a comment: kept by fmt, read by nothing (also allowed above and among the title page's lines) | +| `~` | an open beat: a shot not yet bound to footage (below) | +| `!` | a check: a rule the edit must keep (below) | +| anything else, under a speaker | a line: words quoted exactly from the take. A line is a cut, so a word changed is a line no take says | + +Text that isn't under a speaker and starts with none of these is refused. A shot written as Fountain action +(`!Action The bracket clicks shut`, or a plain description) is refused with the open beat it should be: in the 110 +scripts the bench wrote in Fountain, `!` stood 157 times before a shot description and `@must { }` held the rules 50 +times, and score's reader dropped both silently. `raea-brief convert` turns them into `~` beats and `!` checks. + +### Notes on a line: `[[ ... ]]` + +`[[name prop:"value" prop:[a, b] prop:3 | utilities]]` after a line is a part timed to that line. `name` is a component +in the space's `components/` (or its parts kit); `component name:"x" ...` is the same spelled out; a note with no name +is utilities alone. Props are `key:"text"`, `key:[list]` or `key:number`. Utilities after `|`: + +- timing: `on:'words'`, `until:'words'`, `to-end`, `stagger-after:NAME` +- placement: `place-top`, `place-low`, `place-center`, `place-full`, `place-auto` +- motion: `enter-fade|rise|slide|pop|bounce`, `settle`, `exit-fade`, `dur-sm|md|lg`, `ease-standard|emphasized|decelerate|accelerate` +- punch-in: `punch-in:1.2` +- foley: `sfx:'prompt'`, `sfx-gain:-14` +- a claim: `claim:ID`, the line or part makes the claim `$claim.ID` declares (below) + +Anything else after `|` is refused at its column. A note on a synopsis or a section heading is refused (style goes in +the stylesheet). + +**Typed parts.** When the brief is compiled for a space (or parsed with `--space SPACE`), each part's props are +checked against its component's own TypeScript props (the type of `components/NAME.tsx`'s default export's +parameter, read by `@raea/data/props.ts`): a prop the component hasn't, a required one missing, a value of the +wrong kind (`big:90` where `big` is a string: `big:"90"`) or outside a string union (`region` is `auto`, `top`, +`bottom` or `center`) is refused where its line stands. Captions' `keys` is the compiler's own, not the component's. + +### Variables + +`$name` anywhere in a line, an open beat, a check or a note's props is replaced by its value; an undefined variable is +refused where it's used. A picture variable can only stand in an open beat's finds or a prop (the component gets the +path). + +### Deliverables and variants + +`{9:16}` or `{1:1, 4:5}` at the end of a line or an open beat keeps that element in those deliverables only. A ratio +no `Format:` names is refused. + +`{A}` (a name) at the end of a section heading makes the section one variant's: `# hook {A}` and `# hook {B}` are +two hooks for an experiment, and everything in a section without a name is in every variant. A line or beat can +carry its own name too. `raea-brief compile` makes every variant of every deliverable, `NAME-A-9x16.tsx`, +`NAME-B-1x1.tsx` and so on (`--variant A` makes one); coverage of a shared ask and the checks run per cut. A ratio on a +section heading is refused (a section takes a variant's name; deliverables tag lines and beats). + +``` +Title: Ferro oat milk, two hooks +Format: 9:16, 30 s, tiktok | 1:1, 15 s, instagram + +# hook {A} +@MAYA +I used to hate oat milk. + +# hook {B} +@MAYA +Nobody warned me about oat milk. + +# proof +@MAYA +It's creamy, and it's 90 calories. {9:16} +``` + +### Alternatives + +`first read || second read` on a line gives the compiler alternatives. Before it places anything it picks, for +each such line, a read the transcripts don't flag (no stutter, no rehearsal talk, not cut off mid-sentence, not an +early read of a line said again) that brings the running total nearest the middle of the length the Format allows; +the sheet says which read it took and why the others lost. Every alternative is quoted word for word, like a line. + +``` +Title: Colitt, the first look +Format: 9:16, 12 s + +# hook +@DAD +There he is. || See the bass? +``` + +### Claims + +`$claim.ID: "what it says" source "where it's proven"` on the title page (here, or in a shared brief this uses) +declares a claim; the source may wait, and `! claims sourced` says so. A line or part says it makes the claim with +the utility `claim:ID`; an ID no brief declares is refused. `! claims sourced` fails at compile time and on the render +for a claim with no source, with the frames where it's said or shown. + +``` +Title: Alpha Lion, the safety claim +Format: 9:16, 20 s +$claim.gras: "GRAS verified" source "GRAS notice GRN-1234" + +! claims sourced + +# proof +@SHAWN +Making it a safe choice for you and it's GRAS verified. [[statcard big:"270+" | claim:gras]] +``` + +### Open beats: `~` + +`~ KIND: PHRASE [find: FIND ...]` is a shot the plan wants that no line pins down yet. KIND is to-camera, b-roll, +product, screen or end-card (raea-beats' kinds). PHRASE says what happens, in words SigLIP and the critique can read. +FINDs are perception facts, each one of: + +| find | reads | +|---|---| +| `face` `speech` `text` `screen` | detected (faces.json tracks, VAD and speaking, read-text, layout's screen zone) | +| `hands` `place` | partly detected (the hands command; scene labels) | +| `product` `logo` `action` | SigLIP on PHRASE only (ingest has no object detector) | +| `$picture` | the picture searched against frames (product, logo) | +| `people:N` | N faces in shot | +| `speaking` `eye-contact` `still` `moving` `bright` `no-text` | performance, motion, light and read-text facts | +| `framing:close-up\|medium\|wide` | shot framing | + +The compiler binds each open beat to a span of footage, or names it in the sheet as weak or missing (with how it was +matched: by a fact, or by a SigLIP score against FIND_THRESHOLD). How (score/compiler/moments.py): + +- every take with picture is read from its ingest (`raea-perceive ingest`, once per take): a moment is one SigLIP frame + (8 a second) with the facts true then +- the beat's detected finds filter the moments; among those that pass, the phrase's SigLIP score (or the picture's) + ranks them; a span grows from each peak while the finds hold and the score stays within 0.03 of the peak, 1.5 to 4 s +- b-roll, product and screen beats that don't ask for speech prefer moments where nobody is talking +- a span the edit already keeps isn't bound again +- the best span is **covered** at FIND_THRESHOLD (0.10) or more, **weak** at 0.06 or more (both are cut into the + edit, in the beat's place), **missing** below (the sheet says what to do: record the screen, reshoot the creator, + or find stock); an `end-card` beat is a part, not footage +- a picture is matched image against frame at 0.70, a threshold no labelled set has calibrated + +### Checks: `!` + +`! RULE` is kept by the edit and answered pass or fail in the sheet. RULE is one of: + +- `never says "WORDS"`: no kept line says WORDS +- `the hook reads within half a second`, `nothing covers the face`, `captions read on a phone`, `everything inside the + safe zone`, `ends on a word, never mid-word`, `no black frames`, `the length is within the format` +- `FACT -> FACT`: whenever the first perception fact holds in the render, so does the second (`speaking -> face`) +- `claims sourced`: every claim a line or part makes (`claim:ID`) has a source +- `no shot longer than N s`, `the hook ends by N s`, `a cut at least every N s` (a cut, or new text on screen) + +A must may drop its "the", and the length may be given in seconds (`length within 30 s`); `never says` takes several +phrases. Anything else is refused. Checks add up across `Uses:`; none can be removed. + +**On the render.** The compiler answers what it can before anything renders (what the lines say, the length, the +hook's end, the claims). `raea-brief check NAME SPACE` answers every rule on the rendered video: it loads the piece's +facts as tables in `@raea/data` (its graph, the words as cut, the render manifest `NAME.render.json` with each frame's +text and video boxes, faces read back from the rendered frames twice a second, and perception's moments of the +takes on screen) and evaluates each rule as a query over them: + +| rule | on the render | +|---|---| +| the hook reads within half a second | text on screen, or a word said, before 0.5 s | +| nothing covers the face | the text on each face, all of it, under 8% of the face (faces read back from the render) | +| captions read on a phone | every text at least 2.5% of the frame's height | +| everything inside the safe zone | every text inside the platforms' safe rows and the frame | +| ends on a word, never mid-word | no word runs through a cut or the end | +| no black frames | ffmpeg's blackdetect | +| the length is within the format | the render's length against the deliverable's | +| never says | the words as cut | +| FACT -> FACT | at each read-back frame: face and people:N from the render; speaking, speech from the words; text, no-text from the manifest; eye-contact, framing, still, moving, bright, screen from the moment on screen; product, logo, action, hands, place by SigLIP on it | +| claims sourced | the claims made, and where an unsourced one is said or shown | +| pacing | shots from the manifest (where the source or its time jumps); the hook's end from the timeline | + +It prints a PASS, FAIL or NOT MEASURED line a rule, writes `NAME.check.json`, and exits 0 when every rule passes, 1 on +a fail, 2 when there's no render to check. `--battery` adds a standard set to the piece's own rules (the seven musts, +`speaking -> face`, `claims sourced`, `no shot longer than 6 s`, `a cut at least every 4 s`). + +## Stylesheet + +After `---`, CSS rules: `SELECTOR { property: value; ... }`. + +| selector | properties | +|---|---| +| `:root` | `background`, `music` (a prompt), `music-gain`, `sfx-gain`, `platform`, `eyes` (the eye line, a percentage) | +| `captions` | `place`, `keys` | + +`music` without `music-gain` isn't added, and nor is foley without a gain. Any other selector or property is refused at +its column (an `@must { }` block becomes `!` lines). + +## The graph + +`raea-brief parse FILE` prints: + +``` +{ "file", "kind": "piece"|"shared", "title", "format", "deliverables": [{ratio, secs: [lo, hi], platforms}], + "uses": [path], "meta": {Mode, Angle, ...}, "vars": {name: {value, picture}}, + "sections": [{name, depth, synopsis, at}], + "items": [ {"type": "line", section, take, speaker, delivery, punch, text, notes: [{kind, props, utils, anchor}], variants, at} + | {"type": "beat", section, kind, phrase, find: [..], variants, at} + | {"type": "screen", section, text, notes, at} + | {"type": "transition", text, at} ], + "checks": [{rule, form, args, at}], "style": {selector: {property: value}} } +``` + +`at` is `[line, col]`. On a refusal it prints nothing on stdout and every refusal on stderr, and exits 2. +`raea-brief fmt FILE` prints the file back in one canonical layout; parsing what it prints gives the same graph. +`asks` are the open beats of the shared briefs this one `Uses:`, each with the file it came from. + +## Compiling + +`raea-brief compile FILE SPACE [--o OUT] [--cut RATIO] [--no-sound]` (what `raea script` runs) compiles a piece through +score's SDK backend to `SPACE/NAME.tsx`, an @raea/motion composition, with `NAME.words.json`, `NAME.perception.json` +(the speaker's face per 4 fps sample, from the takes' ingest) and `NAME.checks.json` beside it (`edit.tsx` keeps the +plain names). A piece with several deliverables compiles each to `NAME-9x16.tsx`, `NAME-1x1.tsx` unless `--cut` or +`--o` picks one. It prints the COMPILED line and the sheet: every line and bound beat timed, the total against the +Format and what would bring it inside, open beats with how they were bound, and each check pass, fail or left for +the render. `raea-brief compile --all SPACE` compiles every piece, then answers each shared brief's beats against the +footage each piece cut. `raea-brief convert SCRIPT.fountain` writes a score script as a .brief. + +## Ink + +A piece can also be written in [ink](https://github.com/inkle/ink), inkle's narrative scripting language, in the raea +profile below. `raea-brief` compiles and runs it with blade-ink (Rust; inkjs is the TypeScript runtime), along the +choices `--path 0,1` names (the first choice where the path runs out), and reads what it plays as the .brief it is: +every reading and refusal above holds, and the graph the compiler gets is the same (`raea-brief lower STORY.ink` +prints that .brief; `raea-brief ink FILE.brief` writes a .brief as ink). Ink's own VAR, LIST, conditionals, +interpolation (`{product}`), knots, diverts and choices work as ink has them: the compiler sees what the story plays. + +```ink +# title: Pottery studio: the bowl that cracked +# format: 9:16, 20 s, tiktok | 1:1, 15 s, instagram +# check: never says "game changer" +# music: "sparse marimba, warm room tone" +# music-gain: -24 +VAR hours = "forty" + +-> the_crack + +=== the_crack === +JUNE (flat, then laughing): That's {hours} hours, gone. #section: the crack #take:TAKE03 #part:label text:"40 hours" | on:'forty hours' enter-fade place-top +-> why + +=== why === +JUNE: The wall was thinner on one side, and the kiln found it. #take:TAKE01 #punch:1.15 +>> b-roll: the cracked bowl turned in two hands #find:hands still +* [the fix] -> the_fix +* [the lesson] -> the_lesson + +=== the_fix === +JUNE: So this one's getting a thicker foot. #part:captions keys:"thicker" | place-low +-> END + +=== the_lesson === +JUNE: Every crack tells you where the clay was thin. #only:1:1 +-> END +``` + +| ink | the .brief it plays | +|---|---| +| `# title:` `# format:` `# uses:` `# angle:` `# hook:` `# mode:` `# refuses:` `# $name:` | the title page | +| `# check: RULE` (or `~ check("RULE")` from story logic) | `! RULE` | +| `# music:` `# music-gain:` `# sfx-gain:` `# platform:` `# background:` `# eyes:` `# captions-place:` `# captions-keys:` | the stylesheet (ink reads `{...}` in a tag as logic, so there's no CSS in a tag) | +| `=== knot ===`, `#section: name`, `#synopsis: ...` | `# name` (the knot's own name without a `#section`), `= ...` | +| `SPEAKER: words` / `SPEAKER (delivery): words` | `@SPEAKER`, `(delivery)`, the line | +| `#take:TAKE01` (holds until the next) | `.TAKE01` | +| `#part:NAME props \| utilities` (as many as the line has) | `[[NAME props \| utilities]]` | +| `#punch:1.15` / `#punch:` | `PUNCH IN 1.15X:` / `PUNCH IN:` | +| `#only:1:1` | `{1:1}` | +| `>> KIND: what is shown #find:...` (or `~ beat(...)` from story logic, played between lines) | `~ KIND: ... [find: ...]` | +| `>TEXT<` | `>TEXT<` | +| `_` with tags | a line that only carries its tags (a section with nothing in it yet) | + +In a tag, `#`, `{` and `}` are written `#`, `{`, `}`; in spoken words, ink's own marks are escaped +with `\` (the converter does both). Ink collapses a run of spaces in text to one. diff --git a/brief/src/bin/raea-brief.rs b/brief/src/bin/raea-brief.rs new file mode 100644 index 00000000..0a3e4b8b --- /dev/null +++ b/brief/src/bin/raea-brief.rs @@ -0,0 +1,189 @@ +//! raea-brief: the .brief format (format.md) read, written back, converted from a score script, and compiled. +//! +//! raea-brief parse FILE [--space SPACE] the intent graph as JSON; refusals on stderr as FILE:line:col, exit 2 +//! (with --space, its parts checked against the space's components' props) +//! raea-brief fmt FILE FILE in one layout +//! raea-brief convert SCRIPT.fountain a score script as a .brief +//! raea-brief ink FILE.brief a .brief as an ink story in the raea profile +//! raea-brief lower STORY.ink [--path 0,1] an ink story as the .brief its path plays (parse and compile take .ink too) +//! raea-brief compile FILE SPACE [--o OUT] [--cut RATIO] [--variant NAME] [--no-sound] +//! the piece compiled to an @raea/motion composition (OUT, default +//! SPACE/NAME.tsx) by score's SDK backend; the COMPILED line and the sheet +//! raea-brief check NAME SPACE [--video PATH] NAME's `!` rules on its render (@raea/data/check.ts): a PASS/FAIL line a +//! rule, NAME.check.json; exit 0 all pass, 1 a fail, 2 can't check +//! raea-brief compile --all SPACE every piece in SPACE (each *.brief with a Format:), then each shared +//! brief's beats against the footage the pieces cut (score/cover.py) + +use raea_brief::{convert, fmt, graph, load, load_text, parse, Loaded, Refusal}; +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitCode}; + +fn refuse(file: &Path, bad: &[Refusal]) -> ExitCode { + for r in bad { + if r.line == 0 || r.msg.contains(".brief:") || r.msg.starts_with('/') { + eprintln!("{}", r.msg); + } else { + eprintln!("{}:{}:{}: {}", file.display(), r.line, r.col, r.msg); + } + } + ExitCode::from(2) +} + +fn path_flag() -> Vec { + let a: Vec = std::env::args().collect(); + a.iter().position(|x| x == "--path").and_then(|i| a.get(i + 1)).map(|p| p.split(',').filter_map(|x| x.trim().parse().ok()).collect()).unwrap_or_default() +} + +fn graph_of(file: &Path) -> Result { + let mut docs: Vec = Vec::new(); + if file.extension().is_some_and(|x| x == "ink") { + // an ink story: run along --path and lowered to .brief (raea_brief::ink), then read as a .brief is + let src = std::fs::read_to_string(file).map_err(|e| { eprintln!("{}: {e}", file.display()); ExitCode::from(2) })?; + let (text, _) = raea_brief::ink::lower(&src, &path_flag()).map_err(|b| refuse(file, &b))?; + return load_text(file, Some(&text), &mut Vec::new(), &mut docs).and_then(|_| graph(&docs)).map_err(|b| { + let lines: Vec<&str> = text.lines().collect(); + for r in &b { + let what = lines.get(r.line.wrapping_sub(1)).map(|l| format!(" (the story plays `{}`)", l.trim())).unwrap_or_default(); + eprintln!("{}: {}{what}", file.display(), r.msg.rsplit_once(".ink:").map(|x| x.1).unwrap_or(&r.msg)); + } + ExitCode::from(2) + }); + } + load(file, &mut Vec::new(), &mut docs).map_err(|b| refuse(file, &b))?; + graph(&docs).map_err(|b| refuse(file, &b)) +} + +/// the space's components' props, as TypeScript types them (@raea/data/props.ts; RAEA_DATA overrides where it is) +fn props_of(space: &Path) -> Option { + let data = std::env::var("RAEA_DATA").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("raea/data")); + if !space.join("components").exists() { return None; } + let out = Command::new("bun").arg(data.join("src/props.ts")).arg(space).output().ok()?; + serde_json::from_slice(&out.stdout).ok() +} + +/// the graph's parts against the space's components: their refusals, or none +fn typed(file: &Path, g: &serde_json::Value, space: &Path) -> Result<(), ExitCode> { + match props_of(space) { + Some(schema) => { let bad = raea_brief::check_props(g, &schema); if bad.is_empty() { Ok(()) } else { Err(refuse(file, &bad)) } } + None => Ok(()), + } +} + +fn compile(file: &Path, space: &Path, out: Option, cut: Option) -> ExitCode { + let g = match graph_of(file) { Ok(g) => g, Err(c) => return c }; + if let Err(c) = typed(file, &g, space) { return c; } + if g["kind"] != "piece" { + eprintln!("{}: a shared brief (no Format:): nothing to compile; a piece uses it with `Uses:`", file.display()); + return ExitCode::from(2); + } + let work = space.join(".score"); + let _ = std::fs::create_dir_all(&work); + let stem = file.file_stem().unwrap().to_string_lossy().to_string(); + let gpath = work.join(format!("{stem}.graph.json")); + std::fs::write(&gpath, serde_json::to_string_pretty(&g).unwrap()).unwrap(); + // every variant (`# hook {A}`) of every deliverable, unless --variant, --cut or --o picks: NAME-A-9x16.tsx and so on, + // a name part left out where there's only one of it + let ratios: Vec = g["deliverables"].as_array().map(|d| d.iter().filter_map(|x| x["ratio"].as_str().map(String::from)).collect()).unwrap_or_default(); + let names: Vec = g["variant_names"].as_array().map(|d| d.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default(); + let want_variant = std::env::args().collect::>().windows(2).find(|w| w[0] == "--variant").map(|w| w[1].clone()); + let vs: Vec> = match &want_variant { Some(v) => vec![Some(v.clone())], None if names.is_empty() => vec![None], None => names.iter().cloned().map(Some).collect() }; + let rs: Vec> = match &cut { Some(c) => vec![Some(c.clone())], None if ratios.len() > 1 => ratios.iter().cloned().map(Some).collect(), None => vec![None] }; + if out.is_some() || (vs.len() == 1 && rs.len() == 1) { + let o = out.unwrap_or_else(|| space.join(format!("{stem}{}{}.tsx", vs[0].as_ref().map(|v| format!("-{v}")).unwrap_or_default(), rs[0].as_ref().filter(|_| ratios.len() > 1 && cut.is_none()).map(|r| format!("-{}", r.replace(':', "x"))).unwrap_or_default()))); + return run(file, space, &gpath, &o, rs[0].clone(), vs[0].clone(), &work); + } + let mut worst = ExitCode::SUCCESS; + for v in &vs { + for r in &rs { + let name = format!("{stem}{}{}", v.as_ref().map(|v| format!("-{v}")).unwrap_or_default(), r.as_ref().filter(|_| ratios.len() > 1).map(|r| format!("-{}", r.replace(':', "x"))).unwrap_or_default()); + println!("-- {name}"); + let c = run(file, space, &gpath, &space.join(format!("{name}.tsx")), r.clone(), v.clone(), &work); + if c != ExitCode::SUCCESS { worst = c; } + } + } + worst +} + +fn run(file: &Path, space: &Path, gpath: &Path, out: &Path, cut: Option, variant: Option, work: &Path) -> ExitCode { + let ostem = out.file_stem().unwrap().to_string_lossy().to_string(); + // each piece compiled has its graph under its own name (raea check finds a brief's piece by .score/NAME.graph.json) + let own = work.join(format!("{ostem}.graph.json")); + if own != gpath { let _ = std::fs::copy(gpath, &own); } + let scorec = std::env::var("RAEA_SCOREC").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("raea/score/scorec.py")); + let mut cmd = Command::new("uv"); + cmd.args(["run", "-q", "python"]).arg(&scorec).arg(space).arg(file).arg("--graph").arg(gpath).args(["--target", "sdk", "--o"]).arg(out) + .arg("--json").arg(work.join(format!("{ostem}.ir.json"))); + if let Some(c) = cut { cmd.args(["--cut", &c]); } + if let Some(v) = variant { cmd.args(["--variant", &v]); } + if std::env::args().any(|a| a == "--no-sound") { cmd.arg("--no-sound"); } + match cmd.status() { + Ok(s) => ExitCode::from(s.code().unwrap_or(1) as u8), + Err(e) => { eprintln!("scorec: {e}"); ExitCode::from(1) } + } +} + +fn main() -> ExitCode { + let a: Vec = std::env::args().skip(1).collect(); + let flag = |k: &str| a.iter().position(|x| x == k).and_then(|i| a.get(i + 1)).cloned(); + match a.first().map(String::as_str) { + Some("parse") if a.len() > 1 => match graph_of(Path::new(&a[1])) { + Ok(g) => { + // --space SPACE: its components' props checked too + if let Some(sp) = flag("--space") { if let Err(c) = typed(Path::new(&a[1]), &g, Path::new(&sp)) { return c; } } + println!("{}", serde_json::to_string_pretty(&g).unwrap()); ExitCode::SUCCESS + } + Err(c) => c, + }, + Some("check") if a.len() > 2 => { + // the piece's `!` rules on its render, through @raea/data (data/src/check.ts): PASS/FAIL a rule, NAME.check.json + let data = std::env::var("RAEA_DATA").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("raea/data")); + let mut cmd = Command::new("bun"); + cmd.arg(data.join("src/check.ts")).arg(&a[1]).arg(&a[2]); + if let Some(v) = flag("--video") { cmd.args(["--video", &v]); } + if a.iter().any(|x| x == "--battery") { cmd.arg("--battery"); } + match cmd.status() { Ok(s) => ExitCode::from(s.code().unwrap_or(2) as u8), Err(e) => { eprintln!("bun: {e}"); ExitCode::from(2) } } + } + Some("lower") if a.len() > 1 => match std::fs::read_to_string(&a[1]).map_err(|e| vec![Refusal { line: 0, col: 0, msg: e.to_string() }]).and_then(|t| raea_brief::ink::lower(&t, &path_flag())) { + Ok((text, _)) => { print!("{text}"); ExitCode::SUCCESS } + Err(b) => refuse(Path::new(&a[1]), &b), + }, + Some("ink") if a.len() > 1 => match std::fs::read_to_string(&a[1]).map_err(|e| vec![Refusal { line: 0, col: 0, msg: e.to_string() }]).and_then(|t| parse(&t)) { + Ok(d) => { print!("{}", raea_brief::ink::from_brief(&d)); ExitCode::SUCCESS } + Err(b) => refuse(Path::new(&a[1]), &b), + }, + Some("fmt") if a.len() > 1 => { + let p = Path::new(&a[1]); + match std::fs::read_to_string(p).map_err(|e| e.to_string()).and_then(|t| parse(&t).map_err(|b| { refuse(p, &b); String::new() })) { + Ok(d) => { print!("{}", fmt(&d)); ExitCode::SUCCESS } + Err(e) => { if !e.is_empty() { eprintln!("{}: {e}", p.display()); } ExitCode::from(2) } + } + } + Some("convert") if a.len() > 1 => match std::fs::read_to_string(&a[1]) { + Ok(t) => { print!("{}", convert(&t)); ExitCode::SUCCESS } + Err(e) => { eprintln!("{}: {e}", a[1]); ExitCode::from(2) } + }, + Some("compile") if a.get(1).map(String::as_str) == Some("--all") && a.len() > 2 => { + let space = PathBuf::from(&a[2]); + let mut pieces: Vec = std::fs::read_dir(&space).map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "brief")).collect()).unwrap_or_default(); + pieces.sort(); + pieces.retain(|p| std::fs::read_to_string(p).ok().and_then(|t| parse(&t).ok()).is_none_or(|d| d.title.iter().any(|(k, _, _)| k == "Format"))); + if pieces.is_empty() { eprintln!("{}: no piece (a .brief with a Format:) to compile", space.display()); return ExitCode::from(2); } + let mut worst = ExitCode::SUCCESS; + for p in &pieces { + println!("== {}", p.file_name().unwrap().to_string_lossy()); + let c = compile(p, &space, None, None); + if c != ExitCode::SUCCESS { worst = c; } + } + // the shared asks against what the pieces cut (score/cover.py) + let cover = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("raea/score/cover.py"); + println!("== coverage"); + let _ = Command::new("uv").args(["run", "-q", "python"]).arg(&cover).arg(&space).status(); + worst + } + Some("compile") if a.len() > 2 => compile(Path::new(&a[1]), Path::new(&a[2]), flag("--o").map(PathBuf::from), flag("--cut")), + _ => { + eprintln!("raea-brief parse FILE [--space SPACE] | fmt FILE | convert SCRIPT.fountain | ink FILE.brief | lower STORY.ink | compile FILE SPACE [--o OUT] [--cut RATIO] [--variant NAME] | compile --all SPACE | check NAME SPACE [--video PATH]"); + ExitCode::from(2) + } + } +} diff --git a/brief/src/format.rs b/brief/src/format.rs new file mode 100644 index 00000000..66092d09 --- /dev/null +++ b/brief/src/format.rs @@ -0,0 +1,933 @@ +//! The .brief format (format.md): a Fountain profile with one reading for every line, read into the intent graph. +//! +//! parse the text into a Doc (each element as written, with where it stands), or every refusal +//! graph a Doc, with its `Uses:` applied and its variables filled in, as the JSON the compiler reads +//! fmt a Doc back as text, in one layout (parse(fmt(d)) reads the same as d) +//! convert a score script (script.fountain, read as score/compiler/front.py reads it) as a .brief: what the +//! notation defines kept, Fountain action as open beats, @must as checks, and whatever neither reads +//! kept as `//` comments, so nothing the writer wrote is lost + +pub mod ink; + +use regex::Regex; +use serde_json::{json, Map, Value}; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; + +pub const KINDS: [&str; 5] = ["to-camera", "b-roll", "product", "screen", "end-card"]; +pub const FINDS: [&str; 9] = ["face", "speech", "product", "hands", "screen", "text", "place", "action", "logo"]; +/// facts of a moment a find or a check can test, beyond the nine words (performance, motion, light, read-text) +const FACTS: [&str; 6] = ["speaking", "eye-contact", "still", "moving", "bright", "no-text"]; +pub const MUSTS: [&str; 7] = ["the hook reads within half a second", "nothing covers the face", "captions read on a phone", + "everything inside the safe zone", "ends on a word, never mid-word", "no black frames", "the length is within the format"]; +const META: [&str; 7] = ["Mode", "Angle", "Hook", "Refuses", "Credit", "Author", "Draft date"]; +const PICTURE: [&str; 5] = [".png", ".jpg", ".jpeg", ".webp", ".heic"]; +/// the stylesheet the compiler reads (score/compiler/sheet.py CSS_PROPS, by selector) +const STYLE: [(&str, &[&str]); 2] = [(":root", &["background", "music", "music-gain", "sfx-gain", "platform", "eyes"]), ("captions", &["place", "keys"])]; + +macro_rules! re { + ($name:ident, $pat:expr) => { + static $name: LazyLock = LazyLock::new(|| Regex::new($pat).unwrap()); + }; +} +// a utility the compiler implements (score/compiler/front.py UTIL) +re!(UTIL, r"^(on:'(?:[^']|'\w)+'|until:'(?:[^']|'\w)+'|to-end|place-(top|low|center|full|auto)|punch-in:\d+(\.\d+)?|enter-(fade|rise|slide|pop|bounce)|exit-fade|settle|dur-(sm|md|lg)|ease-(standard|emphasized|decelerate|accelerate)|stagger-after:\w+|sfx:'(?:[^']|'\w)+'|sfx-gain:-?\d+(\.\d+)?|claim:\w+)$"); +re!(TOK, r"[\w-]+:'(?:[^']|'\w)*'|\S+"); +re!(NOTE_PART, r#"^\s*([A-Za-z_][\w-]*)((?:\s+\w+:(?:"[^"]*"|\[[^\]]*\]|-?\d+(?:\.\d+)?))*)\s*(\|(.*))?$"#); +re!(PROP, r#"(\w+):("[^"]*"|\[[^\]]*\]|-?\d+(?:\.\d+)?)"#); +re!(NOTE, r"\[\[(.*?)\]\]"); +re!(VARIANT, r"\s*\{\s*((?:\d+:\d+|[A-Za-z]\w*)(?:\s*,\s*(?:\d+:\d+|[A-Za-z]\w*))*)\s*\}\s*$"); +re!(KEY, r"^(\$[A-Za-z_][\w.]*|[A-Z][A-Za-z ]*):\s*(.*)$"); +re!(CLAIM, r#"^"([^"]+)"(?:\s+source\s+"([^"]+)")?$"#); +re!(PACE, r"(?i)^(no shot longer than|the hook ends by|a cut at least every)\s+(\d+(?:\.\d+)?)\s*s(?:ec(?:ond)?s?)?$"); +re!(PUNCH, r"(?i)^PUNCH IN(?:\s+(\d+(?:\.\d+)?)X?)?[:.]?$"); +re!(TRANSITION, r"^(CUT TO|SMASH CUT TO|MATCH CUT TO|PUNCH OUT|FADE OUT|FADE IN|[A-Z ]+ TO)[:.]?$"); +re!(CUE, r"^[A-Z][A-Z0-9 .'()-]+$"); +re!(BEAT, r"^~\s*([A-Za-z-]+)\s*:\s*(.*?)\s*(?:\[find:\s*([^\]]*)\])?\s*$"); +re!(VAR, r"\$([A-Za-z_]\w*)"); +re!(SECS, r"(?i)(\d+)(?:\s*(?:to|-)\s*(\d+))?\s*s(?:ec|econds?)?\b"); +re!(RATIO, r"(\d+):(\d+)"); +re!(NEVER, r#"^never says ((?:"[^"]+"[\s,]*(?:or\s+|and\s+)?)+)$"#); +re!(QUOTED, r#""([^"]+)""#); +re!(LENGTH, r"(?i)^(?:the )?length (?:is )?within (?:the format|(\d+(?:\.\d+)?) ?s(?:ec(?:ond)?s?)?)$"); +re!(FENCE, r"(?s)```[\w-]*\n(.*?)```"); + +#[derive(Debug, Clone)] +pub struct Refusal { + pub line: usize, + pub col: usize, + pub msg: String, +} + +#[derive(Debug, Clone, Default)] +pub struct Note { + pub kind: Option, + pub props: Vec<(String, String)>, + /// each prop as written: "string" ("..."), "number" or "array" ([...]), for the component's types + pub types: Vec<(String, &'static str)>, + pub utils: Vec, + pub raw: String, +} + +#[derive(Debug, Clone)] +pub enum El { + Section { depth: usize, name: String, variants: Vec }, + Synopsis(String), + Take { take: String, heading: String }, + Speaker(String), + Delivery(String), + Punch(Option), + Transition(String), + Screen { text: String, notes: Vec }, + Beat { kind: String, phrase: String, find: Vec, variants: Vec }, + Check { rule: String }, + Line { text: String, notes: Vec, variants: Vec }, + Comment(String), + Blank, +} + +#[derive(Debug, Clone, Default)] +pub struct Doc { + /// comments above and among the title page's lines, kept for fmt + pub head: Vec, + pub title: Vec<(String, String, usize)>, + pub body: Vec<(El, usize, usize)>, + pub style: Vec<(String, Vec<(String, String, usize, usize)>, usize)>, +} + +fn col_of(raw: &str) -> usize { + raw.chars().take_while(|c| c.is_whitespace()).count() + 1 +} + +/// char column (1-based) of byte offset `b` in `s` +fn ccol(s: &str, b: usize) -> usize { + s[..b.min(s.len())].chars().count() + 1 +} + +fn toks(s: &str) -> Vec { + TOK.find_iter(s).map(|m| m.as_str().to_string()).collect() +} + +pub fn strip_fence(t: &str) -> &str { + if t.trim_start().starts_with("```") { + if let Some(c) = FENCE.captures(t) { + return c.get(1).unwrap().as_str(); + } + } + t +} + +/// one `[[ ... ]]` (its inside, starting at char column `col` on line `ln`), as score/compiler/front.py parse_note +/// reads it; every utility the compiler doesn't implement refused at its column +fn note(inner: &str, ln: usize, col: usize, bad: &mut Vec) -> Note { + let mut n = Note { raw: inner.to_string(), ..Default::default() }; + // a prop's text left open reads everything after it as words: say that once, not each word it swallowed (the note is + // still read as score's reader read it, so convert keeps what that reader kept) + let open_quote = inner.matches('"').count() % 2 == 1; + if open_quote { + let at = inner.rfind('"').unwrap(); + bad.push(Refusal { line: ln, col: col + ccol(inner, at) - 1, msg: "a prop's \"...\" isn't closed: end its text with \" before the `|`".into() }); + } + let ts = toks(inner); + let first = ts.first().cloned().unwrap_or_default(); + let mut util_src = inner.to_string(); + let mut util_off = 0; + match NOTE_PART.captures(inner) { + Some(c) if !UTIL.is_match(&first) && first != "|" => { + let mut kind = c[1].to_string(); + let caps: Vec<_> = PROP.captures_iter(c.get(2).unwrap().as_str()).collect(); + n.types = caps.iter().map(|p| (p[1].to_string(), if p[2].starts_with('"') { "string" } else if p[2].starts_with('[') { "array" } else { "number" })).collect(); + let mut props: Vec<(String, String)> = caps.iter().map(|p| (p[1].to_string(), p[2].trim_matches('"').to_string())).collect(); + if kind == "component" { + match props.iter().position(|(k, _)| k == "name") { + Some(i) => kind = props.remove(i).1, + None => bad.push(Refusal { line: ln, col, msg: "`component` without name:\"...\": name the component".into() }), + } + } + n.kind = Some(kind); + n.props = props; + match c.get(4) { + Some(u) => { util_src = u.as_str().to_string(); util_off = u.start(); n.utils = toks(u.as_str()); } + None => { util_src.clear(); } + } + } + _ => n.utils = ts.into_iter().filter(|x| x != "|").collect(), + } + let mut from = 0; + for u in &n.utils { + let at = util_src[from..].find(u.as_str()).map(|i| i + from).unwrap_or(0); + from = at + u.len(); + if !UTIL.is_match(u) && !open_quote { + let hint = if n.kind.is_none() && !u.contains(':') && n.utils.first() == Some(u) { + format!("; a part is `[[{u} prop:\"...\" | utilities]]`") + } else { String::new() }; + bad.push(Refusal { line: ln, col: col + ccol(inner, util_off + at) - 1, msg: format!("`{u}` isn't a utility (timing, place-*, enter-*/exit-fade/settle, dur-*, ease-*, punch-in:N, sfx:'...', sfx-gain:N){hint}") }); + } + } + n +} + +/// a body line's notes and the text left, the notes refused where a note can't stand +fn notes_of(s: &str, ln: usize, col0: usize, bad: &mut Vec) -> (String, Vec) { + let mut ns = Vec::new(); + for c in NOTE.captures_iter(s) { + let m = c.get(1).unwrap(); + ns.push(note(m.as_str(), ln, col0 + ccol(s, m.start()) - 1, bad)); + } + if s.contains("[[") && !s.contains("]]") { + bad.push(Refusal { line: ln, col: col0 + ccol(s, s.find("[[").unwrap()) - 1, msg: "`[[` without `]]`".into() }); + } + (NOTE.replace_all(s, "").trim().to_string(), ns) +} + +fn variants_of(s: &str) -> (String, Vec) { + match VARIANT.captures(s) { + Some(c) => (s[..c.get(0).unwrap().start()].trim_end().to_string(), c[1].split(',').map(|x| x.trim().to_string()).collect()), + None => (s.to_string(), vec![]), + } +} + +fn find_ok(f: &str) -> bool { + FINDS.contains(&f) || FACTS.contains(&f) || f.starts_with('$') + || f.strip_prefix("people:").is_some_and(|n| n.parse::().is_ok() || n.split_once('-').is_some_and(|(a, b)| a.parse::().is_ok() && b.parse::().is_ok())) + || f.strip_prefix("framing:").is_some_and(|x| ["close-up", "medium", "wide"].contains(&x)) +} + +fn check_form(rule: &str) -> Option<(String, Vec)> { + let r = rule.trim().trim_end_matches('.'); + if let Some(c) = NEVER.captures(r) { + return Some(("never-says".into(), QUOTED.captures_iter(&c[1]).map(|q| q[1].to_string()).collect())); + } + // a must as listed, with or without its "the"; the length also as `length within 30 s` + let bare = |x: &str| x.trim_start_matches("the ").to_lowercase(); + if let Some(m) = MUSTS.iter().find(|m| bare(r) == bare(m)) { + return Some(("must".into(), vec![m.to_string()])); + } + if let Some(c) = LENGTH.captures(r) { + return Some(("must".into(), [MUSTS[6].to_string()].into_iter().chain(c.get(1).map(|x| x.as_str().to_string())).collect())); + } + if bare(r) == "claims sourced" || bare(r) == "every claim has a source" { + return Some(("claims".into(), vec![])); + } + if let Some(c) = PACE.captures(r) { + let form = match c[1].to_lowercase().as_str() { "no shot longer than" => "max-shot", "the hook ends by" => "hook-by", _ => "cut-every" }; + return Some((form.into(), vec![c[2].to_string()])); + } + if let Some((a, b)) = r.split_once("->") { + let (a, b) = (a.trim(), b.trim()); + if find_ok(a) && find_ok(b) && !a.starts_with('$') && !b.starts_with('$') { + return Some(("implies".into(), vec![a.into(), b.into()])); + } + } + None +} + +/// the text as a Doc, or every refusal in it +pub fn parse(text: &str) -> Result> { + let text = strip_fence(text); + let lines: Vec<&str> = text.lines().collect(); + let split = lines.iter().position(|l| l.trim_end() == "---").unwrap_or(lines.len()); + let mut doc = Doc::default(); + let mut bad = Vec::new(); + // the title page: Key: value lines from the top to the first blank line + let mut i = 0; + while i < split && lines[i].trim().is_empty() { i += 1; } + while i < split { + let l = lines[i].trim(); + if l.is_empty() && !doc.title.is_empty() { break; } + if l.is_empty() || l.starts_with("//") { + if let Some(c) = l.strip_prefix("//") { doc.head.push(c.trim().to_string()); } + i += 1; + continue; + } + let Some(c) = KEY.captures(l) else { break }; + let (k, v) = (c[1].to_string(), c[2].trim().to_string()); + if !(k.starts_with('$') || ["Title", "Format", "Uses"].contains(&k.as_str()) || META.contains(&k.as_str())) { + bad.push(Refusal { line: i + 1, col: col_of(lines[i]), msg: format!("`{k}:` isn't a title-page key (Title, Format, Uses, Mode, Angle, Hook, Refuses, Credit, Author, Draft date, or a $variable)") }); + } + doc.title.push((k, v, i + 1)); + i += 1; + } + let mut speaker = false; + let mut pending_delivery: Option<(El, usize, usize)> = None; + for (j, raw) in lines.iter().enumerate().take(split).skip(i) { + let ln = j + 1; + let col = col_of(raw); + let l = raw.trim(); + let el = if l.is_empty() { + speaker = false; + El::Blank + } else if let Some(c) = l.strip_prefix("//") { + El::Comment(c.trim().to_string()) + } else if l.starts_with('#') { + let depth = l.chars().take_while(|&c| c == '#').count(); + let (name, vs) = variants_of(l[depth..].trim()); + if name.contains("[[") { bad.push(Refusal { line: ln, col, msg: "a note can't stand on a section heading: style goes in the stylesheet".into() }); } + if name.is_empty() { bad.push(Refusal { line: ln, col, msg: "a section needs a name".into() }); } + if vs.iter().any(|v| RATIO.is_match(v)) { bad.push(Refusal { line: ln, col, msg: "a deliverable ({1:1}) tags lines and beats; a section heading takes a variant's name ({A})".into() }); } + speaker = false; + El::Section { depth, name, variants: vs } + } else if let Some(s) = l.strip_prefix('=') { + if s.contains("[[") { bad.push(Refusal { line: ln, col: col + l.find("[[").unwrap(), msg: "a note can't stand on a synopsis: style goes in the stylesheet".into() }); } + El::Synopsis(NOTE.replace_all(s, "").trim().to_string()) + } else if l.starts_with('.') && l[1..].starts_with(|c: char| c.is_alphanumeric() || c == '_') { + let head = l[1..].to_string(); + let name: String = head.chars().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '-').collect(); + let take = if name.eq_ignore_ascii_case("BROLL") { + Regex::new(r"-\s*(\w+)").unwrap().captures(&head).map(|c| c[1].to_string()).unwrap_or_default() + } else { name }; + if take.is_empty() { bad.push(Refusal { line: ln, col, msg: "a scene heading names a take: `.TAKE02 - TALKING HEAD`".into() }); } + El::Take { take, heading: head } + } else if let Some(c) = PUNCH.captures(l) { + El::Punch(c.get(1).map(|m| m.as_str().parse().unwrap())) + } else if TRANSITION.is_match(l) { + El::Transition(l.to_string()) + } else if l.starts_with('@') || (CUE.is_match(l) && l.len() < 40 && !l.ends_with(':')) { + speaker = true; + El::Speaker(l.trim_start_matches('@').to_string()) + } else if l.starts_with('(') && l.ends_with(')') { + El::Delivery(l[1..l.len() - 1].to_string()) + } else if l.starts_with('~') { + match BEAT.captures(l) { + Some(c) if KINDS.contains(&c[1].to_lowercase().as_str()) && !c[2].is_empty() => { + let (phrase, vs) = variants_of(&c[2]); + let find: Vec = c.get(3).map(|f| f.as_str().split([',', ' ']).filter(|x| !x.is_empty()).map(String::from).collect()).unwrap_or_default(); + for f in &find { + if !find_ok(f) { + bad.push(Refusal { line: ln, col: col + l.find(f.as_str()).unwrap_or(0), msg: format!("`{f}` isn't a find: face, speech, product, hands, screen, text, place, action, logo, people:N, speaking, eye-contact, still, moving, bright, no-text, framing:close-up|medium|wide, or a $picture") }); + } + } + El::Beat { kind: c[1].to_lowercase(), phrase, find, variants: vs } + } + Some(c) if !KINDS.contains(&c[1].to_lowercase().as_str()) => { + bad.push(Refusal { line: ln, col: col + 1, msg: format!("`{}` isn't a beat's kind: to-camera, b-roll, product, screen or end-card", &c[1]) }); + El::Blank + } + _ => { + bad.push(Refusal { line: ln, col, msg: "an open beat is `~ KIND: what happens [find: ...]`".into() }); + El::Blank + } + } + } else if l.starts_with('>') && NOTE.replace_all(l, "").trim().ends_with('<') { + let (t, ns) = notes_of(l, ln, col, &mut bad); + El::Screen { text: t[1..t.len() - 1].trim().to_string(), notes: ns } + } else if let Some(r) = l.strip_prefix('!') { + let rule = r.trim(); + if check_form(rule).is_none() { + let hint = if rule.starts_with("Action") || rule.contains("[[") || rule.split_whitespace().count() > 4 && !rule.contains("->") { + format!("; a shot to find is an open beat: `~ b-roll: {}`", NOTE.replace_all(rule.trim_start_matches("Action").trim_start_matches(':').trim(), "").trim()) + } else { String::new() }; + let rule = NOTE.replace_all(rule, "").trim().to_string(); + bad.push(Refusal { line: ln, col: col + 1, msg: format!("`! {rule}` isn't a check: `never says \"...\"`, one of the musts ({}), or FACT -> FACT{hint}", MUSTS.join("; ")) }); + } + El::Check { rule: rule.to_string() } + } else if speaker { + let (t, ns) = notes_of(l, ln, col, &mut bad); + let (t, vs) = variants_of(&t); + if t.is_empty() { + // a note alone on its line: the line before it in this speaker's block takes it + match doc.body.iter_mut().rev().take_while(|(e, _, _)| !matches!(e, El::Blank | El::Section { .. })).find(|(e, _, _)| matches!(e, El::Line { .. })) { + Some((El::Line { notes, .. }, _, _)) => { notes.extend(ns); continue; } + _ => { bad.push(Refusal { line: ln, col, msg: "a note stands after the line it's on, and there's no line before it".into() }); } + } + } + El::Line { text: t, notes: ns, variants: vs } + } else { + let desc = NOTE.replace_all(l, ""); + bad.push(Refusal { line: ln, col, msg: format!("text that isn't under a speaker: put @SPEAKER before a quoted line, or write a shot as `~ b-roll: {}`", desc.trim()) }); + El::Blank + }; + // a delivery written just before its speaker (`(measured)` then `@MAYA`) is that speaker's: held until the + // speaker comes, refused if anything else does + if let El::Delivery(_) = &el { + if !speaker { + if let Some((_, pl, pc)) = pending_delivery.take() { bad.push(Refusal { line: pl, col: pc, msg: "delivery stands under a speaker".into() }); } + pending_delivery = Some((el, ln, col)); + continue; + } + } + if let Some((d, pl, pc)) = pending_delivery.take() { + if let El::Speaker(_) = &el { + doc.body.push((el, ln, col)); + doc.body.push((d, pl, pc)); + continue; + } + bad.push(Refusal { line: pl, col: pc, msg: "delivery stands under a speaker (or just before one)".into() }); + } + if matches!(el, El::Line { .. }) && !speaker { + bad.push(Refusal { line: ln, col, msg: "delivery stands under a speaker".into() }); + } + doc.body.push((el, ln, col)); + } + // the stylesheet: SELECTOR { property: value; ... }, only what the compiler reads + if split < lines.len() { + let css: String = lines[split + 1..].join("\n"); + let base = split + 2; + let rule = Regex::new(r"([^{}]+)\{([^}]*)\}").unwrap(); + let mut last = 0; + for c in rule.captures_iter(&css) { + let m0 = c.get(0).unwrap(); + let gap = css[last..m0.start()].trim(); + let pos = |b: usize| (base + css[..b].matches('\n').count(), b - css[..b].rfind('\n').map(|x| x + 1).unwrap_or(0) + 1); + if !gap.is_empty() { let (l, cc) = pos(last); bad.push(Refusal { line: l, col: cc, msg: format!("`{gap}` isn't a stylesheet rule") }); } + last = m0.end(); + let sel = c[1].trim().to_string(); + let sm = c.get(1).unwrap(); + let (sl, sc) = pos(sm.start() + (sm.as_str().len() - sm.as_str().trim_start().len())); + let props = STYLE.iter().find(|(s, _)| *s == sel).map(|(_, p)| *p); + if sel == "@must" { + bad.push(Refusal { line: sl, col: sc, msg: "`@must` rules are `!` lines in the body: `! nothing covers the face`".into() }); + continue; + } else if props.is_none() { + bad.push(Refusal { line: sl, col: sc, msg: format!("`{sel}` isn't a selector the compiler reads (:root, captions); a part styles itself in its component") }); + } + let body = c.get(2).unwrap(); + let mut decls = Vec::new(); + let mut off = body.start(); + for d in body.as_str().split(';') { + let lead = d.len() - d.trim_start().len(); + let (dl, dc) = pos(off + lead); + off += d.len() + 1; + let d = d.trim(); + if d.is_empty() { continue; } + match d.split_once(':') { + Some((k, v)) => { + let k = k.trim(); + if props.is_some_and(|p| !p.contains(&k)) { + bad.push(Refusal { line: dl, col: dc, msg: format!("`{k}` isn't a property of {sel} the compiler reads ({})", props.unwrap().join(", ")) }); + } + decls.push((k.to_string(), v.trim().to_string(), dl, dc)); + } + None => bad.push(Refusal { line: dl, col: dc, msg: format!("`{d}` isn't `property: value`") }), + } + } + doc.style.push((sel, decls, sl)); + } + let rest = css[last..].trim(); + if !rest.is_empty() { + let b = css.rfind(rest).unwrap_or(0); + bad.push(Refusal { line: base + css[..b].matches('\n').count(), col: 1, msg: format!("`{}` isn't a stylesheet rule", rest.lines().next().unwrap_or("")) }); + } + } + if bad.is_empty() { Ok(doc) } else { Err(bad) } +} + +pub fn format_secs(f: &str) -> Option<(f64, f64)> { + let c = SECS.captures(f)?; + let a: f64 = c[1].parse().ok()?; + Some(match c.get(2) { Some(b) => (a, b.as_str().parse().ok()?), None => (a * 0.85, a * 1.15) }) +} + +fn platforms(f: &str) -> Vec<&'static str> { + let f = f.to_lowercase(); + ["tiktok", "reels", "shorts"].into_iter() + .filter(|p| f.contains(p) || (*p == "reels" && f.contains("instagram")) || (*p == "shorts" && f.contains("youtube"))).collect() +} + +fn title<'a>(d: &'a Doc, k: &str) -> Option<&'a str> { + d.title.iter().find(|(x, _, _)| x == k).map(|(_, v, _)| v.as_str()) +} + +pub struct Loaded { + pub file: PathBuf, + pub doc: Doc, +} + +/// a .brief and every brief its `Uses:` names, depth first, each once; a cycle or a file that won't read refused +pub fn load(file: &Path, seen: &mut Vec, out: &mut Vec) -> Result<(), Vec> { + load_text(file, None, seen, out) +} + +/// `load`, with the file's text given (an ink story lowered to .brief, ink::lower) instead of read from disk +pub fn load_text(file: &Path, given: Option<&str>, seen: &mut Vec, out: &mut Vec) -> Result<(), Vec> { + let file = file.canonicalize().map_err(|e| vec![Refusal { line: 0, col: 0, msg: format!("{}: {e}", file.display()) }])?; + if seen.contains(&file) { + return Err(vec![Refusal { line: 0, col: 0, msg: format!("`Uses:` comes back to {}", file.display()) }]); + } + if out.iter().any(|l| l.file == file) { return Ok(()); } + let text = match given { Some(t) => t.to_string(), None => std::fs::read_to_string(&file).map_err(|e| vec![Refusal { line: 0, col: 0, msg: format!("{}: {e}", file.display()) }])? }; + let doc = parse(&text).map_err(|bad| bad.into_iter().map(|r| Refusal { msg: format!("{}:{}:{}: {}", file.display(), r.line, r.col, r.msg), ..r }).collect::>())?; + seen.push(file.clone()); + if let Some((_, uses, ln)) = doc.title.iter().find(|(k, _, _)| k == "Uses") { + for u in uses.split(',').map(str::trim).filter(|u| !u.is_empty()) { + let p = file.parent().unwrap().join(u); + if !p.exists() { + return Err(vec![Refusal { line: *ln, col: 1, msg: format!("{}:{ln}:1: `Uses: {u}`: no such brief", file.display()) }]); + } + load(&p, seen, out)?; + if let Some(l) = out.iter().find(|l| l.file == p.canonicalize().unwrap()) { + if title(&l.doc, "Format").is_some() { + return Err(vec![Refusal { line: *ln, col: 1, msg: format!("{}:{ln}:1: `Uses: {u}` names a piece (it has a Format:); a piece can only use shared briefs", file.display()) }]); + } + } + } + } + seen.pop(); + out.push(Loaded { file, doc }); + Ok(()) +} + +fn note_json(n: &Note, fill: &dyn Fn(&str) -> String) -> Value { + let anchor = n.utils.iter().find_map(|u| u.strip_prefix("on:'").map(|x| x.trim_end_matches('\'').to_string())); + let props: Map = n.props.iter().map(|(k, v)| (k.clone(), Value::String(fill(v)))).collect(); + let types: Map = n.types.iter().map(|(k, t)| (k.clone(), json!(t))).collect(); + json!({"kind": n.kind, "props": props, "types": types, "utils": n.utils, "anchor": anchor}) +} + +/// a graph's parts against the space's components (their props as TypeScript types them, @raea/data/props.ts): +/// an unknown prop, a missing required one, a value of the wrong kind or outside a string union, each refused where its +/// line stands. Props the compiler reads itself (captions' keys) aren't the component's. +pub fn check_props(g: &Value, schema: &Value) -> Vec { + let mut bad = Vec::new(); + for it in g["items"].as_array().into_iter().flatten() { + let (ln, col) = (it["at"][0].as_u64().unwrap_or(0) as usize, it["at"][1].as_u64().unwrap_or(1) as usize); + for n in it["notes"].as_array().into_iter().flatten() { + let Some(kind) = n["kind"].as_str() else { continue }; + let Some(props) = schema.get(kind).and_then(|p| p.as_object()) else { continue }; + let given = n["props"].as_object().cloned().unwrap_or_default(); + let names: Vec<&str> = props.keys().map(|k| k.as_str()).collect(); + for (k, v) in &given { + if kind == "captions" && k == "keys" { continue; } + let Some(p) = props.get(k) else { + bad.push(Refusal { line: ln, col, msg: format!("`{k}` isn't a prop of {kind} (its props: {})", names.join(", ")) }); + continue; + }; + let want = p["kind"].as_str().unwrap_or("any"); + let got = n["types"][k].as_str().unwrap_or("string"); + let fits = match want { "any" | "object" => true, "boolean" => got == "string" && matches!(v.as_str(), Some("true" | "false")) || got == "number", w => w == got }; + if !fits { + let how = match want { "string" => format!("{k}:\"{}\"", v.as_str().unwrap_or("")), "number" => format!("{k}:{}", v.as_str().unwrap_or("0")), "array" => format!("{k}:[...]"), _ => format!("{k}:\"true\"") }; + bad.push(Refusal { line: ln, col, msg: format!("{kind}'s {k} is a {want}, written as a {got}: {how}") }); + } else if let Some(vals) = p["values"].as_array() { + let vs: Vec<&str> = vals.iter().filter_map(|x| x.as_str()).collect(); + if !vs.contains(&v.as_str().unwrap_or("")) { + bad.push(Refusal { line: ln, col, msg: format!("{kind}'s {k} is one of {}, not \"{}\"", vs.join(", "), v.as_str().unwrap_or("")) }); + } + } + } + for (k, p) in props { + if p["required"].as_bool() == Some(true) && !given.contains_key(k) { + bad.push(Refusal { line: ln, col, msg: format!("{kind} needs {k} (a {}): {kind} {k}:\"...\"", p["kind"].as_str().unwrap_or("value")) }); + } + } + } + } + bad +} + +/// the graph of the last of `docs` (a piece or a shared brief), the ones before it the briefs it uses, in order +pub fn graph(docs: &[Loaded]) -> Result> { + let me = docs.last().unwrap(); + let d = &me.doc; + let mut bad = Vec::new(); + // variables: each used brief's in order, this one's last; a later value wins + let mut vars: Vec<(String, String)> = Vec::new(); + for l in docs { + for (k, v, _) in l.doc.title.iter().filter(|(k, _, _)| k.starts_with('$') && !k.starts_with("$claim.")) { + vars.retain(|(x, _)| x != &k[1..]); + vars.push((k[1..].to_string(), v.clone())); + } + } + // claims: `$claim.ID: "what it says" source "where it's proven"`, each used brief's in order, this one's last + let mut claims = Map::new(); + for l in docs { + for (k, v, ln) in l.doc.title.iter().filter(|(k, _, _)| k.starts_with("$claim.")) { + match CLAIM.captures(v.trim()) { + Some(c) => { claims.insert(k["$claim.".len()..].to_string(), json!({"text": &c[1], "source": c.get(2).map(|x| x.as_str()), "from": l.file})); } + None => bad.push(Refusal { line: *ln, col: 1, msg: format!("a claim is `{k}: \"what it says\" source \"where it's proven\"` (the source may wait, and `! claims sourced` will say so)") }), + } + } + } + let is_pic = |v: &str| PICTURE.iter().any(|e| v.to_lowercase().ends_with(e)); + let value = |name: &str| vars.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone()); + let undefined = std::cell::RefCell::new(Vec::::new()); + let fill = |s: &str| -> String { + VAR.replace_all(s, |c: ®ex::Captures| match value(&c[1]) { + Some(v) => v, + None => { undefined.borrow_mut().push(c[1].to_string()); c[0].to_string() } + }).to_string() + }; + let format = title(d, "Format").map(String::from); + let deliverables: Vec = format.as_deref().map(|f| f.split('|').map(|x| { + let x = x.trim(); + json!({"format": x, "ratio": RATIO.captures(x).map(|c| format!("{}:{}", &c[1], &c[2])), "secs": format_secs(x).map(|(a, b)| vec![a, b]), "platforms": platforms(x)}) + }).collect()).unwrap_or_default(); + let ratios: Vec = deliverables.iter().filter_map(|x| x["ratio"].as_str().map(String::from)).collect(); + let mut sections = Vec::new(); + let mut items = Vec::new(); + let (mut section, mut take, mut speaker, mut delivery): (Option, Option, Option, Option) = (None, None, None, None); + let mut punch = Value::Null; + let mut checks = Vec::new(); + for l in &docs[..docs.len() - 1] { + for (el, ln, _) in &l.doc.body { + if let El::Check { rule } = el { + let (form, args) = check_form(&fill(rule)).unwrap(); + checks.push(json!({"rule": fill(rule), "form": form, "args": args, "from": l.file, "at": [ln, 1]})); + } + } + } + let asks: Vec = docs[..docs.len() - 1].iter().flat_map(|l| l.doc.body.iter().filter_map(|(el, ln, _)| match el { + El::Beat { kind, phrase, find, .. } => Some(json!({"kind": kind, "phrase": fill(phrase), "find": find, "from": l.file, "at": [ln, 1]})), + _ => None, + })).collect(); + let tag_ok = |vs: &Vec, ln: usize, col: usize, bad: &mut Vec| { + for v in vs.iter().filter(|v| RATIO.is_match(v)) { + if !ratios.contains(v) { bad.push(Refusal { line: ln, col, msg: format!("{{{v}}}: no deliverable in Format: is {v} ({})", ratios.join(", ")) }); } + } + }; + // a tag is a deliverable (a ratio) or a variant's name; an element is in its own variants, else its section's + let split = |vs: &Vec| -> (Vec, Vec) { vs.iter().cloned().partition(|v| RATIO.is_match(v)) }; + let mut section_variants: Vec = Vec::new(); + let mut variant_names: Vec = Vec::new(); + let claim_refs = |notes: &Vec| -> Vec { notes.iter().flat_map(|n| n.utils.iter().filter_map(|u| u.strip_prefix("claim:").map(String::from))).collect() }; + for (el, ln, col) in &d.body { + let at = json!([ln, col]); + match el { + El::Blank => { speaker = None; delivery = None; } + El::Section { depth, name, variants } => { + section = Some(name.clone()); + section_variants = variants.clone(); + for v in variants { if !variant_names.contains(v) { variant_names.push(v.clone()); } } + sections.push(json!({"name": name, "depth": depth, "synopsis": Value::Null, "variant": variants, "at": at})); + } + El::Synopsis(s) => { if let Some(x) = sections.last_mut() { x["synopsis"] = json!(s); } } + El::Take { take: t, .. } => take = Some(t.clone()), + El::Speaker(s) => speaker = Some(s.clone()), + El::Delivery(s) => delivery = Some(s.clone()), + El::Punch(p) => punch = p.map(|x| json!(x)).unwrap_or(json!("unset")), + El::Transition(t) => items.push(json!({"type": "transition", "text": t, "at": at})), + El::Comment(_) => {} + El::Screen { text, notes } => items.push(json!({"type": "screen", "section": section, "text": fill(text), "notes": notes.iter().map(|n| note_json(n, &fill)).collect::>(), "at": at})), + El::Beat { kind, phrase, find, variants } => { + tag_ok(variants, *ln, *col, &mut bad); + for f in find.iter().filter(|f| f.starts_with('$')) { + match value(&f[1..]) { + Some(v) if is_pic(&v) => {} + Some(_) => bad.push(Refusal { line: *ln, col: *col, msg: format!("{f} is text, not a picture: a find takes a picture variable") }), + None => undefined.borrow_mut().push(f[1..].to_string()), + } + } + let find: Vec = find.iter().map(|f| if let Some(v) = f.strip_prefix('$') { json!({"picture": value(v)}) } else { json!(f) }).collect(); + let (only, names) = split(variants); + for v in &names { if !variant_names.contains(v) { variant_names.push(v.clone()); } } + let variant = if names.is_empty() { section_variants.clone() } else { names }; + items.push(json!({"type": "beat", "section": section, "take": take, "kind": kind, "phrase": fill(phrase), "find": find, "variants": only, "variant": variant, "at": at})); + } + El::Check { rule } => { + let r = fill(rule); + let (form, args) = check_form(&r).unwrap(); + checks.push(json!({"rule": r, "form": form, "args": args, "from": me.file, "at": at})); + } + El::Line { text, notes, variants } => { + tag_ok(variants, *ln, *col, &mut bad); + let (only, names) = split(variants); + for v in &names { if !variant_names.contains(v) { variant_names.push(v.clone()); } } + let variant = if names.is_empty() { section_variants.clone() } else { names }; + // `first read || second read`: alternatives the compiler picks from; `text` is the first + let alts: Vec = fill(text).split(" || ").map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).collect(); + let refs = claim_refs(notes); + for r in &refs { + if !claims.contains_key(r) { bad.push(Refusal { line: *ln, col: *col, msg: format!("claim:{r} isn't a claim (a `$claim.{r}: \"...\" source \"...\"` line on the title page, here or in a brief this uses)") }); } + } + items.push(json!({"type": "line", "section": section, "take": take, "speaker": speaker, "delivery": delivery, "punch": punch, + "text": alts.first().cloned().unwrap_or_default(), "alts": if alts.len() > 1 { json!(alts) } else { Value::Null }, + "notes": notes.iter().map(|n| note_json(n, &fill)).collect::>(), "claims": refs, "variants": only, "variant": variant, "at": at})); + punch = Value::Null; + } + } + for u in undefined.borrow_mut().drain(..) { + bad.push(Refusal { line: *ln, col: *col, msg: format!("${u} isn't defined (a `${u}: value` line on the title page, here or in a brief this uses)") }); + } + } + let mut style = Map::new(); + for (sel, decls, _) in &d.style { + let e = style.entry(sel.clone()).or_insert_with(|| json!({})); + for (k, v, _, _) in decls { e[k] = json!(fill(v)); } + } + for u in undefined.borrow_mut().drain(..) { + bad.push(Refusal { line: 0, col: 0, msg: format!("${u} isn't defined") }); + } + if !bad.is_empty() { return Err(bad); } + let meta: Map = d.title.iter().filter(|(k, _, _)| META.contains(&k.as_str())).map(|(k, v, _)| (k.clone(), json!(fill(v)))).collect(); + Ok(json!({ + "file": me.file, "kind": if format.is_some() { "piece" } else { "shared" }, + "title": title(d, "Title").map(|t| fill(t)), "format": format, "deliverables": deliverables, + "uses": docs[..docs.len() - 1].iter().map(|l| &l.file).collect::>(), "meta": meta, + "vars": vars.iter().map(|(k, v)| (k.clone(), json!({"value": v, "picture": is_pic(v)}))).collect::>(), + "sections": sections, "items": items, "checks": checks, "asks": asks, "style": style, "claims": claims, "variant_names": variant_names, + })) +} + +fn note_text(n: &Note) -> String { + let mut s = String::new(); + if let Some(k) = &n.kind { + s.push_str(k); + for (p, v) in &n.props { + if v.starts_with('[') || v.parse::().is_ok() { s.push_str(&format!(" {p}:{v}")); } else { s.push_str(&format!(" {p}:\"{v}\"")); } + } + if !n.utils.is_empty() { s.push_str(" | "); } + } + s.push_str(&n.utils.join(" ")); + // a list prop last would close as `]]]`, which reads one bracket early + if s.ends_with(']') { s.push(' '); } + format!("[[{s}]]") +} + +fn tagged(s: String, vs: &[String]) -> String { + if vs.is_empty() { s } else { format!("{s} {{{}}}", vs.join(", ")) } +} + +/// the Doc as text in one layout: the title page, then the body with one blank line before each section and none +/// doubled, then the stylesheet one rule to a line +pub fn fmt(d: &Doc) -> String { + let mut out: Vec = d.head.iter().map(|c| format!("// {c}")).collect(); + out.extend(d.title.iter().map(|(k, v, _)| format!("{k}: {v}"))); + out.push(String::new()); + for (el, _, _) in &d.body { + let s = match el { + El::Blank => String::new(), + El::Comment(c) => format!("// {c}"), + El::Section { depth, name, variants } => { if out.last().is_some_and(|l| !l.is_empty()) { out.push(String::new()); } tagged(format!("{} {name}", "#".repeat(*depth)), variants) } + El::Synopsis(s) => format!("= {s}"), + El::Take { heading, .. } => format!(".{heading}"), + El::Speaker(s) => format!("@{s}"), + El::Delivery(s) => format!("({s})"), + El::Punch(p) => p.map(|x| format!("PUNCH IN {x}X:")).unwrap_or("PUNCH IN:".into()), + El::Transition(t) => t.clone(), + El::Screen { text, notes } => [format!(">{text}<")].into_iter().chain(notes.iter().map(note_text)).collect::>().join(" "), + El::Beat { kind, phrase, find, variants } => tagged(if find.is_empty() { format!("~ {kind}: {phrase}") } else { format!("~ {kind}: {phrase} [find: {}]", find.join(" ")) }, variants), + El::Check { rule } => format!("! {rule}"), + El::Line { text, notes, variants } => tagged([text.clone()].into_iter().chain(notes.iter().map(note_text)).collect::>().join(" "), variants), + }; + if s.is_empty() && out.last().is_some_and(|l| l.is_empty()) { continue; } + out.push(s); + } + while out.last().is_some_and(|l| l.is_empty()) { out.pop(); } + if !d.style.is_empty() { + out.push("---".into()); + for (sel, decls, _) in &d.style { + out.push(format!("{sel} {{ {} }}", decls.iter().map(|(k, v, _, _)| format!("{k}: {v};")).collect::>().join(" "))); + } + } + out.join("\n") + "\n" +} + +/// a score script (script.fountain) as a .brief. What the notation defines is kept as the compiler read it; Fountain +/// action (`!Action ...`, a description with no speaker) becomes an open beat; `@must { ... }` becomes `!` lines; +/// title keys, utilities, props and style the notation doesn't read become `//` comments beside where they stood +pub fn convert(fountain: &str) -> String { + // as front.py reads a model's answer: the first fenced block anywhere in it, else the text without a fence opened + // and never closed + let text = match FENCE.captures(fountain) { + Some(c) => c.get(1).unwrap().as_str(), + None => fountain.trim_start().strip_prefix("```").map(|t| t.split_once('\n').map(|x| x.1).unwrap_or("")).unwrap_or(fountain), + }; + let (body, css) = match text.split_once("\n---\n") { Some((a, b)) => (a, b), None => (text, "") }; + let mut out = Vec::new(); + let mut checks = Vec::new(); + let mut speaker = false; + let mut in_title = true; + let mut pending: Vec = Vec::new(); + let mut last_line: Option = None; + // what front.py reads from a note: the part and its props, its utilities; those it calls unknown go to a comment + let keep_note = |inner: &str, dropped: &mut Vec| -> String { + let mut bad = Vec::new(); + let n = note(inner, 0, 1, &mut bad); + let mut n2 = n.clone(); + n2.utils.retain(|u| UTIL.is_match(u)); + if n.utils.len() != n2.utils.len() { + dropped.push(format!("[[{}]] had {}", inner.trim(), n.utils.iter().filter(|u| !UTIL.is_match(u)).cloned().collect::>().join(" "))); + } + if n2.kind.is_none() && n2.utils.is_empty() { String::new() } else { note_text(&n2) } + }; + for raw in body.lines() { + let l = raw.trim(); + if in_title { + if l.is_empty() { if !out.is_empty() { in_title = false; out.push(String::new()); } continue; } + if let Some(c) = KEY.captures(l) { + let k = &c[1]; + if k.starts_with('$') || ["Title", "Format", "Uses"].contains(&k) || META.contains(&k) { out.push(l.to_string()); } else { out.push(format!("// {l}")); } + continue; + } + in_title = false; + out.push(String::new()); + } + if l.is_empty() { + speaker = false; + for p in pending.drain(..) { out.push(format!("// {p}")); } + out.push(String::new()); + continue; + } + let mut dropped = Vec::new(); + // a note left open (`[[... sfx-pop]`): front.py reads it as words of the line; it goes to a comment here + let l = &match (l.rfind("[["), l.rfind("]]")) { + (Some(o), c) if c.is_none_or(|c| c < o) => { dropped.push(format!("a note left open: {}", &l[o..])); l[..o].trim_end().to_string() } + _ => l.to_string(), + }; + let notes: Vec = NOTE.captures_iter(l).map(|c| keep_note(&c[1], &mut dropped)).filter(|s| !s.is_empty()).collect(); + let bare = NOTE.replace_all(l, "").trim().to_string(); + let with = |s: String, notes: &[String]| if notes.is_empty() { s } else { format!("{s} {}", notes.join(" ")) }; + if let Some(c) = KEY.captures(&bare).filter(|c| &c[1] == "Title" || &c[1] == "Format") { + out.push(format!("// {} (a title-page key in the body)", &c[0])); + } else if bare.starts_with('#') { + out.push(bare.clone()); + if !notes.is_empty() { dropped.push(format!("on the heading: {}", notes.join(" "))); } + speaker = false; + } else if bare.starts_with('=') { + out.push(bare.clone()); + if !notes.is_empty() { dropped.push(format!("on the synopsis: {}", notes.join(" "))); } + } else if bare.starts_with('.') && bare[1..].starts_with(|c: char| c.is_alphanumeric() || c == '_') { + out.push(bare.clone()); + } else if PUNCH.is_match(&bare) || TRANSITION.is_match(&bare) || bare.starts_with('@') || (CUE.is_match(&bare) && bare.len() < 40 && !bare.ends_with(':')) { + if bare.starts_with('@') || (CUE.is_match(&bare) && !PUNCH.is_match(&bare) && !TRANSITION.is_match(&bare)) { speaker = true; } + out.push(bare.clone()); + } else if bare.starts_with('(') && bare.ends_with(')') { + if speaker { out.push(bare.clone()); } else { out.push(format!("// {bare} (delivery with no speaker)")); } + } else if bare.starts_with('~') { + out.push(format!("// {l} (a lyric)")); + } else if bare.starts_with('>') && bare.ends_with('<') { + out.push(with(bare.clone(), ¬es)); + } else if speaker && !bare.starts_with('!') { + out.push(with(bare.clone(), ¬es)); + last_line = Some(out.len() - 1); + } else { + // Fountain action: a shot the writer wants, which no line says; front.py moved its notes to the line before + let desc = bare.trim_start_matches('!').trim_start_matches("Action").trim_start_matches(':').trim().replace(['[', ']'], ""); + if !notes.is_empty() { + match last_line { Some(i) => { out[i].push(' '); out[i].push_str(¬es.join(" ")); } None => dropped.push(format!("before any line: {}", notes.join(" "))) } + } + if !desc.is_empty() { out.push(format!("~ b-roll: {desc}")); } + } + for x in dropped { pending.push(format!("not in the notation: {x}")); } + if !speaker { for p in pending.drain(..) { out.push(format!("// {p}")); } } + } + for p in pending.drain(..) { out.push(format!("// {p}")); } + // the stylesheet: the selectors and properties the compiler reads; @must as checks; the rest as comments + let mut style = Vec::new(); + for c in Regex::new(r"([^{}]+)\{([^}]*)\}").unwrap().captures_iter(css) { + let sel = c[1].trim(); + let decls: Vec<&str> = c[2].split(';').map(str::trim).filter(|d| !d.is_empty()).collect(); + if sel == "@must" { + for d in decls { + match check_form(d) { Some(_) => checks.push(format!("! {d}")), None => checks.push(format!("// must: {d} (not a check the runtime has)")) } + } + continue; + } + let props = STYLE.iter().find(|(s, _)| *s == sel).map(|(_, p)| *p); + let (keep, drop): (Vec<&str>, Vec<&str>) = decls.into_iter().partition(|d| props.is_some_and(|p| d.split_once(':').is_some_and(|(k, _)| p.contains(&k.trim())))); + if !keep.is_empty() { style.push(format!("{sel} {{ {} }}", keep.iter().map(|d| format!("{d};")).collect::>().join(" "))); } + if !drop.is_empty() { style.push(format!("// {sel} {{ {} }} (not read by the compiler)", drop.join("; "))); } + } + // checks stand after the title page + let at = out.iter().position(|l| l.is_empty()).map(|i| i + 1).unwrap_or(out.len()); + if !checks.is_empty() { checks.push(String::new()); } + for (i, c) in checks.into_iter().enumerate() { out.insert(at + i, c); } + let mut s = out.join("\n"); + while s.contains("\n\n\n") { s = s.replace("\n\n\n", "\n\n"); } + let mut s = s.trim_end().to_string() + "\n"; + if !style.is_empty() { + // a comment can't stand in the stylesheet: move them above the --- + let (cm, rules): (Vec, Vec) = style.into_iter().partition(|x| x.starts_with("//")); + for c in cm { s.push_str(&c); s.push('\n'); } + if !rules.is_empty() { s.push_str("---\n"); s.push_str(&rules.join("\n")); s.push('\n'); } + } + s +} + +#[cfg(test)] +mod tests { + use super::*; + + fn refusals(t: &str) -> Vec { + parse(t).err().unwrap_or_default().into_iter().map(|r| format!("{}:{} {}", r.line, r.col, r.msg)).collect() + } + + #[test] + fn reads_the_example() { + let t = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/format.md")).unwrap(); + let ex = t.split("```\n").nth(1).unwrap(); + let d = parse(ex).unwrap_or_else(|e| panic!("{e:?}")); + let g = graph(&[Loaded { file: "x.brief".into(), doc: d.clone() }]).unwrap(); + assert_eq!(g["kind"], "piece"); + assert_eq!(g["deliverables"][1]["ratio"], "1:1"); + let lines: Vec<&Value> = g["items"].as_array().unwrap().iter().filter(|i| i["type"] == "line").collect(); + assert_eq!(lines[1]["text"], "Try Milky Jelly."); + assert_eq!(lines[1]["variants"][0], "9:16"); + assert_eq!(lines[0]["notes"][0]["kind"], "captions"); + let beat = g["items"].as_array().unwrap().iter().find(|i| i["type"] == "beat").unwrap(); + assert_eq!(beat["find"][0]["picture"], "media/milky-jelly.png"); + assert_eq!(g["checks"][0]["form"], "never-says"); + // fmt reads back the same + let again = parse(&fmt(&d)).unwrap(); + let g2 = graph(&[Loaded { file: "x.brief".into(), doc: again }]).unwrap(); + let strip = |mut g: Value| { for i in g["items"].as_array_mut().unwrap() { i["at"] = Value::Null; } for s in g["sections"].as_array_mut().unwrap() { s["at"] = Value::Null; } for c in g["checks"].as_array_mut().unwrap() { c["at"] = Value::Null; } g }; + assert_eq!(strip(g), strip(g2)); + } + + /// every fenced example in format.md that isn't ink or the graph's shape reads, with no refusal + #[test] + fn reads_every_example() { + let t = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/format.md")).unwrap(); + // fenced blocks: a line starting ``` opens one (its language after it), a line that is ``` closes it + let (mut blocks, mut cur): (Vec<(String, String)>, Option<(String, String)>) = (vec![], None); + for l in t.lines() { + match (&mut cur, l.strip_prefix("```")) { + (None, Some(lang)) => cur = Some((lang.trim().to_string(), String::new())), + (Some(_), Some(rest)) if rest.trim().is_empty() => blocks.push(cur.take().unwrap()), + (Some((_, body)), _) => { body.push_str(l); body.push('\n'); } + _ => {} + } + } + let mut n = 0; + for (lang, body) in &blocks { + if !lang.is_empty() || body.trim_start().starts_with('{') { continue; } + let d = parse(body).unwrap_or_else(|e| panic!("format.md example {}: {e:?}\n{body}", n + 1)); + graph(&[Loaded { file: "x.brief".into(), doc: d }]).unwrap_or_else(|e| panic!("format.md example {}: {e:?}", n + 1)); + n += 1; + } + assert!(n >= 4, "{n} examples"); + } + + #[test] + fn reads_the_ink_example() { + let t = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/format.md")).unwrap(); + let ex = t.split("```ink\n").nth(1).unwrap().split("```").next().unwrap(); + for (path, last) in [(vec![], "So this one's getting a thicker foot."), (vec![1], "Every crack tells you where the clay was thin.")] { + let (text, _) = crate::ink::lower(ex, &path).unwrap_or_else(|e| panic!("{e:?}")); + let d = parse(&text).unwrap_or_else(|e| panic!("{e:?}\n{text}")); + let g = graph(&[Loaded { file: "x.ink".into(), doc: d }]).unwrap(); + let lines: Vec<&Value> = g["items"].as_array().unwrap().iter().filter(|i| i["type"] == "line").collect(); + assert_eq!(lines[0]["text"], "That's forty hours, gone."); + assert_eq!(lines[0]["section"], "the crack"); + assert_eq!(lines.last().unwrap()["text"], last); + assert_eq!(g["checks"][0]["form"], "never-says"); + assert!(g["items"].as_array().unwrap().iter().any(|i| i["type"] == "beat")); + } + } + + #[test] + fn refuses_with_where() { + let r = refusals("Title: x\nFormat: 9:16, 20 s\n\n@JUNE\nHi there. [[lockup text:\"hi\" | on:'Hi' pops]]\n"); + assert_eq!(r.len(), 1); + assert!(r[0].starts_with("5:40 `pops`"), "{r:?}"); + let r = refusals("Title: x\nFormat: 9:16, 20 s\n\n!Action The bracket clicks shut [[follow | place-low]]\n"); + assert!(r[0].contains("~ b-roll: The bracket clicks shut"), "{r:?}"); + let r = refusals("Title: x\nBuild goal: y\n\n# a\n"); + assert!(r[0].starts_with("2:1 `Build goal:`"), "{r:?}"); + let r = refusals("Title: x\n\n# a\nJust words.\n"); + assert!(r[0].starts_with("4:1 text that isn't under a speaker"), "{r:?}"); + let r = refusals("Title: x\n\n# a\n\n---\n:root { music: \"x\"; energy: f; }\n@must { no black frames; }\n"); + assert_eq!(r.len(), 2, "{r:?}"); + assert!(r[0].starts_with("6:21 `energy`"), "{r:?}"); + assert!(r[1].starts_with("7:1 `@must`"), "{r:?}"); + let r = refusals("Title: x\n\n~ drone: over the hills\n~ b-roll: a pour [find: hands sparkle]\n"); + assert!(r[0].starts_with("3:2 `drone`") && r[1].contains("`sparkle` isn't a find"), "{r:?}"); + } + + #[test] + fn variables_and_variants() { + let d = parse("Title: x\nFormat: 9:16, 20 s\n\n@A\nTry $thing. {1:1}\n").unwrap(); + let e = graph(&[Loaded { file: "x".into(), doc: d }]).unwrap_err(); + assert!(e.iter().any(|r| r.msg.contains("$thing isn't defined")) && e.iter().any(|r| r.msg.contains("{1:1}")), "{e:?}"); + } +} diff --git a/brief/src/ink.rs b/brief/src/ink.rs new file mode 100644 index 00000000..95c9a7b0 --- /dev/null +++ b/brief/src/ink.rs @@ -0,0 +1,302 @@ +//! Ink as the brief's backbone (the founder, 2026-10-17: "lets do it with ink"): a story written in inkle's ink, compiled +//! and run by blade-ink (Rust; inkjs in TypeScript), lowered to .brief text and read by the .brief parser, so every +//! reading and refusal .brief has holds for ink, and the graph the compiler reads is the same. +//! +//! The raea profile of ink (format.md, "Ink"): +//! # title: ... / # format: ... / # uses: ... / # check: RULE the story's global tags +//! # music: "prompt" / # music-gain: -24 / # sfx-gain / # platform / # background / # eyes :root's stylesheet +//! # captions-place: low / # captions-keys: a, b captions' stylesheet +//! # angle: / # hook: / # mode: / # refuses: the strategy's lines +//! === knot === a section, named for the knot (or its `#section: name`); `#synopsis: ...` says what it does +//! SHAWN: the words, quoted a line: the speaker, then words said in a take; `SHAWN (warm): ...` gives delivery +//! #take:TAKE01 the take the lines from here on come from +//! #part:lockup text:"..." | ... a part on the line, in the .brief part notation; `#punch:1.15` zooms the line +//! #only:1:1 the line belongs to that deliverable only +//! >TEXT< text on screen with no line under it +//! >> product: what is shown #find:hands still an open beat, a line of its own (#take, #only as lines have them) +//! ~ beat("product", "what is shown", "hands still") the same from story logic (external function; played between lines) +//! ~ check("never says \"game changer\"") a check, wherever it reads best +//! * [hook A] / * [hook B] choices: `--path 0,1` picks each one; the first is played when none is given +//! Ink's VAR, LIST, conditionals and text interpolation work as ink has them: the lowering sees what the story plays. + +use crate::Refusal; +use bladeink::story::Story; +use bladeink::value_type::ValueType; +use std::cell::RefCell; +use std::rc::Rc; + +/// the external functions the profile gives a story; each becomes .brief text in the order it's played +const PRELUDE: &str = "EXTERNAL beat(kind, phrase, find)\nEXTERNAL check(rule)\n"; + +/// what a tag can't hold as itself in ink (`#` ends it, `{}` are logic), as the converter writes it and back +pub fn untag(t: &str) -> String { + t.replace("#", "#").replace("{", "{").replace("}", "}") +} + +fn entag(t: &str) -> String { + t.replace('#', "#").replace('{', "{").replace('}', "}") +} + +fn s(v: &ValueType) -> String { + match v { + ValueType::String(x) => x.string.clone(), + ValueType::Int(i) => i.to_string(), + ValueType::Float(f) => f.to_string(), + ValueType::Bool(b) => b.to_string(), + _ => String::new(), + } +} + +/// an ink story as .brief text along `path` (choice indices, the first choice where the path runs out); each brief line +/// carries the ink line it came from (0 where it came from a tag or a function), for refusals +pub fn lower(source: &str, path: &[usize]) -> Result<(String, Vec), Vec> { + let prelude_lines = PRELUDE.lines().count(); + // visit counts on every knot: a line's section is the knot whose count went up as it played (the story's path, read + // after a line, already points past it, and inside a choice it names the choice, not the knot it diverts to) + let opts = bladeink_compiler::CompilerOptions { count_all_visits: true, ..Default::default() }; + let knots: Vec = regex::Regex::new(r"(?m)^\s*={2,}\s*(\w+)").unwrap().captures_iter(source).map(|c| c[1].to_string()).filter(|k| k != "function").collect(); + let json = bladeink_compiler::Compiler::with_options(opts).compile(&format!("{PRELUDE}{source}")).map_err(|e| { + let msg = e.to_string(); + // ink says `:LINE:`; the profile's prelude moved every line down + let at = regex::Regex::new(r":(\d+):").unwrap(); + let line = at.captures(&msg).and_then(|c| c[1].parse::().ok()).map(|l| l.saturating_sub(prelude_lines)).unwrap_or(0); + vec![Refusal { line, col: 1, msg: format!("ink: {}", at.replace(&msg, "").trim()) }] + })?; + let mut story = Story::new(&json).map_err(|e| vec![Refusal { line: 0, col: 0, msg: format!("ink: {e}") }])?; + // what the functions are called with, in order, between the lines the story plays + let calls: Rc>> = Rc::new(RefCell::new(Vec::new())); + let c1 = calls.clone(); + story.bind_external_function("beat", move |_, args: &[ValueType]| { + let (kind, phrase, find) = (args.first().map(s).unwrap_or_default(), args.get(1).map(s).unwrap_or_default(), args.get(2).map(s).unwrap_or_default()); + c1.borrow_mut().push(if find.trim().is_empty() { format!("~ {kind}: {phrase}") } else { format!("~ {kind}: {phrase} [find: {find}]") }); + Ok(None) + }, false).map_err(|e| vec![Refusal { line: 0, col: 0, msg: format!("ink: {e}") }])?; + let c2 = calls.clone(); + story.bind_external_function("check", move |_, args: &[ValueType]| { + c2.borrow_mut().push(format!("! {}", args.first().map(s).unwrap_or_default())); + Ok(None) + }, false).map_err(|e| vec![Refusal { line: 0, col: 0, msg: format!("ink: {e}") }])?; + + let mut head: Vec = Vec::new(); + let mut css: Vec = Vec::new(); + let (mut root, mut caps): (Vec, Vec) = (Vec::new(), Vec::new()); + let mut checks: Vec = Vec::new(); + for t in story.get_global_tags().unwrap_or_default().iter().map(|t| untag(t)) { + let (k, v) = t.split_once(':').map(|(k, v)| (k.trim().to_lowercase(), v.trim().to_string())).unwrap_or((t.trim().to_lowercase(), String::new())); + match k.as_str() { + "title" | "format" | "uses" | "angle" | "hook" | "mode" | "refuses" => { + let key = if k == "uses" { "Uses".to_string() } else { format!("{}{}", k[..1].to_uppercase(), &k[1..]) }; + head.push(format!("{key}: {v}")); + } + "check" => checks.push(format!("! {v}")), + // the stylesheet as plain tags (ink reads `{...}` in a tag as logic): :root's and captions' properties + "music" | "music-gain" | "sfx-gain" | "platform" | "background" | "eyes" => root.push(format!("{k}: {v};")), + "captions-place" => caps.push(format!("place: {v};")), + "captions-keys" => caps.push(format!("keys: \"{}\";", v.trim_matches('"'))), + _ if k.starts_with('$') => head.push(format!("{k}: {v}")), + _ => head.push(format!("// tag not in the profile: {t}")), + } + } + if !root.is_empty() { css.push(format!(":root {{ {} }}", root.join(" "))); } + if !caps.is_empty() { css.push(format!("captions {{ {} }}", caps.join(" "))); } + let mut body: Vec<(String, usize)> = Vec::new(); + let (mut knot, mut take) = (String::new(), String::new()); + let mut counts: Vec = vec![0; knots.len()]; + let mut steps = path.iter(); + // SPEAKER: words, or SPEAKER (delivery): words; a name of up to four words, an extension in capitals (V.O.) its own + let line_re = regex::Regex::new(r"^([A-Za-z][\w.'-]*(?: [\w.'-]+){0,3}(?:\s*\([A-Z.' ]+\))?)(?:\s*\(([^)]*)\))?\s*:\s*(.+)$").unwrap(); + loop { + while story.can_continue() { + let text = story.cont().map_err(|e| vec![Refusal { line: 0, col: 0, msg: format!("ink: {e}") }])?; + for c in calls.borrow_mut().drain(..) { + body.push((c, 0)); + } + let tags: Vec = story.get_current_tags().unwrap_or_default().iter().map(|t| untag(t)).collect(); + let now: Vec = knots.iter().map(|k| story.get_visit_count_at_path_string(k).unwrap_or(0)).collect(); + if let Some(i) = (0..knots.len()).find(|&i| now[i] > counts.get(i).copied().unwrap_or(0)) { + if knots[i] != knot { + knot = knots[i].clone(); + body.push((String::new(), 0)); + // a section's own name (spaces and all) when the knot carries it; knot names are identifiers + let name = tags.iter().find_map(|t| t.strip_prefix("section:").map(|v| v.trim().to_string())).unwrap_or_else(|| knot.clone()); + let var = tags.iter().find_map(|t| t.strip_prefix("variant:").map(|v| format!(" {{{}}}", v.trim()))).unwrap_or_default(); + body.push((format!("# {name}{var}"), 0)); + } + } + counts = now; + let tag = |name: &str| tags.iter().find_map(|t| t.strip_prefix(&format!("{name}:")).map(|v| v.trim().to_string())); + if let Some(syn) = tag("synopsis") { + body.push((format!("= {syn}"), 0)); + } + if let Some(t) = tag("take") { + if t != take { + take = t.clone(); + body.push((format!(".{t}"), 0)); + } + } + let line = text.trim(); + // `_`: a line that only carries its tags (a section with nothing in it yet; an empty knot isn't ink) + if line.is_empty() || line == "_" { + continue; + } + // a list prop last would close as `]]]`, which reads one bracket early + let parts: String = tags.iter().filter_map(|t| t.strip_prefix("part:")).map(|p| { let p = p.trim(); format!(" [[{p}{}]]", if p.ends_with(']') { " " } else { "" }) }).collect(); + let only = tag("only").map(|r| format!(" {{{r}}}")).unwrap_or_default(); + if let Some(b) = line.strip_prefix(">>") { + // an open beat as a line: `>> KIND: what is shown #find:...`, in the order and the knot it's played + let find = tag("find").map(|f| format!(" [find: {f}]")).unwrap_or_default(); + body.push((format!("~ {}{find}{only}", b.trim()), 0)); + } else if line.starts_with('>') && line.ends_with('<') { + body.push((format!("{line}{parts}"), 0)); + } else if let Some(c) = line_re.captures(line) { + body.push((String::new(), 0)); + body.push((format!("@{}", c[1].trim()), 0)); + if let Some(d) = c.get(2) { + body.push((format!("({})", d.as_str()), 0)); + } + if let Some(p) = tag("punch") { + body.push((if p.is_empty() { "PUNCH IN:".to_string() } else { format!("PUNCH IN {p}X:") }, 0)); + } + body.push((format!("{}{parts}{only}", c[3].trim()), 0)); + } else { + // not a line: the .brief parser refuses it with what it should be + body.push((String::new(), 0)); + body.push((line.to_string(), 0)); + } + } + for c in calls.borrow_mut().drain(..) { + body.push((c, 0)); + } + let choices = story.get_current_choices(); + if choices.is_empty() { + break; + } + let i = steps.next().copied().unwrap_or(0); + if i >= choices.len() { + return Err(vec![Refusal { line: 0, col: 0, msg: format!("ink: --path asks for choice {i} where there are {} ({})", choices.len(), choices.iter().map(|c| c.text.as_str()).collect::>().join(" | ")) }]); + } + story.choose_choice_index(i).map_err(|e| vec![Refusal { line: 0, col: 0, msg: format!("ink: {e}") }])?; + } + let mut out: Vec<(String, usize)> = head.into_iter().map(|h| (h, 0)).collect(); + out.push((String::new(), 0)); + out.extend(checks.into_iter().map(|c| (c, 0))); + out.extend(body); + if !css.is_empty() { + out.push(("---".into(), 0)); + out.extend(css.into_iter().map(|c| (c, 0))); + } + // a section heading straight after another, or blanks doubled, read the same; keep the text tidy + let mut text = Vec::new(); + let mut map = Vec::new(); + for (l, src) in out { + if l.is_empty() && text.last().is_some_and(|p: &String| p.is_empty()) { + continue; + } + text.push(l); + map.push(src); + } + Ok((text.join("\n") + "\n", map)) +} + +/// ink's syntax in words a line quotes: escaped so they read as words +fn esc(t: &str) -> String { + let mut o = String::new(); + for (i, ch) in t.chars().enumerate() { + if matches!(ch, '{' | '}' | '#' | '\\') || (i == 0 && matches!(ch, '*' | '+' | '-' | '~' | '=')) { + o.push('\\'); + } + o.push(ch); + } + o.replace("//", "/\\/").replace("->", "-\\>").replace("<>", "<\\>") +} + +fn ident(name: &str, used: &mut Vec) -> String { + let mut k: String = name.to_lowercase().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect(); + k = k.trim_matches('_').to_string(); + if k.is_empty() || k.chars().next().unwrap().is_ascii_digit() { k = format!("s_{k}"); } + let base = k.clone(); + let mut n = 2; + while used.contains(&k) { k = format!("{base}_{n}"); n += 1; } + used.push(k.clone()); + k +} + +/// a .brief as an ink story in the raea profile: what `lower` reads back as the same .brief (the parity check) +pub fn from_brief(d: &crate::Doc) -> String { + use crate::El; + let mut out: Vec = Vec::new(); + for c in &d.head { out.push(format!("// {c}")); } + for (k, v, _) in &d.title { out.push(format!("# {}: {}", if k.starts_with('$') { k.clone() } else { k.to_lowercase() }, entag(v))); } + for (el, _, _) in &d.body { + if let El::Check { rule } = el { out.push(format!("# check: {}", entag(rule))); } + } + for (sel, decls, _) in &d.style { + for (k, v, _, _) in decls { + match sel.as_str() { + ":root" => out.push(format!("# {k}: {}", entag(v))), + "captions" => out.push(format!("# captions-{k}: {}", entag(v))), + _ => {} + } + } + } + // the knots, in order; a divert from one to the next + let mut used = Vec::new(); + let mut body: Vec = Vec::new(); + let (mut speaker, mut delivery, mut punch, mut take, mut pending): (Option, Option, Option, Option, Vec) = (None, None, None, None, Vec::new()); + let mut first: Option = None; + let mut sent_take: Option = None; + for (el, _, _) in &d.body { + match el { + El::Section { name, variants, .. } => { + let k = ident(name, &mut used); + // a section whose tags no line took (it holds nothing to play): a `_` line carries them + if !pending.is_empty() { body.push(format!("_{}", pending.drain(..).map(|t| format!(" #{}", entag(&t))).collect::())); } + // what comes before the first section plays first, then diverts into it + if first.is_none() { first = Some(k.clone()); } + body.push(format!("-> {k}")); + body.push(String::new()); + body.push(format!("=== {k} ===")); + pending.push(format!("section: {name}")); + if !variants.is_empty() { pending.push(format!("variant: {}", variants.join(", "))); } + speaker = None; delivery = None; + } + El::Synopsis(s_) => pending.push(format!("synopsis: {s_}")), + El::Take { take: t, .. } => take = Some(t.clone()), + El::Speaker(s_) => { speaker = Some(s_.clone()); delivery = None; } + El::Delivery(s_) => delivery = Some(s_.clone()), + El::Punch(p) => punch = p.or(Some(0.0)), + El::Blank => { speaker = None; delivery = None; } + El::Comment(c) => body.push(format!("// {c}")), + El::Transition(t) => body.push(format!("// {t}")), + El::Check { .. } => {} + El::Beat { kind, phrase, find, variants } => { + let mut tags = std::mem::take(&mut pending); + if take.is_some() && take != sent_take { tags.push(format!("take:{}", take.clone().unwrap())); sent_take = take.clone(); } + if !find.is_empty() { tags.push(format!("find:{}", find.join(" "))); } + if !variants.is_empty() { tags.push(format!("only:{}", variants.join(", "))); } + body.push(format!(">> {kind}: {}{}", esc(phrase), tags.iter().map(|t| format!(" #{}", entag(t))).collect::())); + } + El::Screen { text, notes } => { + let mut tags = std::mem::take(&mut pending); + tags.extend(notes.iter().map(|n| format!("part:{}", n.raw.trim()))); + body.push(format!(">{}<{}", esc(text), tags.iter().map(|t| format!(" #{}", entag(t))).collect::())); + } + El::Line { text, notes, variants } => { + let mut tags = std::mem::take(&mut pending); + if take.is_some() && take != sent_take { tags.push(format!("take:{}", take.clone().unwrap())); sent_take = take.clone(); } + if let Some(p) = punch.take() { tags.push(if p == 0.0 { "punch:".into() } else { format!("punch:{p}") }); } + tags.extend(notes.iter().map(|n| format!("part:{}", n.raw.trim()))); + if !variants.is_empty() { tags.push(format!("only:{}", variants.join(", "))); } + let who = speaker.clone().unwrap_or_else(|| "SPEAKER".into()); + let d_ = delivery.as_ref().map(|x| format!(" ({x})")).unwrap_or_default(); + body.push(format!("{who}{d_}: {}{}", esc(text), tags.iter().map(|t| format!(" #{}", entag(t))).collect::())); + } + } + } + if !pending.is_empty() { body.push(format!("_{}", pending.drain(..).map(|t| format!(" #{}", entag(&t))).collect::())); } + body.push("-> END".into()); + out.push(String::new()); + let _ = first; + out.extend(body); + out.join("\n") + "\n" +} diff --git a/brief/src/main.rs b/brief/src/main.rs new file mode 100644 index 00000000..f1808251 --- /dev/null +++ b/brief/src/main.rs @@ -0,0 +1,224 @@ +//! Track F1 (the roadmap): a brief split into beats, each a phrase, the kind of shot, what Perception should find +//! in the footage for it, and the words of the brief it comes from, written as rows (beats.json) that F2 looks up in +//! the source table. Splitting free text is the agent's job, so this asks the agent's own model (MiniMax-M3 through +//! raea's API, as the project Agent does), then checks what came back against the brief itself: +//! grounded: every beat quotes the brief (its `from` found in it, word for word up to case and spacing) +//! accounted: every unit of the brief (a line, a bullet, or a clause of free text) is used by a beat or set aside +//! with a reason (a date, a price, a rate: logistics no shot can show) +//! vocabulary: kinds and finds from the fixed lists F2 searches by +//! +//! raea-beats split BRIEF.md [-o BEATS.json] one brief +//! raea-beats grade DIR every *.md in DIR split and checked; a JSON summary +//! raea-beats brief BEATS.json [-o OUT.brief] the beats as a shared .brief (format.md): each beat an open beat, +//! its words and what it came from, and every unit set aside, as comments + +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +const MODEL: &str = "MiniMax-M3"; +const KINDS: [&str; 5] = ["to-camera", "b-roll", "product", "screen", "end-card"]; +const FINDS: [&str; 9] = ["face", "speech", "product", "hands", "screen", "text", "place", "action", "logo"]; + +/// A setting: the process environment first, then raea's settings file ($RAEA_ENV_FILE, else ~/.raea/env). +fn setting(name: &str) -> Option { + if let Some(v) = std::env::var(name).ok().filter(|v| !v.trim().is_empty()) { + return Some(v.trim().to_string()); + } + let file = std::env::var_os("RAEA_ENV_FILE").map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".raea/env")); + std::fs::read_to_string(file).ok()?.lines().find_map(|l| { + let (k, v) = l.trim().split_once('=')?; + (k.trim() == name && !l.trim_start().starts_with('#')).then(|| v.trim().trim_matches('"').to_string()) + }).filter(|v| !v.is_empty()) +} + +fn token() -> Result { + if let Some(t) = setting("RAEA_API_TOKEN") { + return Ok(t); + } + let api = setting("RAEA_API").ok_or("RAEA_API is not set (raea's API, in the environment or ~/.raea/env)")?; + let key = setting("RAEA_EVAL_KEY").ok_or("no RAEA_API_TOKEN and no RAEA_EVAL_KEY for raea's API")?; + let res = reqwest::blocking::Client::new().post(format!("{}/v1/dev/eval-session", api.trim_end_matches('/'))).header("x-eval-key", key).send().map_err(|e| e.to_string())?; + let body: Value = res.json().map_err(|e| e.to_string())?; + body["token"].as_str().map(String::from).ok_or_else(|| format!("eval-session answered {body}")) +} + +/// The brief's units: each non-empty line that isn't a heading, bullets on their own, and free text cut at sentence +/// ends, semicolons and commas (a call's notes run one ask into the next). +fn units(brief: &str) -> Vec { + let mut out = Vec::new(); + for l in brief.lines() { + let l = l.trim().trim_start_matches(['-', '*']).trim(); + if l.is_empty() || l.starts_with('#') { + continue; + } + // a full stop or comma ends a clause only before a space ("$3.49", "1,200" stay whole) + let cut = l.replace(". ", "\n").replace("; ", "\n").replace(", ", "\n"); + for part in cut.split('\n').map(|p| p.trim_end_matches(['.', ';', ','])) { + let p = part.trim(); + if p.split_whitespace().count() >= 2 { + out.push(p.to_string()); + } + } + } + out +} + +fn norm(s: &str) -> String { + s.to_lowercase().chars().map(|c| if c.is_alphanumeric() || c == '$' { c } else { ' ' }).collect::().split_whitespace().collect::>().join(" ") +} + +fn ask(token: &str, brief: &str) -> Result { + let units = units(brief); + let numbered: String = units.iter().enumerate().map(|(i, u)| format!("{}. {u}\n", i + 1)).collect(); + let prompt = format!(r#"You plan the shots of a short-form video from a brief. Split the brief into beats, in the order a viewer sees them. + +Each beat is one moment of the video: +- "phrase": what happens, in plain words (what is said or shown) +- "kind": one of {kinds} +- "find": what must be visible or audible in the footage for this beat, from {finds} (one or more) +- "said": the words spoken, if the brief gives them (else "") +- "from": the words of the brief this beat comes from, copied exactly (a phrase of the brief, not a paraphrase) +- "units": the numbers of the brief's units below that this beat uses + +Then list every unit no beat uses in "set_aside", each with a short reason (a launch date, a price, a deliverable count, an instruction to you). +Every unit is either in some beat's "units" or in "set_aside". + +Answer with JSON only: {{"beats": [...], "set_aside": [{{"unit": N, "reason": "..."}}]}} + +The brief: +{brief} + +Its units: +{numbered}"#, kinds = KINDS.join(", "), finds = FINDS.join(", ")); + let body = json!({"model": MODEL, "max_tokens": 4096, "messages": [{"role": "user", "content": prompt}]}); + let client = reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(180)).build().map_err(|e| e.to_string())?; + let api = setting("RAEA_API").ok_or("RAEA_API is not set (raea's API, in the environment or ~/.raea/env)")?; + let res = client.post(format!("{}/v1/ai/anthropic/v1/messages", api.trim_end_matches('/'))).header("x-api-key", token).header("anthropic-version", "2023-06-01") + .json(&body).send().map_err(|e| e.to_string())?; + let status = res.status(); + let v: Value = res.json().map_err(|e| e.to_string())?; + if !status.is_success() { + return Err(format!("{status}: {v}")); + } + let text: String = v["content"].as_array().map(|a| a.iter().filter_map(|c| c["text"].as_str()).collect()).unwrap_or_default(); + let start = text.find('{').ok_or("no JSON in the answer")?; + let end = text.rfind('}').ok_or("no JSON in the answer")?; + let mut out: Value = serde_json::from_str(&text[start..=end]).map_err(|e| format!("{e}: {}", &text[start..=end.min(start + 400)]))?; + out["units"] = json!(units); + out["model"] = json!(MODEL); + Ok(out) +} + +/// What came back, checked against the brief. +fn check(brief: &str, b: &Value) -> Value { + let n = norm(brief); + let units = b["units"].as_array().cloned().unwrap_or_default(); + let beats = b["beats"].as_array().cloned().unwrap_or_default(); + let grounded = beats.iter().filter(|x| x["from"].as_str().is_some_and(|f| !norm(f).is_empty() && n.contains(&norm(f)))).count(); + let vocab = beats.iter().filter(|x| { + KINDS.contains(&x["kind"].as_str().unwrap_or("")) && x["find"].as_array().is_some_and(|f| !f.is_empty() && f.iter().all(|q| FINDS.contains(&q.as_str().unwrap_or("")))) + }).count(); + let mut used = vec![false; units.len()]; + let mut aside = vec![false; units.len()]; + for x in &beats { + for u in x["units"].as_array().into_iter().flatten() { + if let Some(i) = u.as_u64().and_then(|i| (i as usize).checked_sub(1)).filter(|i| *i < units.len()) { + used[i] = true; + } + } + } + for s in b["set_aside"].as_array().into_iter().flatten() { + if let Some(i) = s["unit"].as_u64().and_then(|i| (i as usize).checked_sub(1)).filter(|i| *i < units.len()) { + aside[i] = true; + } + } + let accounted = (0..units.len()).filter(|&i| used[i] || aside[i]).count(); + json!({"beats": beats.len(), "grounded": grounded, "vocabulary": vocab, "units": units.len(), "accounted": accounted, + "used": used.iter().filter(|u| **u).count(), "set_aside": aside.iter().filter(|u| **u).count()}) +} + +/// a split brief as a shared .brief: the client's ask that pieces `Uses:` and are checked against (format.feature) +fn as_brief(name: &str, b: &Value) -> String { + let units = b["units"].as_array().cloned().unwrap_or_default(); + let unit = |i: &Value| i.as_u64().and_then(|i| units.get((i as usize).wrapping_sub(1))).and_then(|u| u.as_str()).unwrap_or("").to_string(); + let clean = |s: &str| s.replace(['[', ']'], "").replace('\n', " ").trim().to_string(); + let mut out = vec![format!("Title: {name}"), String::new(), + format!("// the client's ask, split into beats by raea-beats ({}); a piece made from it says `Uses: {name}.brief`", b["model"].as_str().unwrap_or("?")), String::new()]; + for x in b["beats"].as_array().into_iter().flatten() { + let find: Vec<&str> = x["find"].as_array().into_iter().flatten().filter_map(|f| f.as_str()).filter(|f| FINDS.contains(f)).collect(); + let kind = x["kind"].as_str().filter(|k| KINDS.contains(k)).unwrap_or("b-roll"); + let phrase = clean(x["phrase"].as_str().unwrap_or("")); + out.push(if find.is_empty() { format!("~ {kind}: {phrase}") } else { format!("~ {kind}: {phrase} [find: {}]", find.join(" ")) }); + if let Some(s) = x["said"].as_str().filter(|s| !s.trim().is_empty()) { out.push(format!("// says: \"{}\"", clean(s))); } + if let Some(f) = x["from"].as_str() { out.push(format!("// from the brief: \"{}\"", clean(f))); } + } + let aside: Vec = b["set_aside"].as_array().into_iter().flatten() + .map(|s| format!("// set aside: \"{}\" ({})", clean(&unit(&s["unit"])), clean(s["reason"].as_str().unwrap_or("")))).collect(); + if !aside.is_empty() { out.push(String::new()); out.extend(aside); } + out.join("\n") + "\n" +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some("brief") && args.len() >= 2 { + let b: Value = match std::fs::read_to_string(&args[1]).map_err(|e| e.to_string()).and_then(|t| serde_json::from_str(&t).map_err(|e| e.to_string())) { + Ok(b) => b, + Err(e) => { eprintln!("raea-beats: {}: {e}", args[1]); std::process::exit(2); } + }; + let name = Path::new(&args[1]).file_name().unwrap().to_string_lossy().trim_end_matches(".beats.json").to_string(); + let text = as_brief(&name, &b); + match args.iter().position(|a| a == "-o").and_then(|i| args.get(i + 1)) { + Some(o) => { let _ = std::fs::write(o, text); } + None => print!("{text}"), + } + return; + } + let tok = match token() { + Ok(t) => t, + Err(e) => { + eprintln!("raea-beats: no token: {e}"); + std::process::exit(1); + } + }; + match args.first().map(String::as_str) { + Some("split") if args.len() >= 2 => { + let brief = std::fs::read_to_string(&args[1]).unwrap_or_default(); + match ask(&tok, &brief) { + Ok(mut b) => { + b["check"] = check(&brief, &b); + let out = args.iter().position(|a| a == "-o").and_then(|i| args.get(i + 1)).cloned().unwrap_or_else(|| args[1].replace(".md", ".beats.json")); + let _ = std::fs::write(&out, serde_json::to_string_pretty(&b).unwrap()); + println!("{}", serde_json::to_string_pretty(&b["check"]).unwrap()); + } + Err(e) => eprintln!("raea-beats: {e}"), + } + } + Some("grade") if args.len() >= 2 => { + let mut files: Vec = std::fs::read_dir(&args[1]).map(|rd| rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "md")).collect()).unwrap_or_default(); + files.sort(); + let mut rows = Vec::new(); + let (mut b, mut g, mut v, mut u, mut a) = (0u64, 0u64, 0u64, 0u64, 0u64); + for f in files { + let brief = std::fs::read_to_string(&f).unwrap_or_default(); + let name = f.file_stem().unwrap().to_string_lossy().to_string(); + match ask(&tok, &brief) { + Ok(mut beats) => { + let c = check(&brief, &beats); + beats["check"] = c.clone(); + let _ = std::fs::write(Path::new(&args[1]).join(format!("{name}.beats.json")), serde_json::to_string_pretty(&beats).unwrap()); + b += c["beats"].as_u64().unwrap_or(0); + g += c["grounded"].as_u64().unwrap_or(0); + v += c["vocabulary"].as_u64().unwrap_or(0); + u += c["units"].as_u64().unwrap_or(0); + a += c["accounted"].as_u64().unwrap_or(0); + rows.push(json!({"brief": name, "check": c})); + } + Err(e) => rows.push(json!({"brief": name, "error": e})), + } + } + println!("{}", serde_json::to_string_pretty(&json!({"briefs": rows.len(), "beats": b, "grounded": g, "vocabulary": v, "units": u, "accounted": a, "each": rows})).unwrap()); + } + _ => eprintln!("raea-beats split BRIEF.md [-o BEATS.json] | grade DIR | brief BEATS.json [-o OUT.brief]"), + } +} diff --git a/brief/tests/conformance.rs b/brief/tests/conformance.rs new file mode 100644 index 00000000..e46c7066 --- /dev/null +++ b/brief/tests/conformance.rs @@ -0,0 +1,40 @@ +//! conformance/cases: each .brief says on its first line what reading it gives: `// expect: ok`, or the refusals it +//! must give as `LINE:COL words` joined by ` | ` (each refusal found at that place and starting with those words) + +use raea_brief::{fmt, graph, load, parse, Loaded}; +use std::path::Path; + +#[test] +fn cases() { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("conformance/cases"); + let mut files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "brief")).collect(); + files.sort(); + let mut failed = Vec::new(); + for f in &files { + let text = std::fs::read_to_string(f).unwrap(); + let expect = text.lines().next().and_then(|l| l.strip_prefix("// expect:")).expect("a case starts with // expect:").trim().to_string(); + let mut docs: Vec = Vec::new(); + let got: Vec = match load(f, &mut Vec::new(), &mut docs).and_then(|_| graph(&docs).map(|_| ())) { + Ok(()) => vec![], + Err(bad) => bad.into_iter().map(|r| { + // a refusal from load carries its file: keep LINE:COL and the words + let m = r.msg.rsplit_once(".brief:").map(|(_, x)| x.splitn(3, ':').nth(2).unwrap_or(x).trim().to_string()).unwrap_or(r.msg); + format!("{}:{} {}", r.line, r.col, m) + }).collect(), + }; + let name = f.file_name().unwrap().to_string_lossy().to_string(); + if expect == "ok" { + if !got.is_empty() { failed.push(format!("{name}: expected ok, got {got:?}")); } + // and fmt reads back + let d = parse(&text).unwrap(); + if parse(&fmt(&d)).is_err() { failed.push(format!("{name}: fmt doesn't read back")); } + continue; + } + for want in expect.split(" | ") { + if !got.iter().any(|g| g.starts_with(want)) { failed.push(format!("{name}: no refusal `{want}` in {got:?}")); } + } + let n = expect.split(" | ").count(); + if got.len() != n { failed.push(format!("{name}: {} refusals, expected {n}: {got:?}", got.len())); } + } + assert!(failed.is_empty(), "{} of {} cases:\n{}", failed.len(), files.len(), failed.join("\n")); +} diff --git a/browser/Cargo.lock b/browser/Cargo.lock new file mode 100644 index 00000000..5b0c94e9 --- /dev/null +++ b/browser/Cargo.lock @@ -0,0 +1,3271 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "agent-browser" +version = "0.39.1" +dependencies = [ + "aes-gcm", + "async-trait", + "base64 0.22.1", + "chrono", + "dirs", + "futures-util", + "getrandom 0.2.17", + "hex", + "hmac", + "image", + "libc", + "reqwest", + "rust-embed", + "rustls", + "rustls-native-certs", + "rustls-pemfile", + "serde", + "serde_json", + "sha2 0.10.9", + "similar", + "socket2", + "tempfile", + "time", + "tokio", + "tokio-tungstenite", + "url", + "urlencoding", + "uuid", + "webpki-roots 0.26.11", + "windows-sys 0.52.0", + "zip", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror 2.0.21", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "exr" +version = "1.74.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "num-complex", + "pulp", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.9", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "bytemuck", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pulp" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raea-browser" +version = "0.1.0" +dependencies = [ + "agent-browser", + "raea-native", + "serde_json", + "tokio", +] + +[[package]] +name = "raea-native" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "flate2", + "getrandom 0.3.4", + "rusqlite", + "serde_json", + "sha1", + "sha2 0.10.9", + "ureq", + "url", +] + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.5", + "rand_chacha 0.9.0", + "simd_helpers", + "thiserror 2.0.21", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots 1.0.9", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rusqlite" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rust-embed" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053" +dependencies = [ + "mime_guess", + "proc-macro2", + "quote", + "rust-embed-utils", + "syn 2.0.119", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a" +dependencies = [ + "sha2 0.11.1", + "walkdir", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.8.8", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror 1.0.69", + "utf-8", +] + +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" +dependencies = [ + "base64 0.22.1", + "flate2", + "log", + "once_cell", + "rustls", + "rustls-pki-types", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.9", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "typed-path", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/browser/Cargo.toml b/browser/Cargo.toml new file mode 100644 index 00000000..c182dfc4 --- /dev/null +++ b/browser/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "raea-browser" +version = "0.1.0" +edition = "2024" +license = "Apache-2.0" +description = "agent-browser's words as raea's browser.* native calls: Chrome over CDP (agent-browser in process) and raea's own Blitz backend" + +[lib] +name = "raea_browser" + +[features] +default = ["chrome"] +# agent-browser in process, Chrome over CDP (the Mac's); without it every command goes to the Blitz backend +chrome = ["dep:agent-browser", "dep:tokio"] + +[dependencies] +agent-browser = { path = "vendor/agent-browser/cli", optional = true } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "sync"], optional = true } +raea-native = { path = "../native" } +raea = { path = "../engine", default-features = false, features = ["network"] } +blitz-v8-script = { path = "../engine/vendor/blitz-v8-script" } +blitz-dom = { path = "../engine/vendor/blitz-dom" } +blitz-traits = { version = "=0.3.0-beta.3", default-features = false } +blitz-html = { version = "=0.3.0-beta.3", default-features = false } +keyboard-types = "0.7" +image = { version = "0.25", default-features = false, features = ["png"] } +url = "2" +serde_json = "1" diff --git a/browser/conformance/browser.test.ts b/browser/conformance/browser.test.ts new file mode 100644 index 00000000..22ec8f7e --- /dev/null +++ b/browser/conformance/browser.test.ts @@ -0,0 +1,103 @@ +// @raea/browser on the Mac (Chrome over CDP, agent-browser in process): a fixture form opened, read as a snapshot with +// refs, filled and clicked by ref, and the result read back; a screenshot written. Skipped where there's no browser. +import { describe, expect, test } from "bun:test"; +import { hasNative, native } from "@raea/motion/native"; +import { Browser } from "../ts"; + +const root = engineRoot(); +function engineRoot(): string | null { + if (!hasNative()) return null; + return native("host.env", { name: "RAEA_ROOT" }) as string | null; +} +const hasBrowser = (() => { + try { + return hasNative() && native("host.platform", {}) === "macos" && (native("host.env", { name: "RAEA_NO_BROWSER" }) as string | null) !== "1" && !!root; + } catch { + return false; + } +})(); + +describe.skipIf(!hasBrowser)("the browser (Chrome over CDP, in process)", () => { + const b = new Browser(`raea-test-${Date.now()}`); + test("open, snapshot with refs, fill and click by ref, read the result", () => { + b.open(`file://${root}/browser/conformance/pages/form.html`); + const snap = b.snapshot({ interactive: true }); + const refs = snap.data.refs; + const find = (role: string, name: string) => Object.entries(refs).find(([, r]) => r.role === role && (r.name ?? "").includes(name))?.[0]; + const email = find("textbox", "Email"); + const join = find("button", "Join"); + expect(email).toBeDefined(); + expect(join).toBeDefined(); + expect(snap.data.snapshot).toContain(`[ref=${email}]`); + b.fill(`@${email}`, "kelly@example.com"); + b.click(`@${join}`); + expect(String(b.get("text", "#out").data && (b.get("text", "#out").data as { text?: string }).text)).toBe("Thanks, kelly@example.com on Go"); + expect((b.get("title").data as { title?: string }).title).toBe("Sign up"); + }, 60000); + test("eval, a screenshot to a file, batch, and a refusal", () => { + expect((b.eval("1 + 2").data as { result?: unknown }).result).toBe(3); + const tmp = (native("host.env", { name: "TMPDIR" }) as string) + `raea-browser-${Date.now()}.png`; + b.screenshot(tmp); + expect(native("media.size", { path: tmp })).toBeGreaterThan(1000); + const r = b.batch([["get", "title"], ["get", "url"]]); + expect(r.success).toBe(true); + expect(() => b.click("#nothing-here")).toThrow(); + b.close(); + }, 60000); +}); + +describe.skipIf(!hasBrowser)("the browser as a shell command", () => { + test("browser open, snapshot and screenshot into the project", async () => { + const { Shell } = await import("@raea/shell"); + const tmp = native("host.env", { name: "TMPDIR" }) as string; + const sh = new Shell({ root: `${tmp}raea-browser-shell-${Date.now()}` }); + await sh.exec(`browser --session shelltest open file://${root}/browser/conformance/pages/form.html`); + const snap = await sh.exec("browser --session shelltest snapshot -i"); + expect(snap.exitCode).toBe(0); + expect(snap.stdout).toContain("textbox"); + const shot = await sh.exec("browser --session shelltest screenshot shots/form.png && ls shots"); + expect(shot.stdout).toBe("✓ Screenshot saved to /shots/form.png\nform.png\n"); + expect((shot.row as any).written.map((w: any) => w.path)).toContain("/shots/form.png"); + await sh.exec("browser --session shelltest close"); + }, 60000); +}); + +const blitzOnly = hasNative() && !!root; +describe.skipIf(!blitzOnly)("the Blitz backend (no Chrome)", () => { + const b = new Browser(`raea-blitz-${Date.now()}`); + const words = (...w: string[]) => b.raw("--engine", "blitz", ...w); + test("open, snapshot, fill and click by ref, read the result, screenshot", () => { + expect(words("open", `file://${root}/browser/conformance/pages/form.html`).success).toBe(true); + const snap = words("snapshot", "-i"); + expect(snap.success).toBe(true); + const refs = (snap.data as { refs: Record }).refs; + const find = (role: string, name: string) => Object.entries(refs).find(([, r]) => r.role === role && r.name === name)?.[0]; + expect(words("fill", `@${find("textbox", "Email")}`, "kelly@example.com").success).toBe(true); + expect(words("click", `@${find("button", "Join")}`).success).toBe(true); + expect(((words("get", "text", "#out").data) as { text: string }).text).toBe("Thanks, kelly@example.com on Go"); + expect((words("get", "title").data as { title: string }).title).toBe("Sign up"); + expect((words("eval", "1 + 2").data as { result: unknown }).result).toBe(3); + const tmp = (native("host.env", { name: "TMPDIR" }) as string) + `raea-blitz-${Date.now()}.png`; + expect(words("screenshot", tmp).success).toBe(true); + expect(native("media.size", { path: tmp })).toBeGreaterThan(1000); + expect(words("click", "@e99").success).toBe(false); + words("close"); + }, 60000); +}); + +describe.skipIf(!hasBrowser)("parity: the same refs from Chrome and from Blitz", () => { + for (const page of ["form.html", "list.html"]) { + test(`${page}: interactive snapshots agree line for line`, () => { + const url = `file://${root}/browser/conformance/pages/${page}`; + const chrome = new Browser(`parity-chrome-${Date.now()}`); + chrome.open(url); + const c = chrome.snapshot({ interactive: true }).text.trim(); + chrome.close(); + const blitz = new Browser(`parity-blitz-${Date.now()}`); + blitz.raw("--engine", "blitz", "open", url); + const z = blitz.raw("--engine", "blitz", "snapshot", "-i").text.trim(); + blitz.raw("--engine", "blitz", "close"); + expect(z).toBe(c); + }, 60000); + } +}); diff --git a/browser/conformance/pages/form.html b/browser/conformance/pages/form.html new file mode 100644 index 00000000..38e4e3a2 --- /dev/null +++ b/browser/conformance/pages/form.html @@ -0,0 +1,12 @@ + +Sign up + + +

Sign up

+ + + + + + Terms + diff --git a/browser/conformance/pages/list.html b/browser/conformance/pages/list.html new file mode 100644 index 00000000..7c64dfca --- /dev/null +++ b/browser/conformance/pages/list.html @@ -0,0 +1,17 @@ + +Shots + + +
+

Shot list

+
  • Hook
  • Demo
  • Call to action
+ + + + + + + + Thumbnail +
+ diff --git a/browser/src/blitz.rs b/browser/src/blitz.rs new file mode 100644 index 00000000..ca865857 --- /dev/null +++ b/browser/src/blitz.rs @@ -0,0 +1,827 @@ +//! The Blitz backend: agent-browser's words answered by raea's own engine, without Chrome (so on the iPhone too, and +//! deterministically: a virtual clock, no network unless allowed). A page is a ScriptDocument (Blitz + Stylo + the +//! engine's V8 page scripts); `snapshot` reads the DOM as an accessibility tree in agent-browser's format and numbering +//! (interactive roles always get a ref, named content roles too, a select's options after everything else, as Chrome's +//! tree has them); `click` dispatches a synthetic click through Blitz's event driver (the page's listeners and Blitz's +//! default actions run), `fill` and `type` set a control's value and fire input and change, `get`, `eval` and +//! `screenshot` read the page. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::Arc; + +use blitz_dom::{BaseDocument, Document as _, DocumentConfig, LocalName, Node, NodeId}; +use blitz_traits::events::DomEvent; +use keyboard_types::Modifiers; +use blitz_traits::shell::{ColorScheme, Viewport}; +use blitz_v8_script::ScriptDocument; +use serde_json::{Value, json}; + +type R = Result; + +const PAGE_PRELUDE: &str = r#"(function () { + try { + document.querySelectorAll('*').forEach(function (el) { + (el.getAttributeNames ? el.getAttributeNames() : []).forEach(function (n) { + if (n.length > 2 && n.slice(0, 2) === 'on') { + var fn; try { fn = new Function('event', el.getAttribute(n)); } catch (e) { return; } + el.addEventListener(n.slice(2), function (e) { return fn.call(el, e); }); + } + }); + }); + } catch (e) {} + try { + var any = document.documentElement && Object.getPrototypeOf(document.documentElement); + var d = any && Object.getOwnPropertyDescriptor(any, 'value'); + var opts = function (el) { return Array.prototype.slice.call(el.querySelectorAll('option')); }; + var chosen = function (el) { var o = opts(el); return o.find(function (x) { return x.__raeaSelected; }) || o.find(function (x) { return x.hasAttribute('selected'); }) || o[0] || null; }; + var optValue = function (o) { return o.hasAttribute('value') ? o.getAttribute('value') : (o.textContent || '').trim(); }; + Object.defineProperty(any, 'value', { configurable: true, + get: function () { if (this.tagName === 'SELECT') { var c = chosen(this); return c ? optValue(c) : ''; } if (this.tagName === 'OPTION') return optValue(this); return d && d.get ? d.get.call(this) : this.getAttribute('value'); }, + set: function (v) { if (this.tagName === 'SELECT') { opts(this).forEach(function (o) { o.__raeaSelected = optValue(o) === String(v); }); return; } if (d && d.set) d.set.call(this, v); else this.setAttribute('value', v); } }); + Object.defineProperty(any, 'selectedIndex', { configurable: true, get: function () { if (this.tagName !== 'SELECT') return -1; var c = chosen(this); return c ? opts(this).indexOf(c) : -1; } }); + Object.defineProperty(any, 'options', { configurable: true, get: function () { return this.tagName === 'SELECT' ? opts(this) : undefined; } }); + Object.defineProperty(any, 'selected', { configurable: true, get: function () { if (this.tagName !== 'OPTION') return undefined; var s = this.closest ? this.closest('select') : null; return s ? chosen(s) === this : this.hasAttribute('selected'); } }); + Object.defineProperty(any, 'text', { configurable: true, get: function () { return (this.textContent || '').trim(); } }); + } catch (e) {} +})();"#; + +pub struct Page { + doc: ScriptDocument, + url: String, + width: u32, + height: u32, + refs: HashMap, + result: Rc>>, +} + +thread_local! { + static PAGES: RefCell> = RefCell::new(HashMap::new()); +} + +const SKIP: &[&str] = &["script", "style", "head", "template", "noscript", "meta", "link", "title", "base"]; +const INTERACTIVE: &[&str] = &["button", "link", "textbox", "checkbox", "radio", "combobox", "listbox", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "searchbox", "slider", "spinbutton", "switch", "tab", "treeitem"]; +const CONTENT: &[&str] = &["heading", "cell", "gridcell", "columnheader", "rowheader", "listitem", "article", "region", "main", "navigation"]; + +fn attr<'a>(n: &'a Node, name: &str) -> Option<&'a str> { + n.element_data()?.attr(LocalName::from(name)) +} +fn tag(n: &Node) -> String { + n.element_data().map(|e| e.name.local.to_string()).unwrap_or_default() +} +fn collapse(s: &str) -> String { + s.split_whitespace().collect::>().join(" ") +} + +/// Whitespace runs as one space, ends kept: a label's text as Chrome names its control (" Done" after a checkbox). +fn collapse_runs(s: &str) -> String { + let mut out = String::new(); + let mut ws = false; + for c in s.chars() { + if c.is_whitespace() { + if !ws { + out.push(' '); + } + ws = true; + } else { + out.push(c); + ws = false; + } + } + out.trim_end().to_string() +} + +/// The text a person sees in a subtree (scripts and hidden parts left out). +fn text_of(doc: &BaseDocument, id: NodeId) -> String { + let Some(n) = doc.get_node(id) else { return String::new() }; + if n.is_text_node() { + return n.text_content(); + } + if SKIP.contains(&tag(n).as_str()) || hidden(n) { + return String::new(); + } + n.children.iter().map(|c| text_of(doc, *c)).collect::>().join(if matches!(tag(n).as_str(), "br" | "p" | "div" | "li") { " " } else { "" }) +} + +fn hidden(n: &Node) -> bool { + if attr(n, "hidden").is_some() || attr(n, "aria-hidden") == Some("true") || (tag(n) == "input" && attr(n, "type") == Some("hidden")) { + return true; + } + // a select's options are drawn by the select (display: none in the page), yet they're in the tree + tag(n) != "option" && n.primary_styles().is_some_and(|s| s.get_box().display.is_none()) +} + +/// A select's chosen option: the live one when the page said, else the first marked `selected`, else the first. +fn chosen_option(doc: &BaseDocument, select: NodeId, values: &HashMap) -> Option { + let opts: Vec = all_under(doc, select).into_iter().filter(|id| doc.get_node(*id).is_some_and(|n| tag(n) == "option")).collect(); + opts.iter().copied().find(|id| values.get(id).is_some_and(|v| v == "selected")) + .or_else(|| opts.iter().copied().find(|id| doc.get_node(*id).is_some_and(|n| attr(n, "selected").is_some()))) + .or_else(|| opts.first().copied()) +} + +fn all_under(doc: &BaseDocument, root: NodeId) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![root]; + while let Some(x) = stack.pop() { + out.push(x); + if let Some(n) = doc.get_node(x) { + stack.extend(n.children.iter().rev()); + } + } + out +} + +struct Ax { + role: String, + name: String, + level: Option, + checked: Option, + expanded: Option, + selected: bool, + disabled: bool, + required: bool, + value: Option, + node: NodeId, + children: Vec, + ref_id: Option, + named_by_content: bool, +} + +fn implicit_role(doc: &BaseDocument, n: &Node) -> String { + if let Some(r) = attr(n, "role") { + return r.split_whitespace().next().unwrap_or("").to_string(); + } + let t = tag(n); + match t.as_str() { + "a" | "area" if attr(n, "href").is_some() => "link".into(), + "button" => "button".into(), + "input" => match attr(n, "type").unwrap_or("text").to_ascii_lowercase().as_str() { + "button" | "submit" | "reset" | "image" => "button".into(), + "checkbox" => "checkbox".into(), + "radio" => "radio".into(), + "range" => "slider".into(), + "number" => "spinbutton".into(), + "search" => "searchbox".into(), + _ => "textbox".into(), + }, + "textarea" => "textbox".into(), + "select" => if attr(n, "multiple").is_some() || attr(n, "size").and_then(|s| s.parse::().ok()).is_some_and(|s| s > 1) { "listbox".into() } else { "combobox".into() }, + "option" => "option".into(), + "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => "heading".into(), + "img" => if attr(n, "alt").is_some_and(|a| a.is_empty()) { String::new() } else { "img".into() }, + "ul" | "ol" | "menu" => "list".into(), + "li" => "listitem".into(), + "nav" => "navigation".into(), + "main" => "main".into(), + "article" => "article".into(), + "aside" => "complementary".into(), + "section" if attr(n, "aria-label").is_some() || attr(n, "aria-labelledby").is_some() => "region".into(), + "form" if attr(n, "aria-label").is_some() || attr(n, "name").is_some() => "form".into(), + "table" => "table".into(), + "tr" => "row".into(), + "td" => "cell".into(), + "th" => "columnheader".into(), + "p" => "paragraph".into(), + "label" => "LabelText".into(), + "dialog" => "dialog".into(), + "fieldset" => "group".into(), + "progress" => "progressbar".into(), + "header" if !inside(doc, n, &["article", "section", "main"]) => "banner".into(), + "footer" if !inside(doc, n, &["article", "section", "main"]) => "contentinfo".into(), + _ => String::new(), + } +} + +fn inside(doc: &BaseDocument, n: &Node, tags: &[&str]) -> bool { + let mut p = n.parent; + while let Some(id) = p { + let Some(pn) = doc.get_node(id) else { break }; + if tags.contains(&tag(pn).as_str()) { + return true; + } + p = pn.parent; + } + false +} + +/// The accessible name (aria-label, aria-labelledby, a label, alt, the content for roles named by it, value, +/// placeholder, title), and whether it came from the content. +fn name_of(doc: &BaseDocument, n: &Node, role: &str) -> (String, bool) { + if let Some(l) = attr(n, "aria-label").filter(|l| !l.trim().is_empty()) { + return (collapse(l), false); + } + if let Some(ids) = attr(n, "aria-labelledby") { + let t: Vec = ids.split_whitespace().filter_map(|i| doc.get_element_by_id(i)).map(|id| collapse(&text_of(doc, id))).collect(); + if !t.is_empty() { + return (t.join(" "), false); + } + } + let t = tag(n); + if matches!(t.as_str(), "input" | "select" | "textarea") { + if matches!(attr(n, "type"), Some("button" | "submit" | "reset")) { + return (attr(n, "value").map(collapse).unwrap_or_else(|| if attr(n, "type") == Some("submit") { "Submit".into() } else { String::new() }), false); + } + if let Some(id) = attr(n, "id") { + if let Some(l) = find_label(doc, id) { + return (l, false); + } + } + let mut p = n.parent; + while let Some(pid) = p { + let Some(pn) = doc.get_node(pid) else { break }; + if tag(pn) == "label" { + return (collapse_runs(&text_of(doc, pid)), false); + } + p = pn.parent; + } + if let Some(ph) = attr(n, "placeholder").filter(|p| !p.is_empty()) { + return (collapse(ph), false); + } + } + if t == "img" { + if let Some(a) = attr(n, "alt") { + return (collapse(a), false); + } + } + if matches!(role, "button" | "link" | "heading" | "option" | "cell" | "columnheader" | "rowheader" | "gridcell" | "menuitem" | "tab" | "treeitem" | "checkbox" | "radio" | "switch" | "LabelText") { + let c = collapse(&text_of(doc, n.id)); + if !c.is_empty() { + return (c, true); + } + } + (attr(n, "title").map(collapse).unwrap_or_default(), false) +} + +fn find_label(doc: &BaseDocument, id: &str) -> Option { + let mut stack = vec![doc.root_node().id]; + while let Some(x) = stack.pop() { + let Some(n) = doc.get_node(x) else { continue }; + if tag(n) == "label" && attr(n, "for") == Some(id) { + return Some(collapse(&text_of(doc, x))); + } + stack.extend(n.children.iter().rev()); + } + None +} + +fn build(doc: &BaseDocument, id: NodeId, out: &mut Vec, parent: Option, values: &HashMap) { + let Some(n) = doc.get_node(id) else { return }; + if n.is_text_node() { + let t = collapse(&n.text_content()); + if !t.is_empty() { + let me = out.len(); + out.push(Ax { role: "StaticText".into(), name: t, level: None, checked: None, expanded: None, selected: false, disabled: false, required: false, value: None, node: id, children: Vec::new(), ref_id: None, named_by_content: false }); + if let Some(p) = parent { + out[p].children.push(me); + } + } + return; + } + if n.element_data().is_some() && (SKIP.contains(&tag(n).as_str()) || hidden(n)) { + return; + } + let role = if n.element_data().is_some() { implicit_role(doc, n) } else { String::new() }; + let me = if role.is_empty() { + parent + } else { + let (name, by_content) = name_of(doc, n, &role); + let t = tag(n); + let level = if role == "heading" { attr(n, "aria-level").and_then(|l| l.parse().ok()).or_else(|| t.strip_prefix('h').and_then(|d| d.parse().ok())) } else { None }; + let checked = if matches!(role.as_str(), "checkbox" | "radio" | "switch") { Some(values.get(&id).map(|v| v == "true").unwrap_or(attr(n, "checked").is_some())) } else { None }; + let value = match role.as_str() { + "textbox" | "searchbox" | "spinbutton" => values.get(&id).cloned().or_else(|| attr(n, "value").map(str::to_string)).filter(|v| !v.is_empty()), + "combobox" => chosen_option(doc, id, values).map(|o| collapse(&text_of(doc, o))), + _ => None, + }; + let chosen = if role == "option" { n.parent.and_then(|p| { let mut q = Some(p); while let Some(x) = q { if doc.get_node(x).is_some_and(|pn| tag(pn) == "select") { return Some(x); } q = doc.get_node(x).and_then(|pn| pn.parent); } None }).and_then(|sel| chosen_option(doc, sel, values)) == Some(id) } else { false }; + let name = if role == "LabelText" { String::new() } else { name }; + let o = out.len(); + out.push(Ax { + role: role.clone(), + name, + level, + checked, + expanded: if role == "combobox" { Some(false) } else { None }, + selected: chosen, + disabled: attr(n, "disabled").is_some(), + required: attr(n, "required").is_some(), + value, + node: id, + children: Vec::new(), + ref_id: None, + named_by_content: by_content, + }); + if let Some(p) = parent { + out[p].children.push(o); + } + Some(o) + }; + // a select's options sit in a MenuListPopup, as Chrome's tree has them + if me.is_some_and(|m| out[m].role == "combobox") { + let popup = out.len(); + out.push(Ax { role: "MenuListPopup".into(), name: String::new(), level: None, checked: None, expanded: None, selected: false, disabled: false, required: false, value: None, node: id, children: Vec::new(), ref_id: None, named_by_content: false }); + out[me.unwrap()].children.push(popup); + for c in &n.children { + build(doc, *c, out, Some(popup), values); + } + return; + } + // a node named by its content doesn't list that text again + if me.is_some_and(|m| out[m].named_by_content && out[m].role != "LabelText") { + for c in &n.children { + if doc.get_node(*c).is_some_and(|cn| cn.element_data().is_some()) { + build(doc, *c, out, me, values); + } + } + return; + } + for c in &n.children { + build(doc, *c, out, me, values); + } +} + +fn render(nodes: &[Ax], idx: usize, indent: usize, interactive: bool, out: &mut String) { + let n = &nodes[idx]; + if interactive && n.ref_id.is_none() { + for c in &n.children { + render(nodes, *c, indent, interactive, out); + } + return; + } + let mut line = format!("{}- {}", " ".repeat(indent), n.role); + if !n.name.is_empty() { + line += &format!(" {}", serde_json::to_string(&n.name).unwrap_or_default()); + } + let mut attrs = Vec::new(); + if let Some(l) = n.level { + attrs.push(format!("level={l}")); + } + if let Some(c) = n.checked { + attrs.push(format!("checked={c}")); + } + if let Some(e) = n.expanded { + attrs.push(format!("expanded={e}")); + } + if n.selected { + attrs.push("selected".into()); + } + if n.disabled { + attrs.push("disabled".into()); + } + if n.required { + attrs.push("required".into()); + } + if let Some(r) = &n.ref_id { + attrs.push(format!("ref={r}")); + } + if !attrs.is_empty() { + line += &format!(" [{}]", attrs.join(", ")); + } + if let Some(v) = &n.value { + line += &format!(": {v}"); + } + out.push_str(&line); + out.push('\n'); + for c in &n.children { + render(nodes, *c, indent + 1, interactive, out); + } +} + +impl Page { + fn open(url: &str, allow_network: bool, size: (u32, u32)) -> R { + let (html, base) = if let Some(data) = url.strip_prefix("data:text/html,") { + (urlencoding_decode(data), url::Url::parse("about:blank").ok()) + } else { + let u = url::Url::parse(url).or_else(|_| url::Url::from_file_path(std::path::absolute(url).map_err(|e| e.to_string())?).map_err(|_| format!("{url}: not a URL or a path")))?; + let net = raea::net::SyncNet::new(std::path::Path::new("."), allow_network); + let bytes = net.load(&u).map_err(|e| format!("{url}: {e}"))?; + (String::from_utf8_lossy(&bytes).into_owned(), Some(u)) + }; + let net = Arc::new(raea::net::SyncNet::new(std::path::Path::new("."), allow_network)); + let config = DocumentConfig { + base_url: base.as_ref().map(|u| u.to_string()), + net_provider: Some(net.clone() as _), + html_parser_provider: Some(Arc::new(blitz_html::HtmlProvider)), + viewport: Some(Viewport::new(size.0, size.1, 1.0, ColorScheme::Light)), + ..Default::default() + }; + let mut doc = BaseDocument::new(config); + { + let mut m = doc.mutate(); + blitz_html::DocumentHtmlParser::parse_into_mutator(&mut m, &html); + } + let result: Rc>> = Default::default(); + let slot = result.clone(); + let mut sdoc = ScriptDocument::from_base_document(doc).without_timer_thread().with_virtual_time().with_native("raea_result", move |s| { + *slot.borrow_mut() = Some(s.to_string()); + Ok(String::new()) + }); + // what a browser gives a page that the engine's page runtime leaves out: inline on* attributes bound as + // listeners, and a select's value and selectedIndex from its options + sdoc.eval(PAGE_PRELUDE); + sdoc.execute_scripts(); + // an event fired the way the page's runtime can make one + sdoc.eval("window.__raeaFire = function (el, type) { var e; try { e = new Event(type, { bubbles: true }); } catch (_) { try { e = document.createEvent('Event'); e.initEvent(type, true, true); } catch (__) { e = null; } } if (e) el.dispatchEvent(e); };"); + let mut page = Page { doc: sdoc, url: base.map(|u| u.to_string()).unwrap_or_else(|| url.to_string()), width: size.0, height: size.1, refs: HashMap::new(), result }; + page.settle(50); + Ok(page) + } + + /// Due timers run on the virtual clock, up to `ms` ahead, then style and layout. + fn settle(&mut self, ms: u64) { + let end = self.doc.clock_now() + std::time::Duration::from_millis(ms); + for _ in 0..1000 { + match self.doc.next_timer_deadline() { + Some(d) if d <= end => { + self.doc.advance_clock_to(d); + self.doc.poll(None); + } + _ => break, + } + } + self.doc.advance_clock_to(end); + let mut inner = self.doc.inner_mut(); + inner.resolve(0.0); + } + + /// JS run in the page; what it hands to `raea_result` (JSON) comes back. + fn js(&mut self, code: &str) -> R { + *self.result.borrow_mut() = None; + self.doc.eval(&format!("try {{ __blitz_native('raea_result', JSON.stringify({{ ok: (function() {{ {code} }})() }})) }} catch (e) {{ __blitz_native('raea_result', JSON.stringify({{ err: String(e && e.message || e) }})) }}")); + let errs = self.doc.take_js_errors(); + let r = self.result.borrow_mut().take(); + match r.and_then(|s| serde_json::from_str::(&s).ok()) { + Some(v) if v.get("err").is_some() => Err(v["err"].as_str().unwrap_or("error").to_string()), + Some(v) => Ok(v.get("ok").cloned().unwrap_or(Value::Null)), + None => Err(errs.first().cloned().unwrap_or_else(|| "the script didn't answer".into())), + } + } + + /// The node a target names: @eN / eN from the last snapshot, or a CSS selector. + fn target(&mut self, t: &str) -> R { + let r = t.trim_start_matches('@'); + if let Some(id) = self.refs.get(r) { + return Ok(*id); + } + if r.starts_with('e') && r[1..].chars().all(|c| c.is_ascii_digit()) && !r[1..].is_empty() { + return Err(format!("Element \"{t}\" not found: take a fresh snapshot")); + } + let sel = serde_json::to_string(t).unwrap(); + self.js(&format!("const el = document.querySelector({sel}); if (!el) throw new Error('Element \"' + {sel} + '\" not found'); el.setAttribute('data-raea-target', ''); return 1;"))?; + let doc = self.doc.inner(); + let found = all_nodes(&doc).into_iter().find(|&id| doc.get_node(id).is_some_and(|n| attr(n, "data-raea-target").is_some())); + drop(doc); + self.js("const el = document.querySelector('[data-raea-target]'); if (el) el.removeAttribute('data-raea-target'); return 1;")?; + found.ok_or_else(|| format!("Element \"{t}\" not found")) + } + + /// JS with `el` bound to the node. + fn on(&mut self, node: NodeId, code: &str) -> R { + { + let mut d = self.doc.inner_mut(); + d.mutate().set_attribute(node, blitz_dom::QualName::new(None, blitz_dom::ns!(), blitz_dom::LocalName::from("data-raea-target")), ""); + } + let r = self.js(&format!("const el = document.querySelector('[data-raea-target]'); el.removeAttribute('data-raea-target'); {code}")); + r + } + + fn values(&mut self) -> HashMap { + // current values of controls, read from the page (Blitz keeps a form control's live value in JS) + let _ = self.js("document.querySelectorAll('input,textarea,select,option').forEach((el, i) => el.setAttribute('data-raea-v', String(i))); return 1;"); + let v = self.js("return Array.from(document.querySelectorAll('input,textarea,select,option')).map((el) => el.tagName === 'OPTION' ? (el.selected ? 'selected' : '') : el.tagName === 'SELECT' ? (el.options && el.options[el.selectedIndex] ? el.options[el.selectedIndex].text : '') : (el.type === 'checkbox' || el.type === 'radio') ? String(!!el.checked) : String(el.value == null ? '' : el.value));").unwrap_or(Value::Null); + let doc = self.doc.inner(); + let mut out = HashMap::new(); + if let Some(list) = v.as_array() { + for id in all_nodes(&doc) { + if let Some(i) = doc.get_node(id).and_then(|n| attr(n, "data-raea-v")).and_then(|s| s.parse::().ok()) { + if let Some(s) = list.get(i).and_then(Value::as_str) { + out.insert(id, s.to_string()); + } + } + } + } + drop(doc); + let _ = self.js("document.querySelectorAll('[data-raea-v]').forEach((el) => el.removeAttribute('data-raea-v')); return 1;"); + out + } + + fn snapshot(&mut self, interactive: bool) -> Value { + let values = self.values(); + let doc = self.doc.inner(); + let mut nodes: Vec = Vec::new(); + let root = doc.root_node().id; + nodes.push(Ax { role: "RootWebArea".into(), name: String::new(), level: None, checked: None, expanded: None, selected: false, disabled: false, required: false, value: None, node: root, children: Vec::new(), ref_id: None, named_by_content: false }); + for c in doc.root_node().children.clone() { + build(&doc, c, &mut nodes, Some(0), &values); + } + // a select with no option chosen shows its first + let mut refs = serde_json::Map::new(); + self.refs.clear(); + let mut k = 0; + let mut options = Vec::new(); + for i in 0..nodes.len() { + let n = &nodes[i]; + let wants = INTERACTIVE.contains(&n.role.as_str()) || (CONTENT.contains(&n.role.as_str()) && !n.name.is_empty()); + if !wants { + continue; + } + if n.role == "option" { + options.push(i); + continue; + } + k += 1; + nodes[i].ref_id = Some(format!("e{k}")); + } + for i in options { + k += 1; + nodes[i].ref_id = Some(format!("e{k}")); + } + for n in &nodes { + if let Some(r) = &n.ref_id { + refs.insert(r.clone(), json!({"role": n.role, "name": n.name})); + self.refs.insert(r.clone(), n.node); + } + } + drop(doc); + let mut text = String::new(); + for c in nodes[0].children.clone() { + render(&nodes, c, 0, interactive, &mut text); + } + json!({"snapshot": text.trim_end(), "refs": refs, "origin": self.url}) + } + + fn click(&mut self, node: NodeId) -> R<()> { + let ev = { + let d = self.doc.inner(); + let n = d.get_node(node).ok_or("that element is gone")?; + n.synthetic_click_event(Modifiers::empty()) + }; + self.doc.dispatch_dom_event(DomEvent::new(node, ev)); + self.settle(50); + Ok(()) + } + + fn screenshot(&mut self, path: &str, full: bool) -> R<()> { + let h = if full { + let d = self.doc.inner(); + (d.root_element().final_layout().size.height.ceil() as u32).max(self.height) + } else { + self.height + }; + if full { + let mut d = self.doc.inner_mut(); + d.set_viewport(Viewport::new(self.width, h, 1.0, ColorScheme::Light)); + d.resolve(0.0); + } + let mut rgba = Vec::new(); + { + let mut d = self.doc.inner_mut(); + raea::row_render::paint_document(&mut d, self.width, h, 1.0, false, &mut rgba); + } + for px in rgba.chunks_exact_mut(4) { + let k = 255 - px[3] as u16; + for c in &mut px[..3] { + *c = (*c as u16 + k).min(255) as u8; + } + px[3] = 255; + } + if let Some(dir) = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()) { + let _ = std::fs::create_dir_all(dir); + } + image::save_buffer(path, &rgba, self.width, h, image::ExtendedColorType::Rgba8).map_err(|e| format!("{path}: {e}")) + } +} + +fn all_nodes(doc: &BaseDocument) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![doc.root_node().id]; + while let Some(x) = stack.pop() { + out.push(x); + if let Some(n) = doc.get_node(x) { + stack.extend(n.children.iter().rev()); + } + } + out +} + +fn urlencoding_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' && i + 2 < b.len() { + if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) { + out.push(v); + i += 3; + continue; + } + } + out.push(b[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +/// agent-browser's words on the Blitz backend: the same response shape and printed text for the verbs it has. Pages +/// live on one thread of their own (each page has its own V8 isolate, which mustn't be entered inside a caller's), and +/// each request waits for its answer. +pub fn run(args: &[String]) -> R { + type Req = (Vec, std::sync::mpsc::Sender>); + static TX: std::sync::OnceLock>> = std::sync::OnceLock::new(); + let tx = TX.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("raea-browser-blitz".into()) + .stack_size(16 << 20) + .spawn(move || { + for (args, reply) in rx { + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run_here(&args))).unwrap_or_else(|_| Err("the Blitz page panicked".into())); + let _ = reply.send(r); + } + }) + .expect("the Blitz thread"); + std::sync::Mutex::new(tx) + }); + let (rtx, rrx) = std::sync::mpsc::channel(); + tx.lock().unwrap().send((args.to_vec(), rtx)).map_err(|e| e.to_string())?; + rrx.recv().map_err(|e| e.to_string())? +} + +fn run_here(args: &[String]) -> R { + // --session NAME picks the page; --engine blitz and other flags are taken out + let mut session = "default".to_string(); + let mut allow_network = false; + let mut size = (1280u32, 720u32); + let mut words: Vec = Vec::new(); + let mut i = 0; + while i < args.len() { + match args[i].as_str() { + "--session" => { + session = args.get(i + 1).cloned().unwrap_or_default(); + i += 2; + } + "--engine" | "--screenshot-format" | "--screenshot-quality" | "--cdp" => i += 2, + "--allow-network" => { + allow_network = true; + i += 1; + } + "--viewport" => { + if let Some((w, h)) = args.get(i + 1).and_then(|v| v.split_once('x')) { + size = (w.parse().unwrap_or(1280), h.parse().unwrap_or(720)); + } + i += 2; + } + _ => { + words.push(args[i].clone()); + i += 1; + } + } + } + let verb = words.first().map(String::as_str).unwrap_or(""); + let ok = |data: Value, text: String| Ok(json!({"success": true, "data": data, "error": null, "code": null, "text": text})); + let fail = |e: String| Ok(json!({"success": false, "data": null, "error": e.clone(), "code": null, "text": format!("✗ {e}\n")})); + if verb == "open" || verb == "goto" || verb == "navigate" { + let Some(url) = words.get(1) else { return ok(json!({"url": "about:blank"}), "✓ about:blank\n".into()) }; + return match Page::open(url, allow_network, size) { + Ok(p) => { + let title = p_title(&p); + let u = p.url.clone(); + PAGES.with(|ps| { + if let Some(old) = ps.borrow_mut().insert(session.clone(), p) { + retire(old); + } + }); + ok(json!({"url": u, "title": title}), format!("✓ {title}\n {u}\n")) + } + Err(e) => fail(e), + }; + } + if verb == "close" { + PAGES.with(|ps| { + if let Some(old) = ps.borrow_mut().remove(&session) { + retire(old); + } + }); + return ok(json!({"closed": true}), "✓ Browser closed\n".into()); + } + if verb == "batch" { + return Err("batch is answered by the caller".into()); + } + PAGES.with(|ps| { + let mut ps = ps.borrow_mut(); + let Some(p) = ps.get_mut(&session) else { return fail("no page is open (open URL first)".into()) }; + let r: R<(Value, String)> = (|| match verb { + "snapshot" => { + let interactive = words.iter().any(|w| w == "-i" || w == "--interactive"); + let s = p.snapshot(interactive); + let text = format!("{}\n", s["snapshot"].as_str().unwrap_or("")); + Ok((s, text)) + } + "click" | "dblclick" => { + let t = words.get(1).ok_or("click needs a target")?; + let n = p.target(t)?; + p.click(n)?; + Ok((json!({"clicked": t}), "✓ Done\n".into())) + } + "fill" | "type" => { + let t = words.get(1).ok_or("fill needs a target and text")?; + let text = words.get(2).cloned().unwrap_or_default(); + let n = p.target(t)?; + let s = serde_json::to_string(&text).unwrap(); + let set = if verb == "fill" { format!("el.value = {s};") } else { format!("el.value = String(el.value || '') + {s};") }; + let value = p.on(n, &format!("if (el.focus) el.focus(); {set} return String(el.value);"))?; + // the input event through Blitz's driver, so the page's input listeners see it + p.doc.dispatch_dom_event(DomEvent::new(n, blitz_traits::events::DomEventData::Input(blitz_traits::events::BlitzInputEvent { value: value.as_str().unwrap_or("").to_string() }))); + p.settle(20); + Ok((json!({"filled": t}), "✓ Done\n".into())) + } + "select" => { + let t = words.get(1).ok_or("select needs a target and a value")?; + let v = serde_json::to_string(&words.get(2).cloned().unwrap_or_default()).unwrap(); + let n = p.target(t)?; + p.on(n, &format!("const o = Array.from(el.options).find((o) => o.value === {v} || o.text === {v}); if (!o) throw new Error('no option ' + {v}); el.value = o.value; return 1;"))?; + p.settle(20); + Ok((json!({"selected": t}), "✓ Done\n".into())) + } + "check" | "uncheck" => { + let t = words.get(1).ok_or("check needs a target")?; + let n = p.target(t)?; + p.on(n, &format!("el.checked = {}; __raeaFire(el, 'change'); return 1;", verb == "check"))?; + Ok((json!({"checked": verb == "check"}), "✓ Done\n".into())) + } + "press" | "key" => { + let key = serde_json::to_string(words.get(1).ok_or("press needs a key")?).unwrap(); + p.js(&format!("const t = document.activeElement || document.body; for (const type of ['keydown', 'keyup']) t.dispatchEvent(new KeyboardEvent(type, {{ key: {key}, bubbles: true }})); if ({key} === 'Enter' && t.form) {{ const b = t.form.querySelector('[type=submit],button:not([type])'); if (b) b.click(); }} return 1;"))?; + p.settle(20); + Ok((json!({"pressed": words[1]}), "✓ Done\n".into())) + } + "get" => { + let what = words.get(1).map(String::as_str).ok_or("get needs what (text, value, html, title, url, attr, count)")?; + let v = match what { + "title" => json!({"title": p_title(p)}), + "url" => json!({"url": p.url}), + "text" | "value" | "html" | "attr" => { + let t = words.get(2).ok_or("get needs a target")?; + let n = p.target(t)?; + let field = match what { + "text" => "return (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim();".to_string(), + "value" => "return String(el.value == null ? '' : el.value);".to_string(), + "html" => "return el.innerHTML;".to_string(), + _ => format!("return el.getAttribute({});", serde_json::to_string(words.get(3).ok_or("get attr needs a name")?).unwrap()), + }; + let r = p.on(n, &field)?; + json!({ what: r }) + } + "count" => { + let sel = serde_json::to_string(words.get(2).ok_or("get count needs a selector")?).unwrap(); + json!({"count": p.js(&format!("return document.querySelectorAll({sel}).length;"))?}) + } + w => return Err(format!("get {w} isn't on the Blitz backend yet")), + }; + let text = v.as_object().and_then(|o| o.values().next()).map(|x| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string())).unwrap_or_default(); + Ok((v, format!("{text}\n"))) + } + "eval" => { + let code = words[1..].join(" "); + let r = p.js(&format!("return (0, eval)({});", serde_json::to_string(&code).unwrap()))?; + p.settle(20); + let text = r.as_str().map(str::to_string).unwrap_or_else(|| r.to_string()); + Ok((json!({"result": r}), format!("{text}\n"))) + } + "screenshot" => { + let path = words.iter().skip(1).find(|w| !w.starts_with('-')).cloned().unwrap_or_else(|| std::env::temp_dir().join(format!("screenshot-{}.png", std::process::id())).display().to_string()); + p.screenshot(&path, words.iter().any(|w| w == "--full" || w == "-f"))?; + Ok((json!({"path": path}), format!("✓ Screenshot saved to {path}\n"))) + } + "wait" => { + let ms = words.get(1).and_then(|w| w.parse::().ok()).unwrap_or(0); + p.settle(ms); + Ok((json!({"waited": ms}), "✓ Done\n".into())) + } + "reload" => { + let url = p.url.clone(); + let fresh = Page::open(&url, allow_network, size)?; + retire(std::mem::replace(p, fresh)); + Ok((json!({"url": url}), "✓ Done\n".into())) + } + v => Err(format!("{v} isn't on the Blitz backend yet (open, snapshot, click, fill, type, select, check, press, get, eval, screenshot, wait, reload, close)")), + })(); + match r { + Ok((d, t)) => ok(d, t), + Err(e) => fail(e), + } + }) +} + +/// A page no longer used: V8 isolates must be dropped newest first, and pages come and go in any order, so a page's +/// isolate is kept (its memory with it) for the life of the Blitz thread rather than dropped out of order. +fn retire(p: Page) { + std::mem::forget(p); +} + +fn p_title(p: &Page) -> String { + let d = p.doc.inner(); + all_nodes(&d).into_iter().find_map(|id| d.get_node(id).filter(|n| tag(n) == "title").map(|n| collapse(&n.text_content()))).unwrap_or_default() +} + diff --git a/browser/src/lib.rs b/browser/src/lib.rs new file mode 100644 index 00000000..1ec825f6 --- /dev/null +++ b/browser/src/lib.rs @@ -0,0 +1,155 @@ +//! raea's browser: agent-browser (vercel-labs, Apache-2.0, vendored as a library: vendor/agent-browser/RAEA-CHANGES) +//! run in this process. `browser.run {args}` takes the same words as the `agent-browser` command line (open URL, +//! snapshot -i, click @e2, fill @e3 TEXT, get text @e1, screenshot PATH, eval JS, diff ..., batch ...), executes them on +//! one daemon state kept for the process (its browser stays open between calls, as the daemon's does), and answers the +//! daemon's response with the text the command line would print. The browser is Chrome over CDP (agent-browser's own +//! launch and discovery); the Blitz backend answers the same words without Chrome. + +pub mod blitz; + +#[cfg(feature = "chrome")] +use std::sync::OnceLock; + +#[cfg(feature = "chrome")] +use agent_browser::connection::Response; +#[cfg(feature = "chrome")] +use agent_browser::native::actions::{DaemonState, execute_command}; +use serde_json::{Value, json}; + +#[cfg(feature = "chrome")] +fn runtime() -> &'static tokio::runtime::Runtime { + static RT: OnceLock = OnceLock::new(); + RT.get_or_init(|| tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().thread_name("raea-browser").build().expect("a tokio runtime")) +} + +#[cfg(feature = "chrome")] +/// One daemon state per session (agent-browser runs a daemon per session; here they share the process). +fn state(session: &str) -> std::sync::Arc> { + static ST: OnceLock>>>> = OnceLock::new(); + let mut m = ST.get_or_init(Default::default).lock().unwrap(); + m.entry(session.to_string()).or_insert_with(|| std::sync::Arc::new(tokio::sync::Mutex::new(DaemonState::new()))).clone() +} + +/// Which backend answers: `--engine blitz` (or no Chrome in this build) is raea's own; anything else is Chrome. +fn blitz_wanted(args: &[String]) -> bool { + !cfg!(feature = "chrome") || args.windows(2).any(|w| w[0] == "--engine" && w[1] == "blitz") +} + +/// `batch CMD...` on either backend: each command's words run in turn, stopping at a failure with --bail. +fn batch(args: &[String]) -> Option> { + let pos = args.iter().position(|a| a == "batch")?; + if args[..pos].iter().any(|a| !a.starts_with('-') && !args[..pos].windows(2).any(|w| w[1] == *a && w[0].starts_with("--"))) { + return None; + } + let prefix: Vec = args[..pos].to_vec(); + let rest = &args[pos + 1..]; + let bail = rest.iter().any(|a| a == "--bail"); + let mut results = Vec::new(); + let mut text = String::new(); + let mut ok = true; + for c in rest.iter().filter(|a| *a != "--bail") { + let mut words = prefix.clone(); + words.extend(split_words(c)); + let r = run(&words).unwrap_or_else(|e| json!({"success": false, "error": e, "text": format!("{e}\n")})); + text.push_str(r["text"].as_str().unwrap_or("")); + let good = r["success"].as_bool().unwrap_or(false); + results.push(json!({"command": c, "result": r})); + if !good { + ok = false; + if bail { + break; + } + } + } + Some(Ok(json!({"success": ok, "data": {"results": results}, "error": if ok { Value::Null } else { json!("a command in the batch failed") }, "code": Value::Null, "text": text}))) +} + +/// Shell-style words: quotes group, backslashes escape. +fn split_words(s: &str) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + let mut q: Option = None; + let mut any = false; + let mut chars = s.chars(); + while let Some(c) = chars.next() { + match (q, c) { + (None, '"' | '\'') => { + q = Some(c); + any = true; + } + (Some(x), c) if c == x => q = None, + (_, '\\') => { + if let Some(n) = chars.next() { + cur.push(n); + } + } + (None, c) if c.is_whitespace() => { + if !cur.is_empty() || any { + out.push(std::mem::take(&mut cur)); + any = false; + } + } + (_, c) => cur.push(c), + } + } + if !cur.is_empty() || any { + out.push(cur); + } + out +} + +/// One command line's words run in process: the backend's response and the command line's text. +pub fn run(args: &[String]) -> Result { + if let Some(r) = batch(args) { + return r; + } + if blitz_wanted(args) { + return blitz::run(args); + } + #[cfg(feature = "chrome")] + return chrome(args); + #[cfg(not(feature = "chrome"))] + unreachable!() +} + +#[cfg(feature = "chrome")] +fn chrome(args: &[String]) -> Result { + let flags = agent_browser::flags::parse_flags(args); + let clean = agent_browser::flags::clean_args(args); + let cmd = agent_browser::commands::parse_command(&clean, &flags).map_err(|e| e.format())?; + let action = cmd.get("action").and_then(Value::as_str).map(str::to_string); + // state files (save/load) are local, as the command line handles them + let resp: Value = if let Some(r) = agent_browser::native::state::dispatch_state_command(&cmd) { + match r { + Ok(data) => json!({"success": true, "data": data}), + Err(e) => json!({"success": false, "error": e}), + } + } else { + runtime().block_on(async { + let st = state(&flags.session); + let mut st = st.lock().await; + execute_command(&cmd, &mut st).await + }) + }; + let typed: Response = serde_json::from_value(resp.clone()).map_err(|e| format!("agent-browser answered something unexpected: {e}"))?; + let opts = agent_browser::output::OutputOptions::from_flags(&flags); + let text = match raea_native::capture(&std::env::current_dir().unwrap_or_default(), || agent_browser::output::print_response_with_opts(&typed, action.as_deref(), &opts)) { + Ok(((), out, err)) => format!("{out}{err}"), + Err(e) => e, + }; + Ok(json!({"success": typed.success, "data": typed.data, "error": typed.error, "code": typed.code, "text": text})) +} + +/// The browser.* calls in raea-native's registry. +pub fn register() { + raea_native::register( + "browser.run", + "{ args: string[] }", + "{ success: boolean; data: unknown; error: string | null; code: string | null; text: string }", + "agent-browser's command line words run in process (Chrome over CDP, or --engine blitz: raea's own engine): the response and the printed text", + |v| { + let args: Vec = v.get("args").and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default(); + run(&args) + }, + ); +} diff --git a/browser/ts/index.ts b/browser/ts/index.ts new file mode 100644 index 00000000..c37ce0e5 --- /dev/null +++ b/browser/ts/index.ts @@ -0,0 +1,100 @@ +// @raea/browser: a browser the agent drives, typed. Each call is agent-browser's command line words run in process +// (raea-browser, `browser.run`): Chrome over CDP on the Mac. Snapshots name elements by ref (e1, e2, ...), and the +// other verbs take a ref ("@e2") or a selector. Every call answers the daemon's response; `text` is what the command +// line would print, for the agent to read. +import { native } from "@raea/motion/native"; + +export interface BrowserResult { + success: boolean; + data: T; + error: string | null; + code: string | null; + text: string; +} +export interface SnapshotOptions { + /** interactive elements only (buttons, inputs, links) */ + interactive?: boolean; + /** drop empty structural elements */ + compact?: boolean; + depth?: number; + /** scope to a CSS selector */ + selector?: string; + urls?: boolean; +} +export interface ScreenshotOptions { + full?: boolean; + /** numbered labels on interactive elements ([N] is @eN) */ + annotate?: boolean; + format?: "png" | "jpeg"; + quality?: number; +} + +function run(args: (string | number | undefined | false)[]): BrowserResult { + const words = args.filter((a): a is string | number => a !== undefined && a !== false).map(String); + const r = native("browser.run" as never, { args: words } as never) as BrowserResult; + return r; +} +function must(r: BrowserResult): BrowserResult { + if (!r.success) throw new Error(r.error ?? r.text.trim() ?? "the browser refused"); + return r; +} + +/** The browser (one per process, as agent-browser's daemon keeps one; `session` names an isolated one). */ +export class Browser { + constructor(readonly session?: string) {} + private words(...a: (string | number | undefined | false)[]) { + return this.session ? ["--session", this.session, ...a] : a; + } + /** Any command line words, as `agent-browser WORDS...` takes them; the result unchecked. */ + raw(...words: string[]): BrowserResult { + return run(this.words(...words)); + } + open(url?: string) { + return must(run(this.words("open", url))); + } + /** The accessibility tree with refs; `refs` maps each ref to its role and name. */ + snapshot(o: SnapshotOptions = {}) { + return must(run<{ snapshot: string; refs: Record }>(this.words("snapshot", o.interactive && "-i", o.compact && "-c", o.depth !== undefined && "-d", o.depth, o.selector && "-s", o.selector, o.urls && "--urls"))); + } + click(target: string) { + return must(run(this.words("click", target))); + } + fill(target: string, text: string) { + return must(run(this.words("fill", target, text))); + } + type(target: string, text: string) { + return must(run(this.words("type", target, text))); + } + press(key: string) { + return must(run(this.words("press", key))); + } + hover(target: string) { + return must(run(this.words("hover", target))); + } + /** text, html, value, title, url, count, box, or an attribute (`get("attr", "@e1", "href")`) */ + get(what: string, target?: string, extra?: string) { + return must(run(this.words("get", what, target, extra))); + } + screenshot(path?: string, o: ScreenshotOptions = {}) { + return must(run(this.words("screenshot", path, o.full && "--full", o.annotate && "--annotate", o.format && "--screenshot-format", o.format, o.quality !== undefined && "--screenshot-quality", o.quality))); + } + eval(js: string) { + return must(run(this.words("eval", js))); + } + /** diff snapshot | screenshot --baseline FILE | url A B */ + diff(...words: string[]) { + return run(this.words("diff", ...words)); + } + /** several commands in one call, each its own words */ + batch(commands: string[][], bail = false) { + return run(this.words("batch", bail && "--bail", ...commands.map((c) => c.map((w) => (/[\s"']/.test(w) ? JSON.stringify(w) : w)).join(" ")))); + } + wait(...words: string[]) { + return must(run(this.words("wait", ...words))); + } + close() { + return run(this.words("close")); + } +} + +export const browser = new Browser(); diff --git a/browser/vendor/agent-browser/LICENSE b/browser/vendor/agent-browser/LICENSE new file mode 100644 index 00000000..8226d363 --- /dev/null +++ b/browser/vendor/agent-browser/LICENSE @@ -0,0 +1,201 @@ + 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 2025 Vercel Inc. + +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. diff --git a/browser/vendor/agent-browser/RAEA-CHANGES b/browser/vendor/agent-browser/RAEA-CHANGES new file mode 100644 index 00000000..73a2c1da --- /dev/null +++ b/browser/vendor/agent-browser/RAEA-CHANGES @@ -0,0 +1,9 @@ +agent-browser, vendored into raea from https://github.com/vercel-labs/agent-browser at commit dac13bb (version 0.39.1, +2026-10-15), Apache-2.0 (LICENSE beside this file). Only cli/ is kept (its tests/ removed), plus an empty +packages/dashboard/out/ that its build script expects. + +raea's changes, all in cli/: +- src/lib.rs (new): the crate's modules as a library, so raea-browser runs the daemon's command execution in process. +- Cargo.toml: `autobins = false`, a `[lib]` section, an empty `[workspace]` (it builds on its own inside raea), and + the release profiles removed (the host workspace sets them). +Nothing else is modified. diff --git a/browser/vendor/agent-browser/cli/Cargo.lock b/browser/vendor/agent-browser/cli/Cargo.lock new file mode 100644 index 00000000..a7917b31 --- /dev/null +++ b/browser/vendor/agent-browser/cli/Cargo.lock @@ -0,0 +1,3308 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "agent-browser" +version = "0.39.1" +dependencies = [ + "aes-gcm", + "async-trait", + "base64", + "chrono", + "dirs", + "futures-util", + "getrandom 0.2.17", + "hex", + "hmac", + "image", + "libc", + "reqwest", + "rust-embed", + "rustls", + "rustls-native-certs", + "rustls-pemfile", + "serde", + "serde_json", + "sha2", + "similar", + "socket2", + "tempfile", + "time", + "tokio", + "tokio-tungstenite", + "url", + "urlencoding", + "uuid", + "webpki-roots 0.26.11", + "windows-sys 0.52.0", + "zip", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror 2.0.18", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375082f007bd67184fb9c0374614b29f9aaa604ec301635f72338bb65386a53d" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "bitstream-io" +version = "4.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60d4bd9d1db2c6bdf285e223a7fa369d5ce98ec767dec949c6ca62863ce61757" +dependencies = [ + "core2", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "built" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4ad8f11f288f48ca24471bbd51ac257aaeaaa07adae295591266b792902ae64" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytemuck" +version = "1.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b49ba7ef1ad6107f8824dbe97de947cbaac53c44e7f9756a1fba0d37c1eec505" +dependencies = [ + "memchr", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "data-encoding" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "exr" +version = "1.74.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4300e043a56aa2cb633c01af81ca8f699a321879a7854d3896a0ba89056363be" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "fax" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05de7d48f37cd6730705cbca900770cab77a89f413d23e100ad7fad7795a0ab" +dependencies = [ + "fax_derive", +] + +[[package]] +name = "fax_derive" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0aca10fb742cb43f9e7bb8467c91aa9bcb8e3ffbc6a6f7389bb93ffc920577d" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core 0.10.1", + "wasip2", + "wasip3", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "gif" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5df2ba84018d80c213569363bdcd0c64e6933c67fe4c1d60ecf822971a3c35e" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "pin-utils", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.5", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6506c6c10786659413faa717ceebcb8f70731c0a60cbae39795fdf114519c1a" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core 0.5.1", + "zune-jpeg 0.5.12", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imgref" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c5cedc30da3a610cac6b4ba17597bdf7152cf974e8aab3afb3d54455e371c8" + +[[package]] +name = "indexmap" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libc" +version = "0.2.180" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f12a681b7dd8ce12bff52488013ba614b869148d54dd79836ab85aafdd53f08d" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libredox" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" +dependencies = [ + "bitflags", + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac9557c559cd6fc9867e122e20d2cbefc9ca29d80d027a8e39310920ed2f0a97" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "535d180e0ecab6268a3e718bb9fd44db66bbbc256257165fc699dadf70d16fe7" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52717f9a02b6965224f95ca2a81e2e0c5c43baacd28ca057577988930b6c3d5b" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "pxfm" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5a041e753da8b807c9255f28de81879c78c876392ff2469cde94799b2896b9d" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +dependencies = [ + "bytes", + "getrandom 0.4.1", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + +[[package]] +name = "quote" +version = "1.0.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74d9a594b72ae6656596548f56f667211f8a97b3d4c3d467150794690dc40a" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.1", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.2", + "rand_chacha 0.9.0", + "simd_helpers", + "thiserror 2.0.18", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef69c1990ceef18a116855938e74793a5f7496ee907562bd0857b6ac734ab285" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "rayon" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots 1.0.5", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rust-embed" +version = "8.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04113cb9355a377d83f06ef1f0a45b8ab8cd7d8b1288160717d66df5c7988d27" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0902e4c7c8e997159ab384e6d0fc91c221375f6894346ae107f47dd0f3ccaa" +dependencies = [ + "proc-macro2", + "quote", + "rust-embed-utils", + "syn", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bcdef0be6fe7f6fa333b1073c949729274b05f123a0ad7efcb8efd878e5c3b1" +dependencies = [ + "sha2", + "walkdir", +] + +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[package]] +name = "rustix" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tempfile" +version = "3.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1" +dependencies = [ + "fastrand", + "getrandom 0.4.1", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tiff" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af9605de7fee8d9551863fd692cce7637f548dbd9db9180fcc07ccc6d26c336f" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg 0.4.21", +] + +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.8.5", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror 1.0.69", + "utf-8", +] + +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "unicode-ident" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b672338555252d43fd2240c714dc444b8c6fb0a5c5335e65a07bba7742735ddb" +dependencies = [ + "getrandom 0.4.1", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" +dependencies = [ + "cfg-if", + "futures-util", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.5", +] + +[[package]] +name = "webpki-roots" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12bed680863276c63889429bfd6cab3b99943659923822de1c8a39c49e4d722c" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a789c6e490b576db9f7e6b6d661bcc9799f7c0ac8352f56ea20193b2681532e5" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f65c489a7071a749c849713807783f70672b28094011623e200cb86dcb835953" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zip" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b680f2a0cd479b4cff6e1233c483fdead418106eae419dc60200ae9850f6d004" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "typed-path", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513" + +[[package]] +name = "zmij" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc5a66a20078bf1251bde995aa2fdcc4b800c70b5d92dd2c62abc5c60f679f8" + +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zune-core" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a" + +[[package]] +name = "zune-core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713" +dependencies = [ + "zune-core 0.4.12", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "410e9ecef634c709e3831c2cfdb8d9c32164fae1c67496d5b68fff728eec37fe" +dependencies = [ + "zune-core 0.5.1", +] diff --git a/browser/vendor/agent-browser/cli/Cargo.toml b/browser/vendor/agent-browser/cli/Cargo.toml new file mode 100644 index 00000000..9f03503c --- /dev/null +++ b/browser/vendor/agent-browser/cli/Cargo.toml @@ -0,0 +1,66 @@ +[package] +name = "agent-browser" +autobins = false +version = "0.39.1" +edition = "2021" +description = "Fast browser automation CLI for AI agents" +license = "Apache-2.0" +repository = "https://github.com/vercel-labs/agent-browser" +homepage = "https://agent-browser.dev" +readme = "../README.md" +keywords = ["browser", "automation", "ai", "cdp", "chrome"] +categories = ["command-line-utilities", "web-programming"] + +# (raea) a library for an in-process host: the daemon's command execution without its socket or CLI +[lib] +name = "agent_browser" +path = "src/lib.rs" + +[dependencies] +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +dirs = "5.0" +base64 = "0.22" +getrandom = "0.2" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "time", "sync", "signal", "process"] } +tokio-tungstenite = { version = "0.24", features = ["rustls-tls-webpki-roots"] } +rustls = { version = "0.23", default-features = false } +rustls-native-certs = "0.8" +rustls-pemfile = "2" +webpki-roots = "0.26" +futures-util = "0.3" +url = "2" +uuid = { version = "1", features = ["v4"] } +image = "0.25" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-webpki-roots", "stream"] } +sha2 = "0.10" +aes-gcm = "0.10" +async-trait = "0.1" +socket2 = "0.6" +similar = "2" +zip = { version = "8.2.0", default-features = false, features = ["deflate"] } +time = { version = "0.3", features = ["formatting"] } +hmac = "0.12" +hex = "0.4" +chrono = "0.4" +urlencoding = "2" +rust-embed = "8" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.52", features = ["Win32_System_Threading", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_JobObjects", "Win32_System_StationsAndDesktops", "Win32_Graphics_Gdi"] } + +[dev-dependencies] +tempfile = "3" + +[build-dependencies] +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" + + + +# Keep image processing real-time while application code remains debuggable. + +[workspace] diff --git a/browser/vendor/agent-browser/cli/build.rs b/browser/vendor/agent-browser/cli/build.rs new file mode 100644 index 00000000..7bc9cf10 --- /dev/null +++ b/browser/vendor/agent-browser/cli/build.rs @@ -0,0 +1,498 @@ +use std::collections::HashSet; +use std::env; +use std::fs; +use std::path::Path; + +/// Ensure `packages/dashboard/out/` exists so `rust-embed` doesn't fail during +/// Rust-only dev builds where the dashboard hasn't been built. The placeholder +/// `index.html` is only written when the directory is completely absent. +fn ensure_dashboard_dir() { + let dashboard_out = Path::new("../packages/dashboard/out"); + println!("cargo:rerun-if-changed=../packages/dashboard/out"); + if !dashboard_out.join("index.html").exists() { + let _ = fs::create_dir_all(dashboard_out); + let _ = fs::write( + dashboard_out.join("index.html"), + "

Dashboard not built. Run: cd packages/dashboard && pnpm build

\n", + ); + } +} + +fn main() { + ensure_dashboard_dir(); + + let protocol_dir = Path::new("cdp-protocol"); + let out_dir = env::var("OUT_DIR").unwrap(); + let out_path = Path::new(&out_dir).join("cdp_generated.rs"); + + let browser_path = protocol_dir.join("browser_protocol.json"); + let js_path = protocol_dir.join("js_protocol.json"); + + if !browser_path.exists() && !js_path.exists() { + fs::write( + &out_path, + "// No protocol JSON files found in cdp-protocol/\n", + ) + .unwrap(); + return; + } + + let mut all_domains: Vec = Vec::new(); + + for path in [&browser_path, &js_path] { + if !path.exists() { + continue; + } + println!("cargo:rerun-if-changed={}", path.display()); + let content = fs::read_to_string(path).unwrap(); + let protocol: ProtocolSpec = match serde_json::from_str(&content) { + Ok(p) => p, + Err(e) => { + eprintln!("cargo:warning=Failed to parse {}: {}", path.display(), e); + continue; + } + }; + all_domains.extend(protocol.domains); + } + + // Collect all known type IDs per domain for cross-domain resolution + let mut domain_types: std::collections::HashMap> = + std::collections::HashMap::new(); + for domain in &all_domains { + let mut types = HashSet::new(); + for td in &domain.types { + types.insert(td.id.clone()); + } + domain_types.insert(domain.domain.clone(), types); + } + + // Known recursive struct fields that need Box wrapping + let recursive_fields: HashSet<(&str, &str, &str)> = [ + ("DOM", "Node", "contentDocument"), + ("DOM", "Node", "templateContent"), + ("DOM", "Node", "importedDocument"), + ("Accessibility", "AXNode", "sources"), + ("Runtime", "StackTrace", "parent"), + ] + .into_iter() + .collect(); + + let mut output = String::new(); + output.push_str("use serde::{Deserialize, Serialize};\n\n"); + + for domain in &all_domains { + generate_domain(domain, &domain_types, &recursive_fields, &mut output); + } + + fs::write(&out_path, &output).unwrap(); +} + +#[allow(dead_code)] +#[derive(serde::Deserialize)] +struct ProtocolSpec { + domains: Vec, +} + +#[allow(dead_code)] +#[derive(serde::Deserialize, Clone)] +struct Domain { + domain: String, + #[serde(default)] + types: Vec, + #[serde(default)] + commands: Vec, + #[serde(default)] + events: Vec, +} + +#[allow(dead_code)] +#[derive(serde::Deserialize, Clone)] +struct TypeDef { + id: String, + #[serde(rename = "type", default)] + type_kind: String, + #[serde(default)] + properties: Vec, + #[serde(rename = "enum", default)] + enum_values: Vec, + #[serde(default)] + description: Option, +} + +#[allow(dead_code)] +#[derive(serde::Deserialize, Clone)] +struct Command { + name: String, + #[serde(default)] + parameters: Vec, + #[serde(default)] + returns: Vec, + #[serde(default)] + description: Option, +} + +#[allow(dead_code)] +#[derive(serde::Deserialize, Clone)] +struct Event { + name: String, + #[serde(default)] + parameters: Vec, + #[serde(default)] + description: Option, +} + +#[allow(dead_code)] +#[derive(serde::Deserialize, Clone)] +struct Property { + name: String, + #[serde(rename = "type", default)] + type_kind: Option, + #[serde(rename = "$ref", default)] + ref_type: Option, + #[serde(default)] + optional: bool, + #[serde(default)] + description: Option, + #[serde(default)] + items: Option>, + #[serde(rename = "enum", default)] + enum_values: Vec, +} + +#[allow(dead_code)] +#[derive(serde::Deserialize, Clone)] +struct ItemType { + #[serde(rename = "type", default)] + type_kind: Option, + #[serde(rename = "$ref", default)] + ref_type: Option, +} + +fn to_pascal_case(s: &str) -> String { + let mut result = String::new(); + let mut capitalize = true; + for c in s.chars() { + if c == '_' || c == '-' || c == '.' { + capitalize = true; + } else if capitalize { + result.push(c.to_ascii_uppercase()); + capitalize = false; + } else { + result.push(c); + } + } + result +} + +fn to_snake_case(s: &str) -> String { + let mut result = String::new(); + let chars: Vec = s.chars().collect(); + for (i, &c) in chars.iter().enumerate() { + if c.is_uppercase() && i > 0 { + // Only insert underscore at transitions from lowercase to uppercase, + // or when an uppercase sequence ends (e.g. "DOM" -> "dom", not "d_o_m") + let prev_upper = chars[i - 1].is_uppercase(); + let next_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase()); + if !prev_upper || next_lower { + result.push('_'); + } + } + result.push(c.to_ascii_lowercase()); + } + result +} + +/// Resolve a $ref type reference. Cross-domain refs like "Page.FrameId" become +/// `super::cdp_page::FrameId`. Same-domain refs are used directly. +fn resolve_ref( + r: &str, + current_domain: &str, + domain_types: &std::collections::HashMap>, +) -> String { + let parts: Vec<&str> = r.split('.').collect(); + if parts.len() == 2 { + let ref_domain = parts[0]; + let ref_type = parts[1]; + if ref_domain == current_domain { + to_pascal_case(ref_type) + } else { + // Check if this type actually exists in the referenced domain + if domain_types + .get(ref_domain) + .is_some_and(|t| t.contains(ref_type)) + { + format!( + "super::cdp_{}::{}", + to_snake_case(ref_domain), + to_pascal_case(ref_type) + ) + } else { + // Fall back to serde_json::Value for unknown cross-domain refs + "serde_json::Value".to_string() + } + } + } else { + to_pascal_case(r) + } +} + +fn map_type_in_domain( + prop: &Property, + current_domain: &str, + domain_types: &std::collections::HashMap>, +) -> String { + if let Some(ref r) = prop.ref_type { + let type_name = resolve_ref(r, current_domain, domain_types); + if prop.optional { + format!("Option<{}>", type_name) + } else { + type_name + } + } else if let Some(ref t) = prop.type_kind { + let base = match t.as_str() { + "string" => "String".to_string(), + "integer" => "i64".to_string(), + "number" => "f64".to_string(), + "boolean" => "bool".to_string(), + "object" => "serde_json::Value".to_string(), + "any" => "serde_json::Value".to_string(), + "array" => { + if let Some(ref items) = prop.items { + let inner = if let Some(ref r) = items.ref_type { + resolve_ref(r, current_domain, domain_types) + } else { + match items.type_kind.as_deref().unwrap_or("any") { + "string" => "String".to_string(), + "integer" => "i64".to_string(), + "number" => "f64".to_string(), + "boolean" => "bool".to_string(), + _ => "serde_json::Value".to_string(), + } + }; + format!("Vec<{}>", inner) + } else { + "Vec".to_string() + } + } + _ => "serde_json::Value".to_string(), + }; + if prop.optional { + format!("Option<{}>", base) + } else { + base + } + } else if prop.optional { + "Option".to_string() + } else { + "serde_json::Value".to_string() + } +} + +fn is_rust_keyword(s: &str) -> bool { + matches!( + s, + "type" + | "self" + | "Self" + | "super" + | "move" + | "ref" + | "fn" + | "mod" + | "use" + | "pub" + | "let" + | "mut" + | "const" + | "static" + | "if" + | "else" + | "for" + | "while" + | "loop" + | "match" + | "return" + | "break" + | "continue" + | "as" + | "in" + | "impl" + | "trait" + | "struct" + | "enum" + | "where" + | "async" + | "await" + | "dyn" + | "box" + | "yield" + | "override" + | "crate" + | "extern" + ) +} + +fn generate_domain( + domain: &Domain, + domain_types: &std::collections::HashMap>, + recursive_fields: &HashSet<(&str, &str, &str)>, + output: &mut String, +) { + let mod_name = to_snake_case(&domain.domain); + output.push_str(&format!( + "#[allow(dead_code, non_snake_case, non_camel_case_types, clippy::enum_variant_names)]\npub mod cdp_{} {{\n", + mod_name + )); + output.push_str(" use super::*;\n\n"); + + for type_def in &domain.types { + if !type_def.enum_values.is_empty() { + // Deduplicate enum variants (some CDP enums have duplicated PascalCase forms) + let mut seen_variants = HashSet::new(); + output.push_str(" #[derive(Debug, Clone, Serialize, Deserialize)]\n"); + output.push_str(&format!(" pub enum {} {{\n", type_def.id)); + for val in &type_def.enum_values { + let mut variant = to_pascal_case(val); + if variant == "Self" { + variant = "SelfValue".to_string(); + } + if variant.chars().next().is_some_and(|c| c.is_ascii_digit()) { + variant = format!("V{}", variant); + } + if seen_variants.insert(variant.clone()) { + output.push_str(&format!( + " #[serde(rename = \"{}\")]\n {},\n", + val, variant + )); + } + } + output.push_str(" }\n\n"); + } else if type_def.type_kind == "object" && !type_def.properties.is_empty() { + output.push_str( + " #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(rename_all = \"camelCase\")]\n", + ); + output.push_str(&format!(" pub struct {} {{\n", type_def.id)); + for prop in &type_def.properties { + let field_name = to_snake_case(&prop.name); + let field_name = if is_rust_keyword(&field_name) { + format!("r#{}", field_name) + } else { + field_name + }; + let mut rust_type = map_type_in_domain(prop, &domain.domain, domain_types); + + // Wrap recursive fields in Box + if recursive_fields.contains(&( + domain.domain.as_str(), + type_def.id.as_str(), + prop.name.as_str(), + )) { + if rust_type.starts_with("Option<") { + let inner = &rust_type[7..rust_type.len() - 1]; + rust_type = format!("Option>", inner); + } else { + rust_type = format!("Box<{}>", rust_type); + } + } + + if prop.optional { + output + .push_str(" #[serde(skip_serializing_if = \"Option::is_none\")]\n"); + } + output.push_str(&format!(" pub {}: {},\n", field_name, rust_type)); + } + output.push_str(" }\n\n"); + } else if type_def.type_kind == "object" && type_def.properties.is_empty() { + output.push_str(&format!( + " pub type {} = serde_json::Value;\n\n", + type_def.id + )); + } else if type_def.type_kind == "array" { + output.push_str(&format!( + " pub type {} = Vec;\n\n", + type_def.id + )); + } else if type_def.type_kind == "string" && type_def.enum_values.is_empty() { + output.push_str(&format!(" pub type {} = String;\n\n", type_def.id)); + } else if type_def.type_kind == "integer" { + output.push_str(&format!(" pub type {} = i64;\n\n", type_def.id)); + } else if type_def.type_kind == "number" { + output.push_str(&format!(" pub type {} = f64;\n\n", type_def.id)); + } + } + + for cmd in &domain.commands { + let pascal_name = to_pascal_case(&cmd.name); + + if !cmd.parameters.is_empty() { + output.push_str( + " #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(rename_all = \"camelCase\")]\n", + ); + output.push_str(&format!(" pub struct {}Params {{\n", pascal_name)); + for param in &cmd.parameters { + let field_name = to_snake_case(¶m.name); + let field_name = if is_rust_keyword(&field_name) { + format!("r#{}", field_name) + } else { + field_name + }; + let rust_type = map_type_in_domain(param, &domain.domain, domain_types); + if param.optional { + output + .push_str(" #[serde(skip_serializing_if = \"Option::is_none\")]\n"); + } + output.push_str(&format!(" pub {}: {},\n", field_name, rust_type)); + } + output.push_str(" }\n\n"); + } + + if !cmd.returns.is_empty() { + output.push_str( + " #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(rename_all = \"camelCase\")]\n", + ); + output.push_str(&format!(" pub struct {}Result {{\n", pascal_name)); + for ret in &cmd.returns { + let field_name = to_snake_case(&ret.name); + let field_name = if is_rust_keyword(&field_name) { + format!("r#{}", field_name) + } else { + field_name + }; + let rust_type = map_type_in_domain(ret, &domain.domain, domain_types); + if ret.optional { + output + .push_str(" #[serde(skip_serializing_if = \"Option::is_none\")]\n"); + } + output.push_str(&format!(" pub {}: {},\n", field_name, rust_type)); + } + output.push_str(" }\n\n"); + } + } + + for event in &domain.events { + if !event.parameters.is_empty() { + let pascal_name = to_pascal_case(&event.name); + output.push_str( + " #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(rename_all = \"camelCase\")]\n", + ); + output.push_str(&format!(" pub struct {}Event {{\n", pascal_name)); + for param in &event.parameters { + let field_name = to_snake_case(¶m.name); + let field_name = if is_rust_keyword(&field_name) { + format!("r#{}", field_name) + } else { + field_name + }; + let rust_type = map_type_in_domain(param, &domain.domain, domain_types); + if param.optional { + output + .push_str(" #[serde(skip_serializing_if = \"Option::is_none\")]\n"); + } + output.push_str(&format!(" pub {}: {},\n", field_name, rust_type)); + } + output.push_str(" }\n\n"); + } + } + + output.push_str("}\n\n"); +} diff --git a/browser/vendor/agent-browser/cli/cdp-protocol/browser_protocol.json b/browser/vendor/agent-browser/cli/cdp-protocol/browser_protocol.json new file mode 100644 index 00000000..0ff2f796 --- /dev/null +++ b/browser/vendor/agent-browser/cli/cdp-protocol/browser_protocol.json @@ -0,0 +1,31262 @@ +{ + "version": { + "major": "1", + "minor": "3" + }, + "domains": [ + { + "domain": "Accessibility", + "experimental": true, + "dependencies": [ + "DOM" + ], + "types": [ + { + "id": "AXNodeId", + "description": "Unique accessibility node identifier.", + "type": "string" + }, + { + "id": "AXValueType", + "description": "Enum of possible property types.", + "type": "string", + "enum": [ + "boolean", + "tristate", + "booleanOrUndefined", + "idref", + "idrefList", + "integer", + "node", + "nodeList", + "number", + "string", + "computedString", + "token", + "tokenList", + "domRelation", + "role", + "internalRole", + "valueUndefined" + ] + }, + { + "id": "AXValueSourceType", + "description": "Enum of possible property sources.", + "type": "string", + "enum": [ + "attribute", + "implicit", + "style", + "contents", + "placeholder", + "relatedElement" + ] + }, + { + "id": "AXValueNativeSourceType", + "description": "Enum of possible native property sources (as a subtype of a particular AXValueSourceType).", + "type": "string", + "enum": [ + "description", + "figcaption", + "label", + "labelfor", + "labelwrapped", + "legend", + "rubyannotation", + "tablecaption", + "title", + "other" + ] + }, + { + "id": "AXValueSource", + "description": "A single source for a computed AX property.", + "type": "object", + "properties": [ + { + "name": "type", + "description": "What type of source this is.", + "$ref": "AXValueSourceType" + }, + { + "name": "value", + "description": "The value of this property source.", + "optional": true, + "$ref": "AXValue" + }, + { + "name": "attribute", + "description": "The name of the relevant attribute, if any.", + "optional": true, + "type": "string" + }, + { + "name": "attributeValue", + "description": "The value of the relevant attribute, if any.", + "optional": true, + "$ref": "AXValue" + }, + { + "name": "superseded", + "description": "Whether this source is superseded by a higher priority source.", + "optional": true, + "type": "boolean" + }, + { + "name": "nativeSource", + "description": "The native markup source for this value, e.g. a `
+ diff --git a/engine/react/probe/ls.html b/engine/react/probe/ls.html new file mode 100644 index 00000000..5b19a84e --- /dev/null +++ b/engine/react/probe/ls.html @@ -0,0 +1,10 @@ + +
+
Launch plan
+
Launch plan
+
Launch plan
+
Launch plan
+
Launch plan
+
+ diff --git a/engine/react/probe/tw.html b/engine/react/probe/tw.html new file mode 100644 index 00000000..dee6564a --- /dev/null +++ b/engine/react/probe/tw.html @@ -0,0 +1,23 @@ + +
+

Launch plan

Tasks +
+ \ No newline at end of file diff --git a/engine/react/probe/vals.html b/engine/react/probe/vals.html new file mode 100644 index 00000000..d85d33c5 --- /dev/null +++ b/engine/react/probe/vals.html @@ -0,0 +1,19 @@ + +
hello world
+ diff --git a/engine/scripts/build-dylib.sh b/engine/scripts/build-dylib.sh new file mode 100755 index 00000000..b9ac9623 --- /dev/null +++ b/engine/scripts/build-dylib.sh @@ -0,0 +1,21 @@ +#!/bin/zsh +# Builds libraea.dylib: the C API (include/raea.h) as a dynamic library, for engines that +# embed raea's html nodes (moonsplice links it this way, from its own target directory). +# +# scripts/build-dylib.sh default features (network, skia, ffmpeg, intl, webgl) +# FEATURES=v8 scripts/build-dylib.sh plus scripts on V8 (Mac only) +# OUT=dir scripts/build-dylib.sh copy the dylib and header to dir (default target/dylib) +# +# The crate stays an rlib in Cargo.toml; `cargo rustc --crate-type cdylib` builds the dylib next to it +# (as scripts/build-xcframework.sh does for the staticlib). Its install name is @rpath/libraea.dylib. +set -euo pipefail +cd "$(dirname "$0")/.." +export PATH="$HOME/.cargo/bin:$PATH" +feat=() +[[ -n ${FEATURES:-} ]] && feat=(--features $FEATURES) +cargo rustc --release --lib $feat --crate-type cdylib +out=${OUT:-target/dylib} +mkdir -p $out +cp target/release/libraea.dylib include/raea.h $out/ +install_name_tool -id @rpath/libraea.dylib $out/libraea.dylib +echo "$out/libraea.dylib" diff --git a/engine/scripts/build-xcframework.sh b/engine/scripts/build-xcframework.sh new file mode 100755 index 00000000..e4451b85 --- /dev/null +++ b/engine/scripts/build-xcframework.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +# Build raea.xcframework: libraea.a for iOS devices (arm64) and the iOS +# Simulator (arm64), plus include/raea.h and a module map (`import raea`). +# +# scripts/build-xcframework.sh iOS feature set: no network, no skia, no ffmpeg +# RAEA_FEATURES=skia,network scripts/build-xcframework.sh +# RAEA_MACOS=1 scripts/build-xcframework.sh also a macOS (arm64) slice, same features +# RAEA_SIM_X86=1 ... also x86_64 in the simulator slice (Intel Macs) +# IPHONEOS_DEPLOYMENT_TARGET=16.0 (default) minimum iOS +# +# Output: target/xcframework/raea.xcframework (+ .native-static-libs.txt: what an +# app links besides the .a; the module maps carry the same list for Swift autolinking) +set -euo pipefail +cd "$(dirname "$0")/.." + +export PATH="$HOME/.cargo/bin:$PATH" # rustup's cargo/rustc (the iOS std lives there, not in Homebrew's) +export IPHONEOS_DEPLOYMENT_TARGET="${IPHONEOS_DEPLOYMENT_TARGET:-16.0}" +export MACOSX_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-13.0}" +FEATURES="${RAEA_FEATURES:-}" +OUT=target/xcframework +HEADERS="$OUT/headers" + +targets=(aarch64-apple-ios aarch64-apple-ios-sim) +[[ -n "${RAEA_SIM_X86:-}" ]] && targets+=(x86_64-apple-ios) +[[ -n "${RAEA_MACOS:-}" ]] && targets+=(aarch64-apple-darwin) +rustup target add "${targets[@]}" >/dev/null + +rm -rf "$OUT" +mkdir -p "$OUT" +for t in "${targets[@]}"; do + echo "== $t: cargo rustc --lib --features '$FEATURES'" >&2 + # --print native-static-libs: the system libraries this slice needs (cargo replays the note + # when the crate is already built); they go into the slice's module map for autolinking. + # --crate-type staticlib alone: built together with the rlib, the archive also carries every + # dependency's embedded LLVM bitcode (~230 MB of 320 MB; Xcode ignores it and Xcode 26's + # bitcode_strip can't remove it from archives). Alone it is ~80 MB, same linked size. + cargo rustc --release --lib --target "$t" --no-default-features ${FEATURES:+--features "$FEATURES"} \ + --crate-type staticlib -- --print native-static-libs 2> >(tee "$OUT/$t.log" >&2) + libs=$(sed -n 's/.*native-static-libs: //p' "$OUT/$t.log" | tail -1) + [[ -n "$libs" ]] || { echo "no native-static-libs note for $t (try: cargo clean -p raea --target $t)" >&2; exit 1; } + mkdir -p "$HEADERS/$t" + cp include/raea.h "$HEADERS/$t/" + { + echo "module raea {" + echo " header \"raea.h\"" + set -- $libs + while (($#)); do + case $1 in + -framework) echo " link framework \"$2\""; shift ;; + -lSystem | -lc | -lm) ;; # part of libSystem + -l*) echo " link \"${1#-l}\"" ;; + esac + shift + done | awk '!seen[$0]++' # rustc repeats some (e.g. Foundation) + echo " export *" + echo "}" + } > "$HEADERS/$t/module.modulemap" + echo "$libs" > "$OUT/$t.native-static-libs.txt" +done + +lib() { echo "target/$1/release/libraea.a"; } +args=(-library "$(lib aarch64-apple-ios)" -headers "$HEADERS/aarch64-apple-ios") +if [[ -n "${RAEA_SIM_X86:-}" ]]; then + mkdir -p "$OUT/sim" + lipo -create "$(lib aarch64-apple-ios-sim)" "$(lib x86_64-apple-ios)" -output "$OUT/sim/libraea.a" + args+=(-library "$OUT/sim/libraea.a" -headers "$HEADERS/aarch64-apple-ios-sim") +else + args+=(-library "$(lib aarch64-apple-ios-sim)" -headers "$HEADERS/aarch64-apple-ios-sim") +fi +[[ -n "${RAEA_MACOS:-}" ]] && args+=(-library "$(lib aarch64-apple-darwin)" -headers "$HEADERS/aarch64-apple-darwin") + +xcodebuild -create-xcframework "${args[@]}" -output "$OUT/raea.xcframework" >&2 +rm -rf "$HEADERS" "$OUT/sim" "$OUT"/*.log +echo "$OUT/raea.xcframework" +find "$OUT/raea.xcframework" -name '*.a' -exec ls -lh {} \; >&2 diff --git a/engine/src/api.rs b/engine/src/api.rs new file mode 100644 index 00000000..e36ce3d2 --- /dev/null +++ b/engine/src/api.rs @@ -0,0 +1,902 @@ +//! The library's entry points, behind the C API (ffi.rs): probe, lint, snapshot, and a render +//! session that renders frames on worker threads and hands them over in order. +//! +//! These mirror the CLI (main.rs): the same probe JSON, the same lint checks, the same frame math. +//! (`parse_fps`, `resolve_input`, `frame_count`, `default_fps`, `probe_json` and the lint body are +//! copies of main.rs's; main.rs can switch to these once the C API lands.) +//! +//! Threading: a `Composition` holds a V8 isolate and is `!Send`, so it lives and dies on one +//! thread. Every function here that loads one does so on an internal thread with a 64 MB stack +//! (V8 and Stylo recurse deeply; iOS gives the main thread 1 MB and other threads 512 KB), and +//! returns plain data. So all of them may be called from any thread, including the main thread +//! (they block). A `RenderSession` is `Send`: it owns its worker threads and channels, and can be +//! driven from any one thread at a time. + +use crate::media::{self, AudioClip, FrameProvider, VideoClip, VideoFrames}; +use crate::net::SyncNet; +use crate::runtime; +use crate::scene::{Backend, Composition, Options}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; +use std::sync::Arc; +use std::thread::JoinHandle; + +/// Stack for every thread that runs a composition (same as the CLI's render workers). +pub const STACK_SIZE: usize = 64 << 20; + +/// Byte order of delivered frames. Both are 8 bits per channel, premultiplied alpha, sRGB (what +/// vello_cpu and Skia rasterize to); frames are opaque unless `transparent` is set. +/// `Bgra8` is CoreVideo's kCVPixelFormatType_32BGRA (AVAssetWriter's native input). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum PixelFormat { + #[default] + Rgba8, + Bgra8, +} + +/// RGBA <-> BGRA in place (the swap is its own inverse). +pub fn swap_red_blue(px: &mut [u8]) { + for p in px.chunks_exact_mut(4) { + p.swap(0, 2); + } +} + +/// Options shared by probe / lint / snapshot / render; the C API's `opts_json`. +#[derive(Clone, Debug)] +pub struct RenderOptions { + pub fps: Option<(u32, u32)>, + pub scale: f32, + pub width: Option, + pub height: Option, + pub start: Option, + pub end: Option, + pub variables: Option, + pub backend: Backend, + pub transparent: bool, + /// The HTML composition format conventions (default) or a plain web page (scene::Profile) + pub profile: crate::scene::Profile, + pub workers: Option, + pub network: bool, + pub video_frames: Option, + pub pixel_format: PixelFormat, +} + +impl Default for RenderOptions { + fn default() -> Self { + RenderOptions { + fps: None, + scale: 1.0, + width: None, + height: None, + start: None, + end: None, + variables: None, + backend: Backend::default(), + transparent: false, + profile: crate::scene::Profile::Html, + workers: None, + network: true, + video_frames: None, + pixel_format: PixelFormat::Rgba8, + } + } +} + +const OPTION_KEYS: &str = "fps, scale, width, height, start, end, variables, backend, transparent, workers, network, videoFrames, pixelFormat, profile"; + +impl RenderOptions { + /// `opts_json`: an object with any of `fps` (number or "N/D"), `scale`, `width`, `height`, + /// `start`, `end` (seconds), `variables` (object, or JSON text, or "@path"), `backend` + /// ("vello" | "skia"), `transparent`, `workers`, `network`, `videoFrames` (directory), + /// `pixelFormat` ("rgba" | "bgra"), `profile` ("html" | "web"). + /// Empty / null means all defaults. + pub fn from_json(text: Option<&str>) -> Result { + let mut o = RenderOptions::default(); + let text = text.map(str::trim).unwrap_or(""); + if text.is_empty() || text == "null" { + return Ok(o); + } + let v: Value = serde_json::from_str(text).map_err(|e| format!("opts_json: {e}"))?; + let Some(obj) = v.as_object() else { return Err("opts_json must be a JSON object".into()) }; + let num = |k: &str, v: &Value| v.as_f64().filter(|x| x.is_finite()).ok_or(format!("opts_json.{k} must be a number")); + let uint = |k: &str, v: &Value| v.as_u64().filter(|x| *x <= u32::MAX as u64).ok_or(format!("opts_json.{k} must be a non-negative integer")); + for (k, v) in obj { + if v.is_null() { + continue; + } + match k.as_str() { + "fps" => { + o.fps = Some(match v { + Value::String(s) => parse_fps(s)?, + _ => parse_fps(&num(k, v)?.to_string())?, + }) + } + "scale" => o.scale = num(k, v)? as f32, + "width" => o.width = Some(uint(k, v)? as u32), + "height" => o.height = Some(uint(k, v)? as u32), + "start" => o.start = Some(num(k, v)?), + "end" => o.end = Some(num(k, v)?), + "variables" => { + o.variables = Some(match v { + Value::String(s) => { + let text = match s.strip_prefix('@') { + Some(p) => std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}"))?, + None => s.clone(), + }; + serde_json::from_str(&text).map_err(|e| format!("opts_json.variables: {e}"))? + } + other => other.clone(), + }) + } + "backend" => { + o.backend = match v.as_str() { + Some("auto") => Backend::Auto, + Some("vello") => Backend::Vello, + Some("skia") => Backend::Skia, + Some("gpu") => Backend::Gpu, + _ => return Err(format!("unknown backend {v} (vello | skia | gpu)")), + } + } + "transparent" => o.transparent = v.as_bool().ok_or("opts_json.transparent must be a boolean")?, + "profile" => o.profile = crate::scene::Profile::parse(v.as_str().ok_or("opts_json.profile must be a string")?)?, + "network" => o.network = v.as_bool().ok_or("opts_json.network must be a boolean")?, + "workers" => o.workers = Some((uint(k, v)? as usize).max(1)), + "videoFrames" => o.video_frames = Some(PathBuf::from(v.as_str().ok_or("opts_json.videoFrames must be a path")?)), + "pixelFormat" => { + o.pixel_format = match v.as_str().map(|s| s.to_ascii_lowercase()).as_deref() { + Some("rgba" | "rgba8") => PixelFormat::Rgba8, + Some("bgra" | "bgra8") => PixelFormat::Bgra8, + _ => return Err(format!("unknown pixelFormat {v} (rgba | bgra)")), + } + } + other => return Err(format!("unknown option {other:?} in opts_json (known: {OPTION_KEYS})")), + } + } + if !(o.scale > 0.0 && o.scale.is_finite()) { + return Err("opts_json.scale must be > 0".into()); + } + Ok(o) + } +} + +// --- copies of the CLI's helpers (main.rs) ------------------------------------------------- + +pub fn parse_fps(s: &str) -> Result<(u32, u32), String> { + if let Some((n, d)) = s.split_once('/') { + let n: u32 = n.trim().parse().map_err(|_| format!("bad fps {s}"))?; + let d: u32 = d.trim().parse().map_err(|_| format!("bad fps {s}"))?; + if n == 0 || d == 0 { + return Err(format!("bad fps {s}")); + } + return Ok((n, d)); + } + let f: f64 = s.trim().parse().map_err(|_| format!("bad fps {s}"))?; + if f <= 0.0 || !f.is_finite() { + return Err(format!("bad fps {s}")); + } + if (f - f.round()).abs() < 1e-9 { + Ok((f.round() as u32, 1)) + } else { + Ok(((f * 1000.0).round() as u32, 1000)) + } +} + +/// A project directory (its index.html) or an .html file -> (html, project dir). +pub fn resolve_input(p: &Path) -> Result<(PathBuf, PathBuf), String> { + let p = p.canonicalize().map_err(|e| format!("{}: {e}", p.display()))?; + if p.is_dir() { + let html = p.join("index.html"); + if !html.exists() { + return Err(format!("{} has no index.html", p.display())); + } + Ok((html, p)) + } else { + let dir = p.parent().unwrap_or(Path::new("/")).to_path_buf(); + Ok((p, dir)) + } +} + +pub fn frame_count(duration: f64, fps: f64) -> u64 { + let raw = duration * fps; + let nearest = raw.round(); + if (raw - nearest).abs() <= 1e-3 { nearest as u64 } else { raw.ceil() as u64 } +} + +pub fn default_fps(html: &Path) -> (u32, u32) { + // root data-fps, read without a full parse + let text = std::fs::read_to_string(html).unwrap_or_default(); + if let Some(i) = text.find("data-fps=") { + let rest = &text[i + 9..]; + let q = rest.chars().next().unwrap_or('"'); + let v: String = rest[1..].chars().take_while(|c| *c != q).collect(); + if let Ok(f) = parse_fps(&v) { + return f; + } + } + (30, 1) +} + +/// Default worker count: half the cores (max 8) like the CLI. On iOS at most 2: iPhones have two +/// performance cores, frames are dealt to workers round-robin (so the slowest worker sets the +/// pace), and every worker holds a full document and frame buffers. +pub fn default_workers() -> usize { + let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4); + let max = if cfg!(target_os = "ios") { 2 } else { 8 }; + (cores / 2).clamp(1, max) +} + +pub struct Probe { + pub comp: Composition, + pub videos: Vec, + pub audio: Vec, +} + +fn load(o: &RenderOptions, html: &Path, dir: &Path, fps: (u32, u32), videos: Arc) -> Result { + let size = match (o.width, o.height) { + (Some(w), Some(h)) => Some((w, h)), + _ => None, + }; + Composition::load(Options { + html_path: html.to_path_buf(), + project_dir: dir.to_path_buf(), + fps, + scale: o.scale, + size, + variables: o.variables.clone(), + allow_network: o.network, + transparent: o.transparent, + videos, + backend: o.backend, + profile: o.profile, + html_source: None, + }) +} + +pub fn probe(o: &RenderOptions, html: &Path, dir: &Path, fps: (u32, u32)) -> Result { + let comp = load(o, html, dir, fps, Arc::new(VideoFrames::default()))?; + let (videos, audio) = { + let inner = blitz_dom::Document::inner(&comp.doc); + let durations = std::collections::HashMap::new(); + let windows = std::collections::HashMap::new(); + let mut resolver = runtime::Resolver::new(&inner, &durations, &windows); + media::discover(&inner, &mut resolver, dir, comp.duration) + }; + Ok(Probe { comp, videos, audio }) +} + +pub fn probe_json(p: &Probe, fps: (u32, u32)) -> Value { + let fpsf = fps.0 as f64 / fps.1 as f64; + let (w, h) = p.comp.output_size(); + json!({ + "width": w, + "height": h, + "cssWidth": p.comp.width, + "cssHeight": p.comp.height, + "fps": if fps.1 == 1 { json!(fps.0) } else { json!(format!("{}/{}", fps.0, fps.1)) }, + "duration": p.comp.duration, + "frames": frame_count(p.comp.duration, fpsf), + "rootComposition": p.comp.root_comp_id, + "backend": p.comp.backend_name(), + "timelineDuration": p.comp.timeline_duration, + "videos": p.videos, + "audio": p.audio, + "warnings": p.comp.warnings, + "unsupported": p.comp.unsupported, + "jsErrors": p.comp.js_errors, + }) +} + +/// `lint --json`: `{ok, errors, warnings, unsupported}`. +pub fn lint_json(o: &RenderOptions, html: &Path, dir: &Path, fps: (u32, u32)) -> Result { + let p = probe(o, html, dir, fps)?; + let mut errors: Vec = Vec::new(); + let mut warnings: Vec = p.comp.warnings.clone(); + if p.comp.root_comp_id.is_none() { + errors.push("no element with data-composition-id: the root composition is missing".into()); + } + if p.comp.duration <= 0.0 { + errors.push("composition duration is unknown: set data-duration on the root or register a timeline on window.__timelines".into()); + } + if p.comp.authored_duration.is_none() && p.comp.timeline_duration > 0.0 { + warnings.push(format!("root has no data-duration; using the root timeline's {:.3}s", p.comp.timeline_duration)); + } + for e in &p.comp.js_errors { + errors.push(format!("script error: {e}")); + } + errors.extend(p.comp.structure_errors()); + for v in &p.videos { + if !v.src.contains("://") && !Path::new(&v.src).exists() { + errors.push(format!("video {} source not found: {}", v.id, v.src)); + } + } + for au in &p.audio { + if !au.src.contains("://") && !Path::new(&au.src).exists() { + errors.push(format!("audio {} source not found: {}", au.id, au.src)); + } + } + let mut unsupported = p.comp.unsupported.clone(); + // static scan for features the renderer can't paint + let mut sources = vec![html.to_path_buf()]; + if let Ok(rd) = std::fs::read_dir(dir.join("compositions")) { + sources.extend(rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "html"))); + } + // WebGL renders through ANGLE when this install has it (src/webgl.rs) + let no_gl: &[(&str, &str)] = &[ + ("webgl", "WebGL canvases are not rendered: ANGLE was not found (RAEA_ANGLE_DIR)"), + ("THREE.", "three.js / WebGL scenes are not rendered: ANGLE was not found (RAEA_ANGLE_DIR)"), + ]; + let checks: &[(&str, &str)] = if crate::webgl_available() { &[] } else { no_gl }; + for f in &sources { + let Ok(text) = std::fs::read_to_string(f) else { continue }; + // data-fx effects: unknown names and bad arguments, with how to fix them (effects/catalog.json) + for e in crate::effects::lint_sources([text.as_str()]) { + if !errors.contains(&e) { + errors.push(e); + } + } + for w in crate::effects::lint_warnings([text.as_str()]) { + if !warnings.contains(&w) { + warnings.push(w); + } + } + for (needle, msg) in checks { + if text.contains(needle) { + let m = msg.to_string(); + if !unsupported.contains(&m) { + unsupported.push(m); + } + } + } + } + Ok(json!({"ok": errors.is_empty(), "errors": errors, "warnings": warnings, "unsupported": unsupported})) +} + +// --- threads ---------------------------------------------------------------------------------- + +/// Text of a panic payload. +pub fn panic_message(p: Box) -> String { + if let Some(s) = p.downcast_ref::<&str>() { + format!("panic: {s}") + } else if let Some(s) = p.downcast_ref::() { + format!("panic: {s}") + } else { + "panic".into() + } +} + +/// Run `f` on a fresh thread with a composition-sized stack and wait for it. +pub fn on_render_thread(f: impl FnOnce() -> Result + Send) -> Result { + std::thread::scope(|s| { + let h = std::thread::Builder::new() + .name("raea".into()) + .stack_size(STACK_SIZE) + .spawn_scoped(s, f) + .map_err(|e| format!("spawn: {e}"))?; + h.join().map_err(panic_message)? + }) +} + +/// `