mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 06:53:19 -10:00
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.
This commit is contained in:
commit
e3664ed4e9
1884 files changed
+972126
No files matched your search
@@ -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
|
||||
@@ -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."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
@@ -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/
|
||||
@@ -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$''']
|
||||
+105
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,123 @@
|
||||
<p align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="void/brand/logo/cat-white.svg">
|
||||
<img src="void/brand/logo/cat-black.svg" width="72" alt="raea's cat">
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
<h1 align="center">raea</h1>
|
||||
|
||||
<p align="center"><b>Render Anything Engine</b> <i>(for Anyone)</i></p>
|
||||
|
||||
<p align="center">
|
||||
One GPU engine for video, motion, games, 3D and documents, written as React and TypeScript,<br>
|
||||
rendered faster than it plays, on the device you already own.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://raea.io">raea.io</a> ·
|
||||
<a href="https://raea.io/why/">Why we built it</a> ·
|
||||
<a href="https://raea.io/learn/">How it works</a> ·
|
||||
<a href="docs/settings.md">Settings</a> ·
|
||||
<a href="skills/raea/SKILL.md">Agent skill</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="licence FSL-1.1-ALv2" src="https://img.shields.io/badge/licence-FSL--1.1--ALv2-black">
|
||||
<img alt="status canary" src="https://img.shields.io/badge/status-canary-black">
|
||||
<img alt="macOS, Apple Silicon" src="https://img.shields.io/badge/macOS-Apple%20Silicon-black">
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
> **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 <AbsoluteFill style={{ background: "#000", color: "#fff", fontSize: 120, opacity: interpolate(f, [0, 20], [0, 1]) }}>Hello</AbsoluteFill>;
|
||||
}
|
||||
|
||||
registerRoot(() => <Composition id="hello" component={Hello} width={1920} height={1080} fps={30} durationInFrames={90} />);
|
||||
```
|
||||
|
||||
```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).
|
||||
@@ -0,0 +1 @@
|
||||
target
|
||||
Generated
+1774
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
@@ -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)
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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<Message>,
|
||||
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<Message>) -> 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<mpsc::UnboundedSender<AgentEvent>>,
|
||||
) -> Result<AgentRun> {
|
||||
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<Message>) -> (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<Message>,
|
||||
events: Option<mpsc::UnboundedSender<AgentEvent>>,
|
||||
) -> Result<AgentRun> {
|
||||
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<String, Arc<dyn AgentTool>> = config
|
||||
.tools
|
||||
.iter()
|
||||
.map(|t| (t.name().to_string(), t.clone()))
|
||||
.collect();
|
||||
let tool_defs: Vec<pi_ai::Tool> = config
|
||||
.tools
|
||||
.iter()
|
||||
.map(|t| crate::types::tool_def(t.as_ref()))
|
||||
.collect();
|
||||
|
||||
let mut session_allowed: HashSet<String> = 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<pi_ai::AssistantMessage> = 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<mpsc::UnboundedSender<AgentEvent>>, 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<Message> {
|
||||
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<usize> = messages.iter().enumerate().filter(|(_, m)| matches!(m, Message::ToolResult(_))).map(|(i, _)| i).collect();
|
||||
let assistants: Vec<usize> = messages.iter().enumerate().filter(|(_, m)| matches!(m, Message::Assistant(_))).map(|(i, _)| i).collect();
|
||||
let old_results: std::collections::HashSet<usize> = results.iter().rev().skip(keep).copied().collect();
|
||||
let old_assistants: std::collections::HashSet<usize> = 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<Message> = (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]"))); }
|
||||
}
|
||||
}
|
||||
@@ -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<T> = std::result::Result<T, AgentError>;
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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<AgentToolResult, String> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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<AgentToolResult, String> {
|
||||
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<String, String> {
|
||||
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
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -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<AgentToolResult, String> {
|
||||
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<String, String> {
|
||||
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<usize> = 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<usize> = match_indices.iter().copied().collect();
|
||||
let mut context_set: BTreeSet<usize> = 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
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -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<AgentToolResult, String> {
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -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<Arc<dyn AgentTool>> {
|
||||
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()),
|
||||
]
|
||||
}
|
||||
@@ -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<AgentToolResult, String> {
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<TodoItem>>,
|
||||
}
|
||||
|
||||
#[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<AgentToolResult, String> {
|
||||
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
|
||||
}
|
||||
@@ -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<AgentToolResult, String> {
|
||||
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
|
||||
)))
|
||||
}
|
||||
}
|
||||
@@ -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<Content>,
|
||||
pub details: Value,
|
||||
pub terminate: bool,
|
||||
}
|
||||
|
||||
impl AgentToolResult {
|
||||
pub fn text(s: impl Into<String>) -> 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<AgentToolResult, String>;
|
||||
}
|
||||
|
||||
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<dyn Fn(&[Message]) -> futures::future::BoxFuture<'static, Option<String>> + 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<std::sync::Mutex<Option<pi_ai::AssistantMessageEventStream>>>);
|
||||
|
||||
impl SeededStream {
|
||||
pub fn new(stream: pi_ai::AssistantMessageEventStream) -> Self { Self(Arc::new(std::sync::Mutex::new(Some(stream)))) }
|
||||
pub fn take(&self) -> Option<pi_ai::AssistantMessageEventStream> { 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<Arc<dyn AgentTool>>,
|
||||
pub system_prompt: String,
|
||||
pub permission: Arc<dyn PermissionPolicy>,
|
||||
/// 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<SeededStream>,
|
||||
/// 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<BeforeReply>,
|
||||
}
|
||||
|
||||
impl AgentConfig {
|
||||
pub fn new(model: Model, system_prompt: impl Into<String>) -> 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<Arc<dyn AgentTool>>) -> 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<dyn PermissionPolicy>) -> 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<Message>,
|
||||
},
|
||||
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<Content>,
|
||||
},
|
||||
/// Permission denied for a tool call (the loop appended an error tool result).
|
||||
PermissionDenied {
|
||||
tool_name: String,
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
@@ -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>) -> (String, Arc<Mutex<Vec<Value>>>) {
|
||||
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<AtomicUsize>, says: Option<&'static str>) -> BeforeReply {
|
||||
Arc::new(move |_messages: &[Message]| -> BoxFuture<'static, Option<String>> {
|
||||
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::<Vec<_>>().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<String> = 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(_))));
|
||||
}
|
||||
@@ -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\": \"<!doctype html><html><body><div id=\\\"root\\\" data-dur"}})),
|
||||
("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "max_tokens"}, "usage": {"output_tokens": 16384}})),
|
||||
("message_stop", json!({"type": "message_stop"})),
|
||||
])
|
||||
}
|
||||
|
||||
fn text(id: &str, t: &str) -> 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>) -> (String, Arc<Mutex<Vec<Value>>>) {
|
||||
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<AtomicUsize>);
|
||||
|
||||
#[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<AgentToolResult, String> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(AgentToolResult::text("wrote it"))
|
||||
}
|
||||
}
|
||||
|
||||
fn config(base: &str, writes: Arc<AtomicUsize>) -> 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<Content>, 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");
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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
|
||||
@@ -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> },
|
||||
|
||||
#[error("json: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
|
||||
#[error("io: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -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<AssistantMessageEventStream> {
|
||||
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())),
|
||||
}
|
||||
}
|
||||
@@ -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<UsageDelta>,
|
||||
},
|
||||
#[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<String>,
|
||||
#[serde(default)]
|
||||
usage: Option<UsageDelta>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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<Value> {
|
||||
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::<Vec<_>>();
|
||||
out.push(json!({"role": "user", "content": blocks}));
|
||||
}
|
||||
Message::Assistant(a) => {
|
||||
let blocks = a.content.iter().map(content_to_block).collect::<Vec<_>>();
|
||||
out.push(json!({"role": "assistant", "content": blocks}));
|
||||
}
|
||||
Message::ToolResult(tr) => {
|
||||
let body: Vec<Value> = 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<u32> {
|
||||
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<Value> {
|
||||
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<Value> = 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=<file>: 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<String>,
|
||||
}
|
||||
|
||||
#[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<AssistantMessageEventStream> {
|
||||
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<String, String> = 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<usize, BlockState> = std::collections::HashMap::new();
|
||||
let mut order: Vec<usize> = Vec::new();
|
||||
let mut stop = StopReason::Stop;
|
||||
let mut usage = Usage::default();
|
||||
let mut response_model: Option<String> = 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())
|
||||
}
|
||||
}
|
||||
@@ -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<Candidate>,
|
||||
#[serde(default)]
|
||||
usage_metadata: Option<UsageMetadata>,
|
||||
#[serde(default)]
|
||||
model_version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct Candidate {
|
||||
#[serde(default)]
|
||||
content: Option<CandidateContent>,
|
||||
#[serde(default)]
|
||||
finish_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct CandidateContent {
|
||||
#[serde(default)]
|
||||
parts: Vec<Part>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct Part {
|
||||
#[serde(default)]
|
||||
text: Option<String>,
|
||||
#[serde(default)]
|
||||
function_call: Option<FunctionCall>,
|
||||
}
|
||||
|
||||
#[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<Value> {
|
||||
let mut out: Vec<Value> = Vec::new();
|
||||
for m in messages {
|
||||
match m {
|
||||
Message::User { content, .. } => {
|
||||
let parts: Vec<Value> = 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<Value> = 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::<Vec<_>>()
|
||||
.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<Value> = 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<AssistantMessageEventStream> {
|
||||
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<String, String> = 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<String> = 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<Content> = 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
|
||||
}
|
||||
}
|
||||
@@ -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<AssistantMessageEventStream>;
|
||||
}
|
||||
@@ -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<ChunkChoice>,
|
||||
#[serde(default)]
|
||||
usage: Option<ChunkUsage>,
|
||||
#[serde(default)]
|
||||
model: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct ChunkChoice {
|
||||
#[serde(default)]
|
||||
delta: Option<ChunkDelta>,
|
||||
#[serde(default)]
|
||||
finish_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Default)]
|
||||
struct ChunkDelta {
|
||||
#[serde(default)]
|
||||
content: Option<String>,
|
||||
#[serde(default)]
|
||||
tool_calls: Vec<ToolCallDelta>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct ToolCallDelta {
|
||||
index: usize,
|
||||
#[serde(default)]
|
||||
id: Option<String>,
|
||||
#[serde(default)]
|
||||
function: Option<FunctionDelta>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Default)]
|
||||
struct FunctionDelta {
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default)]
|
||||
arguments: Option<String>,
|
||||
}
|
||||
|
||||
#[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<Value> {
|
||||
let mut out: Vec<Value> = 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::<Vec<_>>()
|
||||
.join("");
|
||||
out.push(json!({"role": "user", "content": text}));
|
||||
}
|
||||
Message::Assistant(a) => {
|
||||
let mut text = String::new();
|
||||
let mut tool_calls: Vec<Value> = 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::<Vec<_>>()
|
||||
.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<Value> = 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<AssistantMessageEventStream> {
|
||||
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<String, String> = 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<usize, PartialToolCall> = Default::default();
|
||||
let mut tool_started: std::collections::BTreeSet<usize> = Default::default();
|
||||
let mut stop = StopReason::Stop;
|
||||
let mut usage = Usage::default();
|
||||
let mut response_model: Option<String> = 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<Content> = 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())
|
||||
}
|
||||
}
|
||||
@@ -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<Value> {
|
||||
let mut out: Vec<Value> = 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::<Vec<_>>()
|
||||
.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<Value> = 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::<Vec<_>>()
|
||||
.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<Value> = 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<OutputItem>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Default)]
|
||||
struct OutputItem {
|
||||
#[serde(rename = "type", default)]
|
||||
item_type: String,
|
||||
#[serde(default)]
|
||||
id: Option<String>,
|
||||
#[serde(default)]
|
||||
call_id: Option<String>,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Default)]
|
||||
struct DeltaEnvelope {
|
||||
#[serde(default)]
|
||||
delta: Option<String>,
|
||||
#[serde(default)]
|
||||
item_id: Option<String>,
|
||||
#[serde(default)]
|
||||
output_index: Option<usize>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Provider for OpenAiResponsesProvider {
|
||||
async fn stream(
|
||||
&self,
|
||||
model: &Model,
|
||||
context: &Context,
|
||||
options: &StreamOptions,
|
||||
) -> Result<AssistantMessageEventStream> {
|
||||
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<String, String> = 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<String, usize> = Default::default();
|
||||
let mut tool_calls: Vec<PartialToolCall> = Vec::new();
|
||||
let mut tool_started: std::collections::BTreeSet<usize> = 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<Content> = 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())
|
||||
}
|
||||
}
|
||||
@@ -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<T> {
|
||||
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<Duration>,
|
||||
},
|
||||
}
|
||||
|
||||
pub async fn with_retry<T, F, Fut>(
|
||||
cfg: &RetryConfig,
|
||||
cancel: Option<&CancellationToken>,
|
||||
mut f: F,
|
||||
) -> Result<T>
|
||||
where
|
||||
F: FnMut(u32) -> Fut,
|
||||
Fut: std::future::Future<Output = Attempt<T>>,
|
||||
{
|
||||
let mut attempt: u32 = 0;
|
||||
let mut last_err: Option<Error>;
|
||||
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<ClassifiedStatus> {
|
||||
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<Duration> {
|
||||
if let Ok(seconds) = value.trim().parse::<u64>() {
|
||||
return Some(Duration::from_secs(seconds));
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -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<AssistantMessageEvent>>;
|
||||
@@ -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<String>,
|
||||
},
|
||||
#[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<String>) -> 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<Content>,
|
||||
#[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<Content>,
|
||||
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<String>,
|
||||
#[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<Content>,
|
||||
pub is_error: bool,
|
||||
#[serde(default = "now_ms")]
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn user_text(s: impl Into<String>) -> 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<String>,
|
||||
/// 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<String>,
|
||||
pub messages: Vec<Message>,
|
||||
pub tools: Vec<Tool>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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<f32>,
|
||||
pub max_tokens: Option<u32>,
|
||||
pub api_key: Option<String>,
|
||||
pub reasoning: Option<ThinkingLevel>,
|
||||
/// Cancellation token honored by the provider HTTP client and SSE loop.
|
||||
pub cancel: Option<tokio_util::sync::CancellationToken>,
|
||||
/// Override base URL (used by OpenAI-compatible passthrough providers).
|
||||
pub base_url: Option<String>,
|
||||
/// Optional custom request headers.
|
||||
pub headers: std::collections::BTreeMap<String, String>,
|
||||
/// Anthropic prompt-cache marker mode. Defaults to `None` (no markers).
|
||||
pub cache_retention: CacheRetention,
|
||||
}
|
||||
|
||||
/// Model descriptor — analogous to the Model<TApi> 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<String>,
|
||||
id: impl Into<String>,
|
||||
base_url: impl Into<String>,
|
||||
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,
|
||||
},
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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]
|
||||
@@ -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:<id>`, `@k:K-12`, `@claim:<id>`, `@cite:<lesson>`, `@knob:<id>`), 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<String>,
|
||||
/// A data table under the step: rows of trimmed cells.
|
||||
pub table: Option<Vec<Vec<String>>>,
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Background {
|
||||
pub steps: Vec<Step>,
|
||||
/// 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<String>,
|
||||
/// Free text between the title and the first step.
|
||||
pub description: Vec<String>,
|
||||
pub steps: Vec<Step>,
|
||||
/// A Scenario Outline (or Template), with its Examples tables.
|
||||
pub outline: bool,
|
||||
pub examples: Vec<Vec<Vec<String>>>,
|
||||
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<String>,
|
||||
pub description: Vec<String>,
|
||||
pub background: Option<Background>,
|
||||
pub scenarios: Vec<Scenario>,
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct Feature {
|
||||
pub name: String,
|
||||
pub tags: Vec<String>,
|
||||
pub description: Vec<String>,
|
||||
pub background: Option<Background>,
|
||||
/// Scenarios before any Rule.
|
||||
pub scenarios: Vec<Scenario>,
|
||||
pub rules: Vec<Rule>,
|
||||
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<Feature>,
|
||||
pub errors: Vec<ParseError>,
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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::<Vec<_>>().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<Feature> = None;
|
||||
let mut at = At::Nothing;
|
||||
let mut pending: Vec<String> = Vec::new();
|
||||
let mut pending_from: Option<usize> = None;
|
||||
let mut last_keyword: Option<Keyword> = 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<String> {
|
||||
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<Feature>) -> Option<&mut Scenario> { feature.as_mut().and_then(scenario_mut) }
|
||||
|
||||
fn last_step(feature: &mut Option<Feature>, 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<Feature>, 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 <addon> line says <duration>
|
||||
|
||||
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<_>>(), 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::<Vec<_>>()).collect::<Vec<_>>()]);
|
||||
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<usize> = 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<std::path::PathBuf>) {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
target/
|
||||
Generated
+1482
File diff suppressed because it is too large.
Load diff
@@ -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"] }
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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<String>,
|
||||
name: String,
|
||||
kind: i32,
|
||||
start: u64,
|
||||
end: u64,
|
||||
attrs: Map<String, Value>,
|
||||
events: Vec<(u64, String, Map<String, Value>)>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
resource: Map<String, Value>,
|
||||
file: Mutex<Option<PathBuf>>,
|
||||
export: Option<mpsc::Sender<Done>>,
|
||||
}
|
||||
|
||||
/// Where spans go. Cheap to clone; every clone writes to the same places.
|
||||
#[derive(Clone)]
|
||||
pub struct Tracer {
|
||||
inner: Arc<Inner>,
|
||||
}
|
||||
|
||||
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<String, Value>) -> 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::<Done>();
|
||||
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<PathBuf>) {
|
||||
*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::<Vec<_>>(),
|
||||
"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<Done>,
|
||||
}
|
||||
|
||||
impl Span {
|
||||
fn new(tracer: Tracer, trace_id: String, parent: Option<String>, 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<Value>) -> &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<String, Value>) -> &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::<String>();
|
||||
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::<String>())
|
||||
}
|
||||
|
||||
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<String, Value>) -> Vec<KeyValue> {
|
||||
m.iter().map(|(k, v)| KeyValue { key: k.clone(), value: Some(any(v)), ..Default::default() }).collect()
|
||||
}
|
||||
|
||||
fn unhex(s: &str) -> Vec<u8> {
|
||||
(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<Done>, resource: Map<String, Value>, 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<Value> = 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
target
|
||||
Generated
+1440
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
@@ -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
|
||||
@@ -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; }
|
||||
@@ -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]
|
||||
@@ -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}
|
||||
@@ -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]]
|
||||
@@ -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]]
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: 3:1 `Build goal:` isn't a title-page key
|
||||
Title: x
|
||||
Build goal: y
|
||||
|
||||
# a
|
||||
@@ -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.
|
||||
@@ -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; }
|
||||
@@ -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
|
||||
@@ -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}
|
||||
@@ -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]]
|
||||
@@ -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
|
||||
@@ -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]
|
||||
@@ -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]
|
||||
@@ -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]]
|
||||
@@ -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]]
|
||||
@@ -0,0 +1,4 @@
|
||||
// expect: 4:1 a claim is
|
||||
Title: x
|
||||
Format: 9:16, 20 s
|
||||
$claim.gras: GRAS verified, trust me
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: ok
|
||||
Title: alternatives
|
||||
Format: 9:16, 20 s
|
||||
|
||||
# hook
|
||||
@DAD
|
||||
There he is. || See the bass?
|
||||
@@ -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}
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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)
|
||||
+339
@@ -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.
|
||||
@@ -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<usize> {
|
||||
let a: Vec<String> = 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<serde_json::Value, ExitCode> {
|
||||
let mut docs: Vec<Loaded> = 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<serde_json::Value> {
|
||||
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<PathBuf>, cut: Option<String>) -> 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<String> = 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<String> = 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::<Vec<_>>().windows(2).find(|w| w[0] == "--variant").map(|w| w[1].clone());
|
||||
let vs: Vec<Option<String>> = 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<Option<String>> = 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<String>, variant: Option<String>, 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<String> = 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<PathBuf> = 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Regex> = 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<String>,
|
||||
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<String>,
|
||||
pub raw: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum El {
|
||||
Section { depth: usize, name: String, variants: Vec<String> },
|
||||
Synopsis(String),
|
||||
Take { take: String, heading: String },
|
||||
Speaker(String),
|
||||
Delivery(String),
|
||||
Punch(Option<f64>),
|
||||
Transition(String),
|
||||
Screen { text: String, notes: Vec<Note> },
|
||||
Beat { kind: String, phrase: String, find: Vec<String>, variants: Vec<String> },
|
||||
Check { rule: String },
|
||||
Line { text: String, notes: Vec<Note>, variants: Vec<String> },
|
||||
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<String>,
|
||||
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<String> {
|
||||
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<Refusal>) -> 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<Refusal>) -> (String, Vec<Note>) {
|
||||
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<String>) {
|
||||
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::<u32>().is_ok() || n.split_once('-').is_some_and(|(a, b)| a.parse::<u32>().is_ok() && b.parse::<u32>().is_ok()))
|
||||
|| f.strip_prefix("framing:").is_some_and(|x| ["close-up", "medium", "wide"].contains(&x))
|
||||
}
|
||||
|
||||
fn check_form(rule: &str) -> Option<(String, Vec<String>)> {
|
||||
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<Doc, Vec<Refusal>> {
|
||||
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<String> = 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<PathBuf>, out: &mut Vec<Loaded>) -> Result<(), Vec<Refusal>> {
|
||||
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<PathBuf>, out: &mut Vec<Loaded>) -> Result<(), Vec<Refusal>> {
|
||||
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::<Vec<_>>())?;
|
||||
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<String, Value> = n.props.iter().map(|(k, v)| (k.clone(), Value::String(fill(v)))).collect();
|
||||
let types: Map<String, Value> = 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<Refusal> {
|
||||
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<Value, Vec<Refusal>> {
|
||||
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::<String>::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<Value> = 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<String> = 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<String>, Option<String>, Option<String>, Option<String>) = (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<Value> = 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<String>, ln: usize, col: usize, bad: &mut Vec<Refusal>| {
|
||||
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<String>| -> (Vec<String>, Vec<String>) { vs.iter().cloned().partition(|v| RATIO.is_match(v)) };
|
||||
let mut section_variants: Vec<String> = Vec::new();
|
||||
let mut variant_names: Vec<String> = Vec::new();
|
||||
let claim_refs = |notes: &Vec<Note>| -> Vec<String> { 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::<Vec<_>>(), "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<Value> = 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<String> = 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::<Vec<_>>(), "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<String, Value> = 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::<Vec<_>>(), "meta": meta,
|
||||
"vars": vars.iter().map(|(k, v)| (k.clone(), json!({"value": v, "picture": is_pic(v)}))).collect::<Map<_, _>>(),
|
||||
"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::<f64>().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<String> = 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::<Vec<_>>().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::<Vec<_>>().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::<Vec<_>>().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<String> = Vec::new();
|
||||
let mut last_line: Option<usize> = 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>| -> 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::<Vec<_>>().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<String> = 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::<Vec<_>>().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<String>, Vec<String>) = 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<String> {
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
@@ -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<usize>), Vec<Refusal>> {
|
||||
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<String> = 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 `<source>:LINE:`; the profile's prelude moved every line down
|
||||
let at = regex::Regex::new(r"<source>:(\d+):").unwrap();
|
||||
let line = at.captures(&msg).and_then(|c| c[1].parse::<usize>().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<RefCell<Vec<String>>> = 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<String> = Vec::new();
|
||||
let mut css: Vec<String> = Vec::new();
|
||||
let (mut root, mut caps): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new());
|
||||
let mut checks: Vec<String> = 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<i32> = 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<String> = story.get_current_tags().unwrap_or_default().iter().map(|t| untag(t)).collect();
|
||||
let now: Vec<i32> = 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::<Vec<_>>().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>) -> 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<String> = 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<String> = Vec::new();
|
||||
let (mut speaker, mut delivery, mut punch, mut take, mut pending): (Option<String>, Option<String>, Option<f64>, Option<String>, Vec<String>) = (None, None, None, None, Vec::new());
|
||||
let mut first: Option<String> = None;
|
||||
let mut sent_take: Option<String> = 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::<String>())); }
|
||||
// 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::<String>()));
|
||||
}
|
||||
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::<String>()));
|
||||
}
|
||||
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::<String>()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !pending.is_empty() { body.push(format!("_{}", pending.drain(..).map(|t| format!(" #{}", entag(&t))).collect::<String>())); }
|
||||
body.push("-> END".into());
|
||||
out.push(String::new());
|
||||
let _ = first;
|
||||
out.extend(body);
|
||||
out.join("\n") + "\n"
|
||||
}
|
||||
@@ -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<String> {
|
||||
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<String, String> {
|
||||
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<String> {
|
||||
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::<String>().split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn ask(token: &str, brief: &str) -> Result<Value, String> {
|
||||
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<String> = 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<String> = 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<PathBuf> = 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]"),
|
||||
}
|
||||
}
|
||||
@@ -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<Loaded> = Vec::new();
|
||||
let got: Vec<String> = 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"));
|
||||
}
|
||||
Generated
+3271
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
@@ -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}`, "[email protected]");
|
||||
b.click(`@${join}`);
|
||||
expect(String(b.get("text", "#out").data && (b.get("text", "#out").data as { text?: string }).text)).toBe("Thanks, [email protected] 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<string, { role: string; name: string }> }).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")}`, "[email protected]").success).toBe(true);
|
||||
expect(words("click", `@${find("button", "Join")}`).success).toBe(true);
|
||||
expect(((words("get", "text", "#out").data) as { text: string }).text).toBe("Thanks, [email protected] 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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>Sign up</title>
|
||||
<style>body{font:16px Inter, sans-serif;margin:24px} .hidden{display:none}</style></head>
|
||||
<body>
|
||||
<h1>Sign up</h1>
|
||||
<label for="email">Email</label> <input id="email" type="email">
|
||||
<label for="plan">Plan</label>
|
||||
<select id="plan"><option>Go</option><option>Creator</option><option>Studio</option></select>
|
||||
<button id="go" onclick="document.getElementById('out').textContent = 'Thanks, ' + document.getElementById('email').value + ' on ' + document.getElementById('plan').value; document.getElementById('out').classList.remove('hidden')">Join</button>
|
||||
<p id="out" class="hidden" role="status"></p>
|
||||
<a href="#terms">Terms</a>
|
||||
</body></html>
|
||||
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>Shots</title></head>
|
||||
<body>
|
||||
<nav aria-label="Main"><a href="/">Home</a> <a href="/projects">Projects</a></nav>
|
||||
<main>
|
||||
<h2>Shot list</h2>
|
||||
<ul><li>Hook</li><li>Demo</li><li>Call to action</li></ul>
|
||||
<label><input type="checkbox" id="done"> Done</label>
|
||||
<label><input type="radio" name="r" checked> Vertical</label>
|
||||
<label><input type="radio" name="r"> Square</label>
|
||||
<textarea placeholder="Notes"></textarea>
|
||||
<input type="search" aria-label="Find">
|
||||
<input type="submit" value="Save">
|
||||
<button disabled>Delete</button>
|
||||
<img src="x.png" alt="Thumbnail">
|
||||
</main>
|
||||
</body></html>
|
||||
@@ -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<T> = Result<T, String>;
|
||||
|
||||
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<String, NodeId>,
|
||||
result: Rc<RefCell<Option<String>>>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static PAGES: RefCell<HashMap<String, Page>> = 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::<Vec<_>>().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::<Vec<_>>().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<NodeId, String>) -> Option<NodeId> {
|
||||
let opts: Vec<NodeId> = 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<NodeId> {
|
||||
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<u32>,
|
||||
checked: Option<bool>,
|
||||
expanded: Option<bool>,
|
||||
selected: bool,
|
||||
disabled: bool,
|
||||
required: bool,
|
||||
value: Option<String>,
|
||||
node: NodeId,
|
||||
children: Vec<usize>,
|
||||
ref_id: Option<String>,
|
||||
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::<u32>().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<String> = 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<String> {
|
||||
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<Ax>, parent: Option<usize>, values: &HashMap<NodeId, String>) {
|
||||
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<Page> {
|
||||
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<RefCell<Option<String>>> = 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<Value> {
|
||||
*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::<Value>(&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<NodeId> {
|
||||
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<Value> {
|
||||
{
|
||||
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<NodeId, String> {
|
||||
// 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::<usize>().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<Ax> = 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<NodeId> {
|
||||
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<Value> {
|
||||
type Req = (Vec<String>, std::sync::mpsc::Sender<R<Value>>);
|
||||
static TX: std::sync::OnceLock<std::sync::Mutex<std::sync::mpsc::Sender<Req>>> = std::sync::OnceLock::new();
|
||||
let tx = TX.get_or_init(|| {
|
||||
let (tx, rx) = std::sync::mpsc::channel::<Req>();
|
||||
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<Value> {
|
||||
// --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<String> = 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::<u64>().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()
|
||||
}
|
||||
|
||||
@@ -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<tokio::runtime::Runtime> = 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<tokio::sync::Mutex<DaemonState>> {
|
||||
static ST: OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<tokio::sync::Mutex<DaemonState>>>>> = 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<Result<Value, String>> {
|
||||
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<String> = 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<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut q: Option<char> = 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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<String> = 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)
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -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<T = unknown> {
|
||||
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<T = unknown>(args: (string | number | undefined | false)[]): BrowserResult<T> {
|
||||
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<T>;
|
||||
return r;
|
||||
}
|
||||
function must<T>(r: BrowserResult<T>): BrowserResult<T> {
|
||||
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<string, { role: string; name?: string }> }>(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();
|
||||
Vendored
+201
@@ -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.
|
||||
+9
@@ -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.
|
||||
+3308
File diff suppressed because it is too large.
Load diff
Loaded 100 of 1884 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user