Compare commits
290 commits
f8da686987
...
5c967da418
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c967da418 | ||
|
|
09165c15dc | ||
|
|
e2e7a6769e | ||
|
|
5d3b9e467e | ||
|
|
06826ef10f | ||
|
|
7f4a99aa95 | ||
|
|
122619624d | ||
|
|
2ea99a81f1 | ||
|
|
c30d18b10d | ||
|
|
18051ab399 | ||
|
|
654a864b3a | ||
|
|
5fba9b0cba | ||
|
|
906bff792c | ||
|
|
c029cc4354 | ||
|
|
0bafd1938c | ||
|
|
b7b1d1a2c7 | ||
|
|
a1d2ef6514 | ||
|
|
81f818aa86 | ||
|
|
f49be143f3 | ||
|
|
3eab273b85 | ||
|
|
85f8bf7393 | ||
|
|
da87558cc2 | ||
|
|
6bca2136a1 | ||
|
|
ef5da3ccc2 | ||
|
|
a3669a29e6 | ||
|
|
3d9852ae04 | ||
|
|
46845bf2f5 | ||
|
|
e4b81180c1 | ||
|
|
aeb5d6d7ff | ||
|
|
486e5f7cdd | ||
|
|
d3070bbc0d | ||
|
|
e5f5767d2c | ||
|
|
12aacf3cea | ||
|
|
b32570d931 | ||
|
|
59d8766f35 | ||
|
|
27c566c212 | ||
|
|
2bba4e2220 | ||
|
|
ec64ba3e69 | ||
|
|
b3d93d4474 | ||
|
|
a6b0ee9f36 | ||
|
|
3bb2f2a61d | ||
|
|
24fd1015f0 | ||
|
|
ef5606bb61 | ||
|
|
5abe4bcbc6 | ||
|
|
d139a871db | ||
|
|
830414004a | ||
|
|
bc64e1f955 | ||
|
|
d74e47ea51 | ||
|
|
f0ed342c19 | ||
|
|
92b0efeee0 | ||
|
|
4d6a3c7e11 | ||
|
|
b8c853a63d | ||
|
|
8042408df4 | ||
|
|
518502e5ef | ||
|
|
6049ceaecf | ||
|
|
6726b15fce | ||
|
|
bedfe32fdc | ||
|
|
58f84cf041 | ||
|
|
60374460f2 | ||
|
|
b141288fb0 | ||
|
|
777e16dd1f | ||
|
|
f0341c96a1 | ||
|
|
ffbda20db1 | ||
|
|
c3b9cacc0e | ||
|
|
5ec1ce7cd0 | ||
|
|
6e58a92713 | ||
|
|
887e3782a8 | ||
|
|
652f13c7ce | ||
|
|
1226e28dd3 | ||
|
|
cbaf8e4d9d | ||
|
|
c19c89a30a | ||
|
|
1d029c5ff5 | ||
|
|
bf4e559347 | ||
|
|
6472f018a6 | ||
|
|
7ae24463e1 | ||
|
|
710228e3dd | ||
|
|
6afac23e4a | ||
|
|
9b4737b0d7 | ||
|
|
9a7a5d685d | ||
|
|
b49e5f19b9 | ||
|
|
32f2593047 | ||
|
|
63f725e8d6 | ||
|
|
aa6062edaf | ||
|
|
bc6a483e5c | ||
|
|
32d0737318 | ||
|
|
80a4042ff5 | ||
|
|
0464de8fdd | ||
|
|
a65e677376 | ||
|
|
f838eb1248 | ||
|
|
ceff1b227b | ||
|
|
d2cbf930f7 | ||
|
|
a55e3e99f5 | ||
|
|
a9296b9a5a | ||
|
|
a718a2bde6 | ||
|
|
b328711bbe | ||
|
|
fe48ef424c | ||
|
|
c171bbac44 | ||
|
|
f839f8e108 | ||
|
|
6555ac3d04 | ||
|
|
75c17a6ee9 | ||
|
|
a1d019bdd8 | ||
|
|
1965d69819 | ||
|
|
88a54a2683 | ||
|
|
5e717a06cd | ||
|
|
e25458243b | ||
|
|
867e51189b | ||
|
|
4129fc87d8 | ||
|
|
53ed11b2af | ||
|
|
7103c8c8e6 | ||
|
|
1025b13951 | ||
|
|
6df9ae9f8f | ||
|
|
6e9f461cf8 | ||
|
|
efacf30294 | ||
|
|
c551ec93b0 | ||
|
|
533d3d534b | ||
|
|
5618485134 | ||
|
|
4bee412118 | ||
|
|
b20cd411ec | ||
|
|
a8966695ee | ||
|
|
eb944cfd7a | ||
|
|
b5b52ada0c | ||
|
|
b1bfde9e9d | ||
|
|
e7bbfd5223 | ||
|
|
a60cf568b7 | ||
|
|
16ae765da8 | ||
|
|
158fcac15e | ||
|
|
511d2c43d2 | ||
|
|
1a0b54616b | ||
|
|
a0ee9fb431 | ||
|
|
277b22f0d2 | ||
|
|
5139a6bfc1 | ||
|
|
1dac14c53a | ||
|
|
63ff99795c | ||
|
|
49fe1fcad5 | ||
|
|
281cfdd7a2 | ||
|
|
707c00b474 | ||
|
|
3e77442f2e | ||
|
|
a5457029cc | ||
|
|
2984fafdf2 | ||
|
|
7ef1fa1380 | ||
|
|
a6780a5a47 | ||
|
|
b72e57da65 | ||
|
|
2e20860461 | ||
|
|
bcfbf669bd | ||
|
|
6a747984d3 | ||
|
|
a8cdf1d869 | ||
|
|
216980f671 | ||
|
|
786eb24521 | ||
|
|
bb460d5f26 | ||
|
|
453b020866 | ||
|
|
8309bc4098 | ||
|
|
001d94d149 | ||
|
|
bc41407a5e | ||
|
|
d3a9fd96a3 | ||
|
|
13e7c11768 | ||
|
|
d066a73609 | ||
|
|
a74a96e25d | ||
|
|
8bfe32010c | ||
|
|
eb2223c080 | ||
|
|
b1180f749c | ||
|
|
b0911ccc9e | ||
|
|
450206e49d | ||
|
|
de529b5677 | ||
|
|
835cd847ef | ||
|
|
2c26e5e544 | ||
|
|
d3e27abc87 | ||
|
|
cfd0461b5a | ||
|
|
949d993146 | ||
|
|
dee596fa96 | ||
|
|
91531fad6d | ||
|
|
e2a1c4ce0c | ||
|
|
d5cf9a65d2 | ||
|
|
da74e24a79 | ||
|
|
776b8304b1 | ||
|
|
78749a4c2a | ||
|
|
6753eb1736 | ||
|
|
ba350974af | ||
|
|
da66f95237 | ||
|
|
f78f6da255 | ||
|
|
77cbba9b1a | ||
|
|
1399540715 | ||
|
|
f0cbb42fa6 | ||
|
|
d61ffb8e6b | ||
|
|
7ec36d3661 | ||
|
|
7afcc87927 | ||
|
|
0307c7fb35 | ||
|
|
33eb2d83ed | ||
|
|
560f784776 | ||
|
|
8d28ca5c01 | ||
|
|
78b5c0e774 | ||
|
|
e024200c67 | ||
|
|
800706d7a8 | ||
|
|
70733ceb6e | ||
|
|
0ec218fa5f | ||
|
|
f15d759bf6 | ||
|
|
b13849d04f | ||
|
|
97c25c31e4 | ||
|
|
c84c22dab5 | ||
|
|
4558d14cf8 | ||
|
|
7f7c21536e | ||
|
|
ddb847d03a | ||
|
|
ee5c7b6d45 | ||
|
|
b3ce9a49f7 | ||
|
|
251456cf20 | ||
|
|
0042fb5850 | ||
|
|
2b506483b2 | ||
|
|
c7b9039e4b | ||
|
|
814443a466 | ||
|
|
d2953a2b57 | ||
|
|
bb63046a08 | ||
|
|
3a81f8e9ab | ||
|
|
80c0f7de0a | ||
|
|
dd528e3efb | ||
|
|
a4c6a8392d | ||
|
|
43b7ca9cc2 | ||
|
|
1103bd8055 | ||
|
|
d33a3186aa | ||
|
|
bc363322af | ||
|
|
e82c04b356 | ||
|
|
80d41375e5 | ||
|
|
5656f3eb3f | ||
|
|
0f6ebdd269 | ||
|
|
068d64edd6 | ||
|
|
e2c38b5358 | ||
|
|
661f185f9f | ||
|
|
7c10059340 | ||
|
|
1ddf7407e9 | ||
|
|
2e70059cd9 | ||
|
|
952119de41 | ||
|
|
d42edc15f9 | ||
|
|
1d207b02e0 | ||
|
|
7b6be29669 | ||
|
|
a11af20495 | ||
|
|
be0fc7fdf5 | ||
|
|
0535f47291 | ||
|
|
a39f1d163d | ||
|
|
ad042e5c9d | ||
|
|
40d3c79f2f | ||
|
|
69effe73d9 | ||
|
|
8dff89c8d1 | ||
|
|
a0aa3e842f | ||
|
|
57a64fc824 | ||
|
|
0d832bc6d5 | ||
|
|
c0596fade7 | ||
|
|
a949cabb32 | ||
|
|
ae47ec9ac0 | ||
|
|
ad437c93c2 | ||
|
|
c5f6fca756 | ||
|
|
589dc95c87 | ||
|
|
3a821765e5 | ||
|
|
da43bdb648 | ||
|
|
c352cad169 | ||
|
|
46b08f9d7d | ||
|
|
4557ad7ad1 | ||
|
|
85f410004c | ||
|
|
938490639a | ||
|
|
8708a6fa74 | ||
|
|
b8dce970fa | ||
|
|
14befe2151 | ||
|
|
8ca194d833 | ||
|
|
980a294292 | ||
|
|
9abb73ee32 | ||
|
|
2a00db06ce | ||
|
|
10fc0fb527 | ||
|
|
c3951af24f | ||
|
|
7a37888f7b | ||
|
|
7dcd422a73 | ||
|
|
b9ba43c9c1 | ||
|
|
ec9ba5f069 | ||
|
|
ea01b926ea | ||
|
|
342580531c | ||
|
|
d3d5fb0d15 | ||
|
|
988f083fc5 | ||
|
|
62c01be72e | ||
|
|
8ce894b909 | ||
|
|
533e975df0 | ||
|
|
79f998a5f3 | ||
|
|
770e20c839 | ||
|
|
68340172a1 | ||
|
|
e1f13a84b7 | ||
|
|
1dc07b40b9 | ||
|
|
5aeb8a7e0f | ||
|
|
bfe914beec | ||
|
|
f2df3f9e18 | ||
|
|
2bd7f35157 | ||
|
|
53c910982c | ||
|
|
4d13f01c89 | ||
|
|
43585afc29 | ||
|
|
23231879cd | ||
|
|
ce38fd67a8 |
160
.agents/skills/gpui-test/SKILL.md
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
---
|
||||
name: gpui-test
|
||||
description: >-
|
||||
Use when writing, debugging, or reproducing GPUI tests in Zed, including
|
||||
gpui::test arguments, TestAppContext parameters, scheduler seeds,
|
||||
ITERATIONS/SEED reproduction, parking failures, and pending task traces.
|
||||
---
|
||||
|
||||
# GPUI Test Debugging
|
||||
|
||||
Use this skill when the user asks about `#[gpui::test]`, GPUI test seeds or iterations, deterministic scheduler failures, parking/pending task failures, or how to reproduce a flaky GPUI test.
|
||||
|
||||
## What `#[gpui::test]` does
|
||||
|
||||
`#[gpui::test]` expands to a normal Rust `#[test]`, so it runs under standard Rust test runners such as `cargo test` and `cargo nextest`.
|
||||
|
||||
It wraps the body in GPUI's deterministic test dispatcher/scheduler and can run the same test multiple times with different seeds. The seed controls scheduler task interleavings and any `StdRng` argument injected into the test.
|
||||
|
||||
The macro supports both synchronous and asynchronous tests.
|
||||
|
||||
### Supported function arguments
|
||||
|
||||
The macro recognizes arguments by type name:
|
||||
|
||||
| Test kind | Supported arguments |
|
||||
| --- | --- |
|
||||
| Sync and async | `&TestAppContext`, `&mut TestAppContext`, `StdRng` |
|
||||
| Async only | `BackgroundExecutor` |
|
||||
| Sync only | `&App`, `&mut App` |
|
||||
|
||||
`StdRng` is seeded from the current GPUI test seed, and `BackgroundExecutor` is backed by the same deterministic test dispatcher.
|
||||
|
||||
### Attribute arguments
|
||||
|
||||
Use these forms on `#[gpui::test(arguments)]`:
|
||||
|
||||
- No arguments: runs once with seed `0`, unless `SEED` is set.
|
||||
- `seed = N`: adds a single explicit seed.
|
||||
- `seeds(...)`: adds multiple explicit seeds.
|
||||
- `iterations = N`: runs sequential seeds starting at `0` by default.
|
||||
- `retries = N`: retries a failing run up to `N` times before surfacing the failure.
|
||||
- `on_failure = "path::to::function"`: calls the function after final failure, before resuming the panic.
|
||||
- `iterations` can be combined with explicit `seed` / `seeds`; explicit seeds are appended to the `0..iterations` range.
|
||||
- If the `SEED` environment variable is set, it takes precedence over explicit seeds.
|
||||
- With `SEED=N` and `ITERATIONS=M` or `iterations = M`, the harness runs seeds `N..N+M`.
|
||||
|
||||
## Environment variables
|
||||
|
||||
### GPUI test macro / scheduler execution
|
||||
|
||||
- `SEED=<u64>` — chooses the scheduler seed. Use this to reproduce a failure printed as `failing seed: N`. It also seeds injected `StdRng` arguments. For `#[gpui::property_test]`, it controls the scheduler seed and GPUI applies it to the proptest config for deterministic case generation.
|
||||
- `ITERATIONS=<usize>` — overrides the `iterations = ...` value at runtime. Use to sweep many seeds without editing the test.
|
||||
- `PENDING_TRACES=1` or `PENDING_TRACES=true` — captures and prints pending task traces when the test scheduler panics with `Parking forbidden`. Use this when `run_until_parked()` or teardown reports pending work.
|
||||
- `GPUI_RUN_UNTIL_PARKED_LOG=1` — logs when `allow_parking()` is enabled. Use to find tests that explicitly permit parking/pending work.
|
||||
- `DEBUG_SCHEDULER=1` — prints scheduler clock/timer debugging from `scheduler::TestScheduler`.
|
||||
|
||||
### Lower-level scheduler tests
|
||||
|
||||
- `SCHEDULER_NONINTERACTIVE=1` — suppresses interactive seed progress output in `scheduler::TestScheduler::many`. This does not affect the `#[gpui::test]` harness path.
|
||||
|
||||
### General Rust test debugging vars often useful with GPUI tests
|
||||
|
||||
- `RUST_BACKTRACE=1` or `RUST_BACKTRACE=full` — show panic backtraces.
|
||||
- `RUST_LOG=<filter>` — enable logs when the test initializes logging.
|
||||
- `ZED_HEADLESS=1` — forces GPUI platform guessing toward headless mode; useful for tests that otherwise interact with platform/window setup.
|
||||
|
||||
Prefer env vars over editing the test when narrowing a reproduction.
|
||||
|
||||
## Reproducing a specific GPUI test
|
||||
|
||||
1. Identify the crate/package and test name.
|
||||
|
||||
2. Run the narrowest test filter first, skip to 3. if a failing seed is known.
|
||||
|
||||
```sh
|
||||
cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
3. If the failure mentions a seed, rerun exactly that seed.
|
||||
|
||||
```sh
|
||||
SEED=<seed> cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
4. If the failure is flaky and no seed is known, sweep seeds.
|
||||
|
||||
```sh
|
||||
ITERATIONS=100 cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
When the harness prints `failing seed: <seed>`, switch to `SEED=<seed>` for all future debugging.
|
||||
|
||||
5. If the failure is `Parking forbidden`, rerun with pending traces.
|
||||
|
||||
```sh
|
||||
PENDING_TRACES=1 cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
If a failing seed was printed or is already known, include it too:
|
||||
|
||||
```sh
|
||||
SEED=<seed> PENDING_TRACES=1 cargo -q test -p <crate-name> <test_name> -- --nocapture
|
||||
```
|
||||
|
||||
Inspect the pending traces for a task that was spawned but not awaited, detached, completed, or intentionally allowed to park.
|
||||
|
||||
6. If timing or timer advancement is involved, prefer GPUI scheduler timers in tests:
|
||||
|
||||
```rust
|
||||
cx.background_executor().timer(duration).await;
|
||||
```
|
||||
|
||||
Avoid `smol::Timer::after(...)` in GPUI tests that rely on `run_until_parked()`, because GPUI's scheduler may not track it.
|
||||
|
||||
7. Minimize the reproduction.
|
||||
- Keep the failing `SEED` fixed.
|
||||
- Reduce `ITERATIONS` to `1` or remove it once a seed is known.
|
||||
- Remove unrelated setup only after confirming the same seed still fails.
|
||||
- Preserve scheduler-sensitive awaits/yields; removing them can mask the bug.
|
||||
- If randomness is test-controlled via `StdRng`, log or assert the generated scenario after fixing the scheduler seed.
|
||||
|
||||
8. Validate the fix.
|
||||
- Run the fixed seed.
|
||||
- Run a modest seed sweep, e.g. `ITERATIONS=20`, if the failure was scheduler-sensitive.
|
||||
- Run the relevant crate's test filter or broader suite if the touched code has shared behavior.
|
||||
|
||||
## Common diagnosis patterns
|
||||
|
||||
### Seed-dependent assertion failure
|
||||
|
||||
Likely caused by a scheduler interleaving or by `StdRng`-driven test data. Fix `SEED`, reproduce, and inspect which task or generated scenario differs.
|
||||
|
||||
### `Parking forbidden`
|
||||
|
||||
Usually means a foreground/background task is still pending when the scheduler expected the test to make progress or finish. Look for:
|
||||
|
||||
- A task that should be awaited but was dropped.
|
||||
- A task that should be detached with error logging.
|
||||
- A timer or receiver that is waiting forever.
|
||||
- A missing `cx.run_until_parked()` after triggering async work in a test.
|
||||
- A missing `cx.advance_clock(...)` to wait for debounced work in a test.
|
||||
- Use of non-GPUI timers or executors that the test scheduler cannot drive.
|
||||
|
||||
Rerun with `PENDING_TRACES=1` before changing code.
|
||||
|
||||
### Non-determinism / wrong thread
|
||||
|
||||
The scheduler can report activity from an unexpected thread. Look for work escaping GPUI's foreground/background executors, direct thread spawns, or external async runtimes not controlled by the test dispatcher.
|
||||
|
||||
### Tests pass alone but fail in sweeps
|
||||
|
||||
Use the failing seed from sweep output. Avoid assuming test order unless the runner is explicitly serial. Check globals, leaked entities/tasks, and state not reset by test initialization.
|
||||
|
||||
## Writing GPUI tests
|
||||
|
||||
- Prefer `#[gpui::test]` for tests that need `TestAppContext`, deterministic executors, fake time, or scheduler interleaving coverage.
|
||||
- Add `iterations = N` when the test is intentionally checking interleavings.
|
||||
- Use `StdRng` as a test argument when randomized test data should follow the same seed as the scheduler.
|
||||
- Use `cx.background_executor().timer(duration).await` for delays/timeouts in GPUI tests.
|
||||
- Do not add or increase `retries` while fixing a test unless the user explicitly asks or the test already documents why probabilistic tolerance is intentional. Retries can mask the failure instead of fixing it.
|
||||
175
.agents/skills/zed-cherry-pick/SKILL.md
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
---
|
||||
name: zed-cherry-pick
|
||||
description: Cherry-pick one or more merged PRs and/or commits into Zed's `preview` or `stable` release branch. Use this whenever the user mentions cherry-picking to preview/stable, a failed cherry-pick run, or wants to manually port fix(es) into a release branch.
|
||||
---
|
||||
|
||||
# Zed Cherry-Pick
|
||||
|
||||
Zed ships from two long-lived release branches that live on `origin`:
|
||||
|
||||
- `preview` channel → branch like `v1.4.x`
|
||||
- `stable` channel → branch like `v1.3.x`
|
||||
|
||||
The version numbers change with each release. **Never hardcode them — always discover the current mapping** (see [Finding the target branch](#finding-the-target-branch)).
|
||||
|
||||
A merged PR on `main` gets ported to a release branch by `script/cherry-pick`, normally driven by the `cherry_pick` GitHub Actions workflow. When that workflow fails (almost always a merge conflict), use this skill to finish the job locally and open the cherry-pick PR by hand.
|
||||
|
||||
## When to use
|
||||
|
||||
Use this when the user asks to cherry-pick one or more commits and/or Pull Requests (by number or URL) to `preview` or `stable`.
|
||||
Optionally, the user may specify whether to resolve merge conflicts; if unspecified, attempt the cherry-pick, and then if there are merge conflicts in practice, stop and inform the user that there are merge conflicts and offer to resolve them. (Users may prefer to resolve the merge conflicts themselves before continuing.)
|
||||
|
||||
## The script you're emulating
|
||||
|
||||
The canonical procedure lives in `script/cherry-pick` and the `cherry_pick` GitHub Actions workflow. Read the script first if anything looks off — your local steps must produce the same branch name, PR title, and PR body it would.
|
||||
|
||||
Signature: `script/cherry-pick <branch-name> <commit-sha> <channel>`
|
||||
|
||||
- `<branch-name>` is the release branch (e.g. `v1.4.x`), **not** the channel name.
|
||||
- `<channel>` is `preview` or `stable`, used only for display text in the PR title/body.
|
||||
|
||||
It creates a local branch named `cherry-pick-<branch-name>-<short-sha>` (the short SHA is the first 8 chars of the commit), force-pushes it to `origin`, and opens a PR.
|
||||
|
||||
## Finding the target branch
|
||||
|
||||
The channel→branch mapping changes every release. Find the current one by inspecting the most recent `cherry_pick` workflow runs:
|
||||
|
||||
```
|
||||
gh run list --workflow=cherry_pick.yml --limit 30 --json displayTitle,databaseId
|
||||
# pick a recent run for the channel you want, then:
|
||||
gh run view <id> --log 2>&1 | grep -E "BRANCH:|CHANNEL:"
|
||||
```
|
||||
|
||||
A successful run prints both `BRANCH:` and `CHANNEL:` env vars; that's your mapping.
|
||||
|
||||
## Procedure
|
||||
|
||||
### 1. Gather context
|
||||
|
||||
You need three things: the **merge commit SHA**, the **target branch**, and the **channel name**.
|
||||
|
||||
If the user requested multiple PRs and/or commits, gather the metadata for all of them first and cherry-pick them in the order they landed on `main`, oldest to newest. For PRs, order by `mergedAt`; for raw commits, use their order on `main` when available, otherwise commit date. This tends to reduce avoidable conflicts because later changes may depend on earlier ones, but it does not guarantee a conflict-free cherry-pick when the release branch has diverged.
|
||||
|
||||
```
|
||||
gh pr view <PR_NUMBER> --json title,number,mergeCommit,mergedAt,url
|
||||
```
|
||||
|
||||
If the user said the workflow failed, fetch its log to see exactly which command failed and which file conflicted:
|
||||
|
||||
```
|
||||
gh run list --workflow=cherry_pick.yml --limit 10 --json databaseId,displayTitle,status,conclusion
|
||||
gh run view <failed_run_id> --log-failed
|
||||
```
|
||||
|
||||
The failed-run log also confirms the `BRANCH` and `COMMIT` the workflow used — handy if there's any ambiguity.
|
||||
|
||||
### 2. Reproduce the script's setup locally
|
||||
|
||||
The repository may be a worktree (check `.git` — if it's a file, you're in a worktree pointing at a shared gitdir). That's fine; just operate normally.
|
||||
|
||||
```
|
||||
git --no-pager fetch origin <branch-name> <commit-sha>
|
||||
git checkout --force origin/<branch-name> -B cherry-pick-<branch-name>-<short-sha>
|
||||
git cherry-pick <commit-sha>
|
||||
```
|
||||
|
||||
The branch name **must** match `cherry-pick-<branch-name>-<short-sha>` exactly (script convention; reviewers and tooling expect it).
|
||||
|
||||
### 3. Check for missing prerequisite cherry-picks
|
||||
|
||||
If the cherry-pick conflicts, do not immediately resolve the conflicts manually.
|
||||
|
||||
First determine whether the conflict is likely caused by other PRs or commits that are already on `main` but missing from the release branch. If so, point out those candidate prerequisite PRs/commits to the user, including PR links, and offer to either resolve the conflicts manually or let the user run the GitHub cherry-pick workflow for those commits first.
|
||||
|
||||
If the user wants to run the workflow for the missing prerequisites, stop here. This often keeps cherry-picks clean and eligible for automatic approval.
|
||||
|
||||
Only resolve conflicts manually if:
|
||||
- no likely missing prerequisites are found, or
|
||||
- the user chooses manual conflict resolution instead of cherry-picking the prerequisites first.
|
||||
|
||||
### 4. Resolve the conflicts manually
|
||||
|
||||
Do this only after checking for missing prerequisite cherry-picks.
|
||||
|
||||
- Inspect every conflicted file with `grep -n '<<<<<<<\\|>>>>>>>\\|=======' <path>` to find the markers.
|
||||
- Conflicts are usually `diff3` style with three sections: HEAD (release branch), `||||||| parent of <sha>` (merge base on `main`), and the incoming change.
|
||||
- Read the **original commit** (`git --no-pager show <commit-sha> -- <path>`) to understand the author's intent, then pick the resolution that produces the equivalent end state on the release branch.
|
||||
- Don't grab unrelated changes from `main` that happen to surround the conflict — keep the cherry-pick minimal.
|
||||
|
||||
### 5. Validate
|
||||
|
||||
Always build and (if reasonable) test the affected crate(s) before continuing the cherry-pick.
|
||||
|
||||
```
|
||||
cargo check -p <affected_crate>
|
||||
cargo test -p <affected_crate>
|
||||
```
|
||||
|
||||
If validation fails, fix the resolution — do **not** continue with a broken build. If you can't reach a clean state, abort with `git cherry-pick --abort` and report back to the user.
|
||||
|
||||
### 6. Finish the cherry-pick
|
||||
|
||||
`git cherry-pick --continue` opens an editor by default. Prevent that:
|
||||
|
||||
```
|
||||
git add <resolved_files>
|
||||
GIT_EDITOR=true git cherry-pick --continue
|
||||
```
|
||||
|
||||
This preserves the original commit message verbatim, which is what the script does.
|
||||
|
||||
### 7. Push and open the PR
|
||||
|
||||
```
|
||||
git push origin -f cherry-pick-<branch-name>-<short-sha>
|
||||
```
|
||||
|
||||
Then create the PR with the **exact** title and body format `script/cherry-pick` uses, so it's indistinguishable from an automated one.
|
||||
|
||||
**Title:**
|
||||
|
||||
```
|
||||
<original commit subject> (cherry-pick to <channel>)
|
||||
```
|
||||
|
||||
The original commit subject already ends in ` (#<original_pr_number>)`; keep it.
|
||||
|
||||
**Body** (when the original commit title ends in `(#<N>)`, which is the normal case):
|
||||
|
||||
```
|
||||
Cherry-pick of #<original_pr_number> to <channel>
|
||||
|
||||
----
|
||||
<original commit body, verbatim>
|
||||
```
|
||||
|
||||
Create it with `gh pr create`, writing the body to a temp file to keep formatting intact:
|
||||
|
||||
```
|
||||
git --no-pager log -1 --pretty=format:"%b" > /tmp/cp-body-tail.md
|
||||
printf 'Cherry-pick of #%s to %s\n\n----\n' <PR_NUMBER> <channel> | cat - /tmp/cp-body-tail.md > /tmp/cp-body.md
|
||||
gh pr create --base <branch-name> --head cherry-pick-<branch-name>-<short-sha> \\
|
||||
--title "<commit subject> (cherry-pick to <channel>)" \\
|
||||
--body-file /tmp/cp-body.md
|
||||
```
|
||||
|
||||
Do **not** add a `Release Notes:` section — the original commit body already has one (or already says `N/A`), and you don't want it duplicated.
|
||||
|
||||
## Final report to the user
|
||||
|
||||
Tell the user:
|
||||
- The new PR URL.
|
||||
- A one-line summary of the conflict and how you resolved it.
|
||||
- What validation you ran (commands + result).
|
||||
- That their local branch is now `cherry-pick-<branch-name>-<short-sha>`, in case they want you to switch back.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **`--no-pager` and `GIT_EDITOR=true`**: required for non-interactive git in this environment. Forgetting `GIT_EDITOR=true` on `cherry-pick --continue` hangs the terminal.
|
||||
- **Worktree index lock**: if a previous git command was interrupted, you may see `index.lock` errors. The lock lives at `<gitdir>/index.lock` where `<gitdir>` is what `cat .git` points to (for a worktree). Remove it only if you're sure no git process is running.
|
||||
- **Don't expand the cherry-pick's scope**: when resolving conflicts, never pull in unrelated changes from `main` just because they sit next to the conflict region. The PR should be the smallest diff that reproduces the original commit's intent on the release branch.
|
||||
- **Channel branches are not called `preview`/`stable`**: don't try to `git fetch origin preview`. Look up the actual `vX.Y.x` branch name first.
|
||||
|
||||
## When Finished
|
||||
|
||||
After everything is finished, the last thing to do is to provide a link to the opened pull request(s) for the cherry-pick(s).
|
||||
2
.github/CODEOWNERS.hold
vendored
|
|
@ -55,7 +55,6 @@
|
|||
/crates/open_ai/ @zed-industries/ai-team
|
||||
/crates/open_router/ @zed-industries/ai-team
|
||||
/crates/prompt_store/ @zed-industries/ai-team
|
||||
/crates/rules_library/ @zed-industries/ai-team
|
||||
# SUGGESTED: Review needed - based on Richard Feldman (2 commits)
|
||||
/crates/shell_command_parser/ @zed-industries/ai-team
|
||||
/crates/vercel/ @zed-industries/ai-team
|
||||
|
|
@ -181,7 +180,6 @@
|
|||
/crates/fs_benchmarks/ @zed-industries/infrastructure-team
|
||||
/crates/http_client/ @zed-industries/infrastructure-team
|
||||
/crates/http_client_tls/ @zed-industries/infrastructure-team
|
||||
/crates/nc/ @zed-industries/infrastructure-team
|
||||
/crates/net/ @zed-industries/infrastructure-team
|
||||
/crates/paths/ @zed-industries/infrastructure-team
|
||||
/crates/release_channel/ @zed-industries/infrastructure-team
|
||||
|
|
|
|||
|
|
@ -1,113 +0,0 @@
|
|||
name: Community Champion Auto Labeler
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
label_community_champion:
|
||||
if: github.repository_owner == 'zed-industries'
|
||||
runs-on: namespace-profile-2x4-ubuntu-2404
|
||||
steps:
|
||||
- name: Check if author is a community champion and apply label
|
||||
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
|
||||
env:
|
||||
COMMUNITY_CHAMPIONS: |
|
||||
0x2CA
|
||||
5brian
|
||||
5herlocked
|
||||
abdelq
|
||||
afgomez
|
||||
AidanV
|
||||
akbxr
|
||||
AlvaroParker
|
||||
amtoaer
|
||||
artemevsevev
|
||||
bajrangCoder
|
||||
bcomnes
|
||||
Be-ing
|
||||
blopker
|
||||
bnjjj
|
||||
bobbymannino
|
||||
CharlesChen0823
|
||||
chbk
|
||||
davewa
|
||||
davidbarsky
|
||||
ddoemonn
|
||||
djsauble
|
||||
errmayank
|
||||
fantacell
|
||||
fdncred
|
||||
findrakecil
|
||||
FloppyDisco
|
||||
gko
|
||||
huacnlee
|
||||
imumesh18
|
||||
injust
|
||||
jacobtread
|
||||
jansol
|
||||
jeffreyguenther
|
||||
jenslys
|
||||
jongretar
|
||||
lemorage
|
||||
lingyaochu
|
||||
lnay
|
||||
marcocondrache
|
||||
marius851000
|
||||
mikebronner
|
||||
ognevny
|
||||
PKief
|
||||
playdohface
|
||||
RemcoSmitsDev
|
||||
rgbkrk
|
||||
romaninsh
|
||||
rxptr
|
||||
Simek
|
||||
someone13574
|
||||
sourcefrog
|
||||
suxiaoshao
|
||||
Takk8IS
|
||||
tartarughina
|
||||
thedadams
|
||||
tidely
|
||||
timvermeulen
|
||||
valentinegb
|
||||
versecafe
|
||||
vitallium
|
||||
WhySoBad
|
||||
ya7010
|
||||
Zertsov
|
||||
with:
|
||||
script: |
|
||||
const communityChampions = process.env.COMMUNITY_CHAMPIONS
|
||||
.split('\n')
|
||||
.map(handle => handle.trim().toLowerCase())
|
||||
.filter(handle => handle.length > 0);
|
||||
|
||||
let author;
|
||||
if (context.eventName === 'issues') {
|
||||
author = context.payload.issue.user.login;
|
||||
} else if (context.eventName === 'pull_request_target') {
|
||||
author = context.payload.pull_request.user.login;
|
||||
}
|
||||
|
||||
if (!author || !communityChampions.includes(author.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
const issueNumber = context.payload.issue?.number || context.payload.pull_request?.number;
|
||||
|
||||
try {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issueNumber,
|
||||
labels: ['community champion']
|
||||
});
|
||||
|
||||
console.log(`Applied 'community champion' label to #${issueNumber} by ${author}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to apply label: ${error.message}`);
|
||||
}
|
||||
2
.github/workflows/extension_bump.yml
vendored
|
|
@ -5,7 +5,7 @@ env:
|
|||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: '1'
|
||||
CARGO_INCREMENTAL: '0'
|
||||
ZED_EXTENSION_CLI_SHA: 1fa7f1a3ec28ea1eae6db2e937d7a538fb10c0c7
|
||||
ZED_EXTENSION_CLI_SHA: 2a00db06ce6d01089bfafd207b6348078e980df9
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
|
|
|
|||
2
.github/workflows/extension_tests.yml
vendored
|
|
@ -5,7 +5,7 @@ env:
|
|||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: '1'
|
||||
CARGO_INCREMENTAL: '0'
|
||||
ZED_EXTENSION_CLI_SHA: 1fa7f1a3ec28ea1eae6db2e937d7a538fb10c0c7
|
||||
ZED_EXTENSION_CLI_SHA: 2a00db06ce6d01089bfafd207b6348078e980df9
|
||||
RUSTUP_TOOLCHAIN: stable
|
||||
CARGO_BUILD_TARGET: wasm32-wasip2
|
||||
on:
|
||||
|
|
|
|||
97
.github/workflows/nix_build.yml
vendored
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
# Generated from xtask::workflows::nix_build
|
||||
# Rebuild with `cargo xtask workflows`.
|
||||
name: nix_build
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: '1'
|
||||
on:
|
||||
pull_request:
|
||||
types:
|
||||
- labeled
|
||||
- synchronize
|
||||
jobs:
|
||||
build_nix_linux_x86_64:
|
||||
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && (github.event.label.name == 'run-nix' || github.event.label.name == 'run-bundling')) || (github.event.action == 'synchronize' && (contains(github.event.pull_request.labels.*.name, 'run-nix') || contains(github.event.pull_request.labels.*.name, 'run-bundling'))))
|
||||
runs-on: namespace-profile-32x64-ubuntu-2004
|
||||
env:
|
||||
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
|
||||
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
|
||||
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
|
||||
GIT_LFS_SKIP_SMUDGE: '1'
|
||||
steps:
|
||||
- name: steps::checkout_repo
|
||||
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
|
||||
with:
|
||||
clean: false
|
||||
- name: steps::cache_nix_dependencies_namespace
|
||||
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
|
||||
with:
|
||||
cache: nix
|
||||
- name: nix_build::build_nix::install_nix
|
||||
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: nix_build::build_nix::cachix_action
|
||||
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
|
||||
with:
|
||||
name: zed
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
cachixArgs: -v
|
||||
pushFilter: -zed-editor-[0-9.]*
|
||||
- name: nix_build::build_nix::build
|
||||
run: nix build .#default -L --accept-flake-config
|
||||
timeout-minutes: 60
|
||||
continue-on-error: true
|
||||
build_nix_mac_aarch64:
|
||||
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && (github.event.label.name == 'run-nix' || github.event.label.name == 'run-bundling')) || (github.event.action == 'synchronize' && (contains(github.event.pull_request.labels.*.name, 'run-nix') || contains(github.event.pull_request.labels.*.name, 'run-bundling'))))
|
||||
runs-on: namespace-profile-mac-large
|
||||
env:
|
||||
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
|
||||
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
|
||||
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
|
||||
GIT_LFS_SKIP_SMUDGE: '1'
|
||||
steps:
|
||||
- name: steps::checkout_repo
|
||||
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
|
||||
with:
|
||||
clean: false
|
||||
- name: steps::cache_nix_store_macos
|
||||
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
|
||||
with:
|
||||
path: ~/nix-cache
|
||||
- name: nix_build::build_nix::install_nix
|
||||
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: nix_build::build_nix::configure_local_nix_cache
|
||||
run: |
|
||||
mkdir -p ~/nix-cache
|
||||
echo "extra-substituters = file://$HOME/nix-cache?priority=10" | sudo tee -a /etc/nix/nix.conf
|
||||
echo "require-sigs = false" | sudo tee -a /etc/nix/nix.conf
|
||||
sudo launchctl kickstart -k system/org.nixos.nix-daemon
|
||||
- name: nix_build::build_nix::cachix_action
|
||||
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
|
||||
with:
|
||||
name: zed
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
cachixArgs: -v
|
||||
pushFilter: -zed-editor-[0-9.]*
|
||||
- name: nix_build::build_nix::build
|
||||
run: nix build .#default -L --accept-flake-config
|
||||
- name: nix_build::build_nix::export_to_local_nix_cache
|
||||
if: always()
|
||||
run: |
|
||||
if [ -L result ]; then
|
||||
echo "Copying build closure to local binary cache..."
|
||||
nix copy --to "file://$HOME/nix-cache" ./result || echo "Warning: nix copy to local cache failed"
|
||||
else
|
||||
echo "No build result found, skipping cache export."
|
||||
fi
|
||||
timeout-minutes: 60
|
||||
continue-on-error: true
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
|
||||
cancel-in-progress: true
|
||||
defaults:
|
||||
run:
|
||||
shell: bash -euxo pipefail {0}
|
||||
247
.github/workflows/pr_issue_labeler.yml
vendored
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
# Labels pull requests by author:
|
||||
# - 'community champion' for community champions
|
||||
# - 'bot' for bot accounts
|
||||
# - 'staff' for staff team members
|
||||
# - 'guild' for guild members
|
||||
# - 'first contribution' for first-time external contributors
|
||||
# Labels issues by author:
|
||||
# - 'community champion' for community champions
|
||||
|
||||
name: PR Issue Labeler
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-authorship-and-label:
|
||||
if: github.repository == 'zed-industries/zed'
|
||||
runs-on: namespace-profile-2x4-ubuntu-2404
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- id: get-app-token
|
||||
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
|
||||
with:
|
||||
app-id: ${{ secrets.ZED_COMMUNITY_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.ZED_COMMUNITY_BOT_PRIVATE_KEY }}
|
||||
owner: zed-industries
|
||||
|
||||
- id: apply-authorship-label
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
with:
|
||||
github-token: ${{ steps.get-app-token.outputs.token }}
|
||||
script: |
|
||||
const BOT_LABEL = 'bot';
|
||||
const STAFF_LABEL = 'staff';
|
||||
const STAFF_TEAM_SLUG = 'staff';
|
||||
const FIRST_CONTRIBUTION_LABEL = 'first contribution';
|
||||
const GUILD_LABEL = 'guild';
|
||||
const GUILD_MEMBERS = [
|
||||
'11happy',
|
||||
'AidanV',
|
||||
'alanpjohn',
|
||||
'AmaanBilwar',
|
||||
'arjunkomath',
|
||||
'austincummings',
|
||||
'ayushk-1801',
|
||||
'criticic',
|
||||
'dongdong867',
|
||||
'emamulandalib',
|
||||
'eureka928',
|
||||
'feitreim',
|
||||
'iam-liam',
|
||||
'iksuddle',
|
||||
'ishaksebsib',
|
||||
'lingyaochu',
|
||||
'loadingalias',
|
||||
'marcocondrache',
|
||||
'mchisolm0',
|
||||
'MostlyKIGuess',
|
||||
'nairadithya',
|
||||
'nihalxkumar',
|
||||
'notJoon',
|
||||
'OmChillure',
|
||||
'Palanikannan1437',
|
||||
'polyesterswing',
|
||||
'prayanshchh',
|
||||
'razeghi71',
|
||||
'sarmadgulzar',
|
||||
'seanstrom',
|
||||
'Shivansh-25',
|
||||
'SkandaBhat',
|
||||
'th0jensen',
|
||||
'tommyming',
|
||||
'transitoryangel',
|
||||
'TwistingTwists',
|
||||
'virajbhartiya',
|
||||
'YEDASAVG',
|
||||
'Ziqi-Yang',
|
||||
];
|
||||
const COMMUNITY_CHAMPION_LABEL = 'community champion';
|
||||
const COMMUNITY_CHAMPIONS = [
|
||||
'0x2CA',
|
||||
'5brian',
|
||||
'5herlocked',
|
||||
'abdelq',
|
||||
'afgomez',
|
||||
'AidanV',
|
||||
'akbxr',
|
||||
'AlvaroParker',
|
||||
'amtoaer',
|
||||
'artemevsevev',
|
||||
'bajrangCoder',
|
||||
'bcomnes',
|
||||
'Be-ing',
|
||||
'blopker',
|
||||
'bnjjj',
|
||||
'bobbymannino',
|
||||
'CharlesChen0823',
|
||||
'chbk',
|
||||
'davewa',
|
||||
'davidbarsky',
|
||||
'ddoemonn',
|
||||
'djsauble',
|
||||
'errmayank',
|
||||
'fantacell',
|
||||
'fdncred',
|
||||
'findrakecil',
|
||||
'FloppyDisco',
|
||||
'gko',
|
||||
'huacnlee',
|
||||
'imumesh18',
|
||||
'injust',
|
||||
'jacobtread',
|
||||
'jansol',
|
||||
'jeffreyguenther',
|
||||
'jenslys',
|
||||
'jongretar',
|
||||
'lemorage',
|
||||
'lingyaochu',
|
||||
'lnay',
|
||||
'marcocondrache',
|
||||
'marius851000',
|
||||
'mikebronner',
|
||||
'ognevny',
|
||||
'PKief',
|
||||
'playdohface',
|
||||
'RemcoSmitsDev',
|
||||
'rgbkrk',
|
||||
'romaninsh',
|
||||
'rxptr',
|
||||
'Simek',
|
||||
'someone13574',
|
||||
'sourcefrog',
|
||||
'suxiaoshao',
|
||||
'Takk8IS',
|
||||
'tartarughina',
|
||||
'thedadams',
|
||||
'tidely',
|
||||
'timvermeulen',
|
||||
'valentinegb',
|
||||
'versecafe',
|
||||
'vitallium',
|
||||
'WhySoBad',
|
||||
'ya7010',
|
||||
'Zertsov',
|
||||
];
|
||||
|
||||
const pr = context.payload.pull_request;
|
||||
const issue = context.payload.issue;
|
||||
const target = pr || issue;
|
||||
const author = target.user.login;
|
||||
|
||||
const listIncludesAuthor = (members, author) => {
|
||||
const authorLower = author.toLowerCase();
|
||||
return members.some((member) => member.toLowerCase() === authorLower);
|
||||
};
|
||||
|
||||
const isStaffMember = async (author) => {
|
||||
try {
|
||||
const response = await github.rest.teams.getMembershipForUserInOrg({
|
||||
org: 'zed-industries',
|
||||
team_slug: STAFF_TEAM_SLUG,
|
||||
username: author
|
||||
});
|
||||
return response.data.state === 'active';
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const getIssueLabels = () => {
|
||||
if (listIncludesAuthor(COMMUNITY_CHAMPIONS, author)) {
|
||||
return [COMMUNITY_CHAMPION_LABEL];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
const getPullRequestLabels = async () => {
|
||||
if (target.user.type === 'Bot') {
|
||||
return [BOT_LABEL];
|
||||
}
|
||||
|
||||
if (await isStaffMember(author)) {
|
||||
return [STAFF_LABEL];
|
||||
}
|
||||
|
||||
// External contributors
|
||||
|
||||
const labelsToAdd = [];
|
||||
|
||||
if (listIncludesAuthor(COMMUNITY_CHAMPIONS, author)) {
|
||||
labelsToAdd.push(COMMUNITY_CHAMPION_LABEL);
|
||||
}
|
||||
|
||||
if (listIncludesAuthor(GUILD_MEMBERS, author)) {
|
||||
labelsToAdd.push(GUILD_LABEL);
|
||||
}
|
||||
|
||||
// We use inverted logic here due to a suspected GitHub bug where first-time contributors
|
||||
// get 'NONE' instead of 'FIRST_TIME_CONTRIBUTOR' or 'FIRST_TIMER'.
|
||||
// https://github.com/orgs/community/discussions/78038
|
||||
// This will break if GitHub ever adds new associations.
|
||||
const association = pr.author_association;
|
||||
const knownAssociations = ['CONTRIBUTOR', 'COLLABORATOR', 'MEMBER', 'OWNER', 'MANNEQUIN'];
|
||||
|
||||
if (knownAssociations.includes(association)) {
|
||||
console.log(`PR #${pr.number} by ${author}: not a first-time contributor (association: '${association}')`);
|
||||
} else {
|
||||
labelsToAdd.push(FIRST_CONTRIBUTION_LABEL);
|
||||
}
|
||||
|
||||
return labelsToAdd;
|
||||
};
|
||||
|
||||
const labelsToAdd = pr ? await getPullRequestLabels() : getIssueLabels();
|
||||
|
||||
if (labelsToAdd.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: target.number,
|
||||
labels: labelsToAdd
|
||||
});
|
||||
|
||||
const targetType = pr ? 'PR' : 'issue';
|
||||
const labels = labelsToAdd.map((label) => `'${label}'`).join(', ');
|
||||
console.log(`${targetType} #${target.number} by ${author}: labeled ${labels}`);
|
||||
} catch (error) {
|
||||
if (pr) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.error(`Failed to label issue #${target.number}: ${error.message}`);
|
||||
}
|
||||
150
.github/workflows/pr_labeler.yml
vendored
|
|
@ -1,150 +0,0 @@
|
|||
# Labels pull requests by author: 'bot' for bot accounts, 'staff' for
|
||||
# staff team members, 'guild' for guild members, 'first contribution' for
|
||||
# first-time external contributors.
|
||||
name: PR Labeler
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
check-authorship-and-label:
|
||||
if: github.repository == 'zed-industries/zed'
|
||||
runs-on: namespace-profile-2x4-ubuntu-2404
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- id: get-app-token
|
||||
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
|
||||
with:
|
||||
app-id: ${{ secrets.ZED_COMMUNITY_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.ZED_COMMUNITY_BOT_PRIVATE_KEY }}
|
||||
owner: zed-industries
|
||||
|
||||
- id: apply-authorship-label
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
with:
|
||||
github-token: ${{ steps.get-app-token.outputs.token }}
|
||||
script: |
|
||||
const BOT_LABEL = 'bot';
|
||||
const STAFF_LABEL = 'staff';
|
||||
const GUILD_LABEL = 'guild';
|
||||
const FIRST_CONTRIBUTION_LABEL = 'first contribution';
|
||||
const STAFF_TEAM_SLUG = 'staff';
|
||||
const GUILD_MEMBERS = [
|
||||
'11happy',
|
||||
'AidanV',
|
||||
'AmaanBilwar',
|
||||
'MostlyKIGuess',
|
||||
'OmChillure',
|
||||
'Palanikannan1437',
|
||||
'Shivansh-25',
|
||||
'SkandaBhat',
|
||||
'TwistingTwists',
|
||||
'YEDASAVG',
|
||||
'Ziqi-Yang',
|
||||
'alanpjohn',
|
||||
'arjunkomath',
|
||||
'austincummings',
|
||||
'ayushk-1801',
|
||||
'criticic',
|
||||
'dongdong867',
|
||||
'emamulandalib',
|
||||
'eureka928',
|
||||
'feitreim',
|
||||
'iam-liam',
|
||||
'iksuddle',
|
||||
'ishaksebsib',
|
||||
'lingyaochu',
|
||||
'loadingalias',
|
||||
'marcocondrache',
|
||||
'mchisolm0',
|
||||
'nairadithya',
|
||||
'nihalxkumar',
|
||||
'notJoon',
|
||||
'polyesterswing',
|
||||
'prayanshchh',
|
||||
'razeghi71',
|
||||
'sarmadgulzar',
|
||||
'seanstrom',
|
||||
'th0jensen',
|
||||
'tommyming',
|
||||
'transitoryangel',
|
||||
'virajbhartiya',
|
||||
];
|
||||
|
||||
const pr = context.payload.pull_request;
|
||||
const author = pr.user.login;
|
||||
|
||||
if (pr.user.type === 'Bot') {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: [BOT_LABEL]
|
||||
});
|
||||
console.log(`PR #${pr.number} by ${author}: labeled '${BOT_LABEL}' (user type: '${pr.user.type}')`);
|
||||
return;
|
||||
}
|
||||
|
||||
let isStaff = false;
|
||||
try {
|
||||
const response = await github.rest.teams.getMembershipForUserInOrg({
|
||||
org: 'zed-industries',
|
||||
team_slug: STAFF_TEAM_SLUG,
|
||||
username: author
|
||||
});
|
||||
isStaff = response.data.state === 'active';
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (isStaff) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: [STAFF_LABEL]
|
||||
});
|
||||
console.log(`PR #${pr.number} by ${author}: labeled '${STAFF_LABEL}' (staff team member)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const authorLower = author.toLowerCase();
|
||||
const isGuildMember = GUILD_MEMBERS.some(
|
||||
(member) => member.toLowerCase() === authorLower
|
||||
);
|
||||
if (isGuildMember) {
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: [GUILD_LABEL]
|
||||
});
|
||||
console.log(`PR #${pr.number} by ${author}: labeled '${GUILD_LABEL}' (guild member)`);
|
||||
// No early return: guild members can also get 'first contribution'
|
||||
}
|
||||
|
||||
// We use inverted logic here due to a suspected GitHub bug where first-time contributors
|
||||
// get 'NONE' instead of 'FIRST_TIME_CONTRIBUTOR' or 'FIRST_TIMER'.
|
||||
// https://github.com/orgs/community/discussions/78038
|
||||
// This will break if GitHub ever adds new associations.
|
||||
const association = pr.author_association;
|
||||
const knownAssociations = ['CONTRIBUTOR', 'COLLABORATOR', 'MEMBER', 'OWNER', 'MANNEQUIN'];
|
||||
|
||||
if (knownAssociations.includes(association)) {
|
||||
console.log(`PR #${pr.number} by ${author}: not a first-time contributor (association: '${association}')`);
|
||||
return;
|
||||
}
|
||||
|
||||
await github.rest.issues.addLabels({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: pr.number,
|
||||
labels: [FIRST_CONTRIBUTION_LABEL]
|
||||
});
|
||||
console.log(`PR #${pr.number} by ${author}: labeled '${FIRST_CONTRIBUTION_LABEL}' (association: '${association}')`);
|
||||
79
.github/workflows/run_bundling.yml
vendored
|
|
@ -264,85 +264,6 @@ jobs:
|
|||
path: target/zed-remote-server-windows-x86_64.zip
|
||||
if-no-files-found: error
|
||||
timeout-minutes: 60
|
||||
build_nix_linux_x86_64:
|
||||
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && github.event.label.name == 'run-bundling') || (github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'run-bundling')))
|
||||
runs-on: namespace-profile-32x64-ubuntu-2004
|
||||
env:
|
||||
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
|
||||
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
|
||||
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
|
||||
GIT_LFS_SKIP_SMUDGE: '1'
|
||||
steps:
|
||||
- name: steps::checkout_repo
|
||||
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
|
||||
with:
|
||||
clean: false
|
||||
- name: steps::cache_nix_dependencies_namespace
|
||||
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
|
||||
with:
|
||||
cache: nix
|
||||
- name: nix_build::build_nix::install_nix
|
||||
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: nix_build::build_nix::cachix_action
|
||||
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
|
||||
with:
|
||||
name: zed
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
cachixArgs: -v
|
||||
pushFilter: -zed-editor-[0-9.]*
|
||||
- name: nix_build::build_nix::build
|
||||
run: nix build .#default -L --accept-flake-config
|
||||
timeout-minutes: 60
|
||||
continue-on-error: true
|
||||
build_nix_mac_aarch64:
|
||||
if: (github.repository_owner == 'zed-industries' || github.repository_owner == 'zed-extensions') && ((github.event.action == 'labeled' && github.event.label.name == 'run-bundling') || (github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'run-bundling')))
|
||||
runs-on: namespace-profile-mac-large
|
||||
env:
|
||||
ZED_CLIENT_CHECKSUM_SEED: ${{ secrets.ZED_CLIENT_CHECKSUM_SEED }}
|
||||
ZED_MINIDUMP_ENDPOINT: ${{ secrets.ZED_SENTRY_MINIDUMP_ENDPOINT }}
|
||||
ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON: ${{ secrets.ZED_CLOUD_PROVIDER_ADDITIONAL_MODELS_JSON }}
|
||||
GIT_LFS_SKIP_SMUDGE: '1'
|
||||
steps:
|
||||
- name: steps::checkout_repo
|
||||
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd
|
||||
with:
|
||||
clean: false
|
||||
- name: steps::cache_nix_store_macos
|
||||
uses: namespacelabs/nscloud-cache-action@a90bb5d4b27522ce881c6e98eebd7d7e6d1653f9
|
||||
with:
|
||||
path: ~/nix-cache
|
||||
- name: nix_build::build_nix::install_nix
|
||||
uses: cachix/install-nix-action@02a151ada4993995686f9ed4f1be7cfbb229e56f
|
||||
with:
|
||||
github_access_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: nix_build::build_nix::configure_local_nix_cache
|
||||
run: |
|
||||
mkdir -p ~/nix-cache
|
||||
echo "extra-substituters = file://$HOME/nix-cache?priority=10" | sudo tee -a /etc/nix/nix.conf
|
||||
echo "require-sigs = false" | sudo tee -a /etc/nix/nix.conf
|
||||
sudo launchctl kickstart -k system/org.nixos.nix-daemon
|
||||
- name: nix_build::build_nix::cachix_action
|
||||
uses: cachix/cachix-action@0fc020193b5a1fa3ac4575aa3a7d3aa6a35435ad
|
||||
with:
|
||||
name: zed
|
||||
authToken: ${{ secrets.CACHIX_AUTH_TOKEN }}
|
||||
cachixArgs: -v
|
||||
pushFilter: -zed-editor-[0-9.]*
|
||||
- name: nix_build::build_nix::build
|
||||
run: nix build .#default -L --accept-flake-config
|
||||
- name: nix_build::build_nix::export_to_local_nix_cache
|
||||
if: always()
|
||||
run: |
|
||||
if [ -L result ]; then
|
||||
echo "Copying build closure to local binary cache..."
|
||||
nix copy --to "file://$HOME/nix-cache" ./result || echo "Warning: nix copy to local cache failed"
|
||||
else
|
||||
echo "No build result found, skipping cache export."
|
||||
fi
|
||||
timeout-minutes: 60
|
||||
continue-on-error: true
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
|
|
|||
|
|
@ -16,8 +16,9 @@ jobs:
|
|||
github.event_name == 'issues' &&
|
||||
github.repository == 'zed-industries/zed' &&
|
||||
github.event.issue.pull_request == null &&
|
||||
github.event.issue.type != null &&
|
||||
(github.event.issue.type.name == 'Bug' || github.event.issue.type.name == 'Crash')
|
||||
(github.event.issue.type == null ||
|
||||
github.event.issue.type.name == 'Bug' ||
|
||||
github.event.issue.type.name == 'Crash')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
|
|
|
|||
3
.gitignore
vendored
|
|
@ -55,3 +55,6 @@ crates/docs_preprocessor/actions.json
|
|||
# Local documentation audit files
|
||||
/december-2025-releases.md
|
||||
/docs/december-2025-documentation-gaps.md
|
||||
|
||||
# NixOS integration test state
|
||||
.nixos-test-history
|
||||
|
|
|
|||
1484
Cargo.lock
generated
37
Cargo.toml
|
|
@ -130,13 +130,13 @@ members = [
|
|||
"crates/lsp",
|
||||
"crates/markdown",
|
||||
"crates/markdown_preview",
|
||||
"crates/mermaid_render",
|
||||
"crates/media",
|
||||
"crates/menu",
|
||||
"crates/migrator",
|
||||
"crates/miniprofiler_ui",
|
||||
"crates/mistral",
|
||||
"crates/multi_buffer",
|
||||
"crates/nc",
|
||||
"crates/net",
|
||||
"crates/node_runtime",
|
||||
"crates/notifications",
|
||||
|
|
@ -171,7 +171,8 @@ members = [
|
|||
"crates/reqwest_client",
|
||||
"crates/rope",
|
||||
"crates/rpc",
|
||||
"crates/rules_library",
|
||||
"crates/sandbox",
|
||||
"crates/skill_creator",
|
||||
"crates/scheduler",
|
||||
"crates/schema_generator",
|
||||
"crates/search",
|
||||
|
|
@ -388,15 +389,14 @@ lmstudio = { path = "crates/lmstudio" }
|
|||
lsp = { path = "crates/lsp" }
|
||||
markdown = { path = "crates/markdown" }
|
||||
markdown_preview = { path = "crates/markdown_preview" }
|
||||
mermaid_render = { path = "crates/mermaid_render" }
|
||||
svg_preview = { path = "crates/svg_preview" }
|
||||
media = { path = "crates/media" }
|
||||
menu = { path = "crates/menu" }
|
||||
mermaid-rs-renderer = { git = "https://github.com/zed-industries/mermaid-rs-renderer", rev = "782b89a7da3f0e91e51f98d00a93acba679be6fb", default-features = false }
|
||||
migrator = { path = "crates/migrator" }
|
||||
mistral = { path = "crates/mistral" }
|
||||
multi_buffer = { path = "crates/multi_buffer" }
|
||||
miniprofiler_ui = { path = "crates/miniprofiler_ui" }
|
||||
nc = { path = "crates/nc" }
|
||||
net = { path = "crates/net" }
|
||||
node_runtime = { path = "crates/node_runtime" }
|
||||
notifications = { path = "crates/notifications" }
|
||||
|
|
@ -431,8 +431,9 @@ reqwest_client = { path = "crates/reqwest_client" }
|
|||
rodio = { git = "https://github.com/RustAudio/rodio", rev = "e50e726ddd0292f6ef9de0dda6b90af4ed1fb66a", features = ["wav", "playback", "wav_output", "recording"] }
|
||||
rope = { path = "crates/rope" }
|
||||
rpc = { path = "crates/rpc" }
|
||||
rules_library = { path = "crates/rules_library" }
|
||||
skill_creator = { path = "crates/skill_creator" }
|
||||
scheduler = { path = "crates/scheduler" }
|
||||
sandbox = { path = "crates/sandbox" }
|
||||
search = { path = "crates/search" }
|
||||
session = { path = "crates/session" }
|
||||
sidebar = { path = "crates/sidebar" }
|
||||
|
|
@ -500,9 +501,13 @@ ztracing_macro = { path = "crates/ztracing_macro" }
|
|||
# External crates
|
||||
#
|
||||
|
||||
agent-client-protocol = { version = "=0.11.1", features = ["unstable"] }
|
||||
accesskit = "0.24.0"
|
||||
accesskit_macos = "0.26.0"
|
||||
accesskit_unix = "0.21.0"
|
||||
accesskit_windows = "0.32.1"
|
||||
agent-client-protocol = { version = "=0.12.1", features = ["unstable"] }
|
||||
aho-corasick = "1.1"
|
||||
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "9d9640d4" }
|
||||
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "fcf32feacb367b75ec84dd40f041e4fd411d3cc1" }
|
||||
any_vec = "0.14"
|
||||
anyhow = "1.0.86"
|
||||
ashpd = { version = "0.13", default-features = false, features = [
|
||||
|
|
@ -554,14 +559,14 @@ clap = { version = "4.4", features = ["derive", "wrap_help"] }
|
|||
cocoa = "=0.26.0"
|
||||
cocoa-foundation = "=0.2.0"
|
||||
const_format = "0.2"
|
||||
convert_case = "0.8.0"
|
||||
convert_case = "0.11.0"
|
||||
core-foundation = "=0.10.0"
|
||||
core-foundation-sys = "0.8.6"
|
||||
core-video = { version = "0.5.2", features = ["metal"] }
|
||||
cpal = "0.17"
|
||||
crash-handler = "0.7"
|
||||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
ctor = "0.4.0"
|
||||
ctor = "1.0.6"
|
||||
dap-types = { git = "https://github.com/zed-industries/dap-types", rev = "1b461b310481d01e02b2603c16d7144b926339f8" }
|
||||
dashmap = "6.0"
|
||||
derive_more = { version = "2.1.1", features = [
|
||||
|
|
@ -590,7 +595,7 @@ futures = "0.3.32"
|
|||
futures-concurrency = "7.7.1"
|
||||
futures-lite = "1.13"
|
||||
gh-workflow = { git = "https://github.com/zed-industries/gh-workflow", rev = "37f3c0575d379c218a9c455ee67585184e40d43f" }
|
||||
git2 = { version = "0.20.1", default-features = false, features = ["vendored-libgit2"] }
|
||||
git2 = { version = "0.21.0", default-features = false, features = ["vendored-libgit2", "unstable-sha256"] }
|
||||
globset = "0.4"
|
||||
heapless = "0.9.2"
|
||||
handlebars = "4.3"
|
||||
|
|
@ -620,6 +625,7 @@ linkify = "0.10.0"
|
|||
libwebrtc = "0.3.26"
|
||||
livekit = { version = "0.7.32", features = ["tokio", "rustls-tls-native-roots"] }
|
||||
log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] }
|
||||
lru = "0.16"
|
||||
lsp-types = { git = "https://github.com/zed-industries/lsp-types", rev = "f4dfa89a21ca35cd929b70354b1583fabae325f8" }
|
||||
mach2 = "0.5"
|
||||
markup5ever_rcdom = "0.3.0"
|
||||
|
|
@ -721,6 +727,7 @@ serde_json_lenient = { version = "0.2", features = [
|
|||
"preserve_order",
|
||||
"raw_value",
|
||||
] }
|
||||
serde_yaml = "0.9.34"
|
||||
serde_path_to_error = "0.1.17"
|
||||
serde_urlencoded = "0.7"
|
||||
sha2 = "0.10"
|
||||
|
|
@ -762,7 +769,7 @@ toml_edit = { version = "0.22", default-features = false, features = [
|
|||
"serde",
|
||||
] }
|
||||
tower-http = "0.4.4"
|
||||
tree-sitter = { version = "0.26.8", features = ["wasm"] }
|
||||
tree-sitter = { version = "0.26.9", features = ["wasm"] }
|
||||
tree-sitter-bash = "0.25.1"
|
||||
tree-sitter-c = "0.24.1"
|
||||
tree-sitter-cpp = { git = "https://github.com/tree-sitter/tree-sitter-cpp", rev = "5cb9b693cfd7bfacab1d9ff4acac1a4150700609" }
|
||||
|
|
@ -812,7 +819,7 @@ which = "6.0.0"
|
|||
wasm-bindgen = "0.2.120"
|
||||
web-time = "1.1.0"
|
||||
webrtc-sys = "0.3.23"
|
||||
wgpu = { git = "https://github.com/zed-industries/wgpu.git", branch = "v29" }
|
||||
wgpu = { git = "https://github.com/zed-industries/wgpu.git", rev = "357a0c56e0070480ad9daea5d2eaa83150b79e88" }
|
||||
windows-core = "0.61"
|
||||
yaml-rust2 = "0.8"
|
||||
yawc = "0.2.5"
|
||||
|
|
@ -884,9 +891,9 @@ notify = { git = "https://github.com/zed-industries/notify.git", rev = "ce58c24c
|
|||
notify-types = { git = "https://github.com/zed-industries/notify.git", rev = "ce58c24cad542c28e04ced02e20325a4ec28a31d" }
|
||||
windows-capture = { git = "https://github.com/zed-industries/windows-capture.git", rev = "f0d6c1b6691db75461b732f6d5ff56eed002eeb9" }
|
||||
calloop = { git = "https://github.com/zed-industries/calloop" }
|
||||
livekit = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
|
||||
libwebrtc = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
|
||||
webrtc-sys = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "147fbca3d4b592d96d33f5e6a84b59fc0b5d9bf1" }
|
||||
livekit = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
|
||||
libwebrtc = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
|
||||
webrtc-sys = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "c3a55bbc207008f1ca3474b6037fdd3c443cad0f" }
|
||||
|
||||
[profile.dev]
|
||||
split-debuginfo = "unpacked"
|
||||
|
|
|
|||
788
LICENSE-AGPL
|
|
@ -1,788 +0,0 @@
|
|||
Copyright 2022 - 2025 Zed Industries, Inc.
|
||||
|
||||
|
||||
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
Preamble
|
||||
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
|
||||
0. Definitions.
|
||||
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
|
||||
1. Source Code.
|
||||
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
|
||||
8. Termination.
|
||||
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
|
||||
11. Patents.
|
||||
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
|
@ -13,7 +13,7 @@ On macOS, Linux, and Windows you can [download Zed directly](https://zed.dev/dow
|
|||
|
||||
Other platforms are not yet available:
|
||||
|
||||
- Web ([tracking issue](https://github.com/zed-industries/zed/issues/5396))
|
||||
- Web ([tracking discussion](https://github.com/zed-industries/zed/discussions/26195))
|
||||
|
||||
### Developing Zed
|
||||
|
||||
|
|
@ -29,6 +29,8 @@ Also... we're hiring! Check out our [jobs](https://zed.dev/jobs) page for open r
|
|||
|
||||
### Licensing
|
||||
|
||||
Zed source code is licensed primarily under GPL-3.0-or-later, with Apache-2.0 components where marked.
|
||||
|
||||
License information for third party dependencies must be correctly provided for CI to pass.
|
||||
|
||||
We use [`cargo-about`](https://github.com/EmbarkStudios/cargo-about) to automatically comply with open source licenses. If CI is failing, check the following:
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path opacity="0.3" d="M9 1.5H3C2.17157 1.5 1.5 2.17157 1.5 3V9C1.5 9.82843 2.17157 10.5 3 10.5H9C9.82843 10.5 10.5 9.82843 10.5 9V3C10.5 2.17157 9.82843 1.5 9 1.5Z" stroke="#C6CAD0" stroke-width="0.9"/>
|
||||
<path d="M4.32058 8.53711C3.99873 8.53711 3.79672 8.34879 3.79672 8.05092C3.79672 7.96532 3.82069 7.84891 3.8652 7.72222L5.21422 4.04838C5.35802 3.64778 5.60112 3.46289 5.99144 3.46289C6.39546 3.46289 6.63514 3.64093 6.78236 4.04495L8.13823 7.72222C8.18616 7.85575 8.20328 7.9482 8.20328 8.05092C8.20328 8.3351 7.98758 8.53711 7.68627 8.53711C7.39524 8.53711 7.24117 8.40358 7.14872 8.08173L6.8885 7.30108H5.10465L4.84444 8.07146C4.74857 8.40015 4.59449 8.53711 4.32058 8.53711ZM5.33063 6.49989H6.64883L5.99487 4.47636H5.9709L5.33063 6.49989Z" fill="#C6CAD0"/>
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M5.76074 11.3828C5.3316 11.3828 5.06226 11.1317 5.06226 10.7346C5.06226 10.6204 5.09422 10.4652 5.15356 10.2963L6.95226 5.39784C7.14399 4.86371 7.46812 4.61719 7.98855 4.61719C8.52724 4.61719 8.84682 4.85457 9.04311 5.39327L10.8509 10.2963C10.9148 10.4743 10.9377 10.5976 10.9377 10.7346C10.9377 11.1135 10.6501 11.3828 10.2483 11.3828C9.86028 11.3828 9.65486 11.2048 9.53159 10.7756L9.18463 9.73477H6.80616L6.45922 10.7619C6.33139 11.2002 6.12595 11.3828 5.76074 11.3828ZM7.10747 8.66652H8.86507L7.99312 5.96848H7.96116L7.10747 8.66652Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.3" d="M12 2H4C2.89543 2 2 2.89543 2 4V12C2 13.1046 2.89543 14 4 14H12C13.1046 14 14 13.1046 14 12V4C14 2.89543 13.1046 2 12 2Z" stroke="#C6CAD0" stroke-width="1.2"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 868 B After Width: | Height: | Size: 851 B |
|
|
@ -1,15 +1,15 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M12.146 2H4.85398C3.55391 2 2.5 3.05391 2.5 4.35398V11.646C2.5 12.9461 3.55391 14 4.85398 14H12.146C13.4461 14 14.5 12.9461 14.5 11.646V4.35398C14.5 3.05391 13.4461 2 12.146 2Z" stroke="black" stroke-width="1.11504"/>
|
||||
<path opacity="0.487119" d="M10.5177 3.60177H6.21681C5.8698 3.60177 5.58849 3.88308 5.58849 4.23009V4.23894C5.58849 4.58595 5.8698 4.86726 6.21681 4.86726H10.5177C10.8647 4.86726 11.146 4.58595 11.146 4.23894V4.23009C11.146 3.88308 10.8647 3.60177 10.5177 3.60177Z" fill="black"/>
|
||||
<path opacity="0.845099" d="M8.83628 3.60177H4.53539C4.18838 3.60177 3.90707 3.88308 3.90707 4.23009V4.23894C3.90707 4.58595 4.18838 4.86726 4.53539 4.86726H8.83628C9.18329 4.86726 9.4646 4.58595 9.4646 4.23894V4.23009C9.4646 3.88308 9.18329 3.60177 8.83628 3.60177Z" fill="black"/>
|
||||
<path opacity="0.487119" d="M12.7389 5.10619H8.43806C8.09105 5.10619 7.80974 5.3875 7.80974 5.73451V5.74336C7.80974 6.09037 8.09105 6.37168 8.43806 6.37168H12.7389C13.086 6.37168 13.3673 6.09037 13.3673 5.74336V5.73451C13.3673 5.3875 13.086 5.10619 12.7389 5.10619Z" fill="black"/>
|
||||
<path opacity="0.845099" d="M11.0575 5.10619H6.75664C6.40963 5.10619 6.12832 5.3875 6.12832 5.73451V5.74336C6.12832 6.09037 6.40963 6.37168 6.75664 6.37168H11.0575C11.4045 6.37168 11.6858 6.09037 11.6858 5.74336V5.73451C11.6858 5.3875 11.4045 5.10619 11.0575 5.10619Z" fill="black"/>
|
||||
<path opacity="0.487119" d="M11.5619 6.59292H7.26106C6.91405 6.59292 6.63274 6.87423 6.63274 7.22124V7.23009C6.63274 7.5771 6.91405 7.85841 7.26106 7.85841H11.5619C11.909 7.85841 12.1903 7.5771 12.1903 7.23009V7.22124C12.1903 6.87423 11.909 6.59292 11.5619 6.59292Z" fill="black"/>
|
||||
<path opacity="0.845099" d="M9.86284 6.59292H5.56195C5.21494 6.59292 4.93363 6.87423 4.93363 7.22124V7.23009C4.93363 7.5771 5.21494 7.85841 5.56195 7.85841H9.86284C10.2098 7.85841 10.4912 7.5771 10.4912 7.23009V7.22124C10.4912 6.87423 10.2098 6.59292 9.86284 6.59292Z" fill="black"/>
|
||||
<path opacity="0.487119" d="M10.1903 8.10619H5.88937C5.54236 8.10619 5.26105 8.3875 5.26105 8.73451V8.74336C5.26105 9.09037 5.54236 9.37168 5.88937 9.37168H10.1903C10.5373 9.37168 10.8186 9.09037 10.8186 8.74336V8.73451C10.8186 8.3875 10.5373 8.10619 10.1903 8.10619Z" fill="black"/>
|
||||
<path opacity="0.845099" d="M8.50886 8.10619H4.20797C3.86096 8.10619 3.57965 8.3875 3.57965 8.73451V8.74336C3.57965 9.09037 3.86096 9.37168 4.20797 9.37168H8.50886C8.85587 9.37168 9.13717 9.09037 9.13717 8.74336V8.73451C9.13717 8.3875 8.85587 8.10619 8.50886 8.10619Z" fill="black"/>
|
||||
<path opacity="0.487119" d="M10.9513 9.59292H7.37611C7.0291 9.59292 6.74779 9.87423 6.74779 10.2212V10.2301C6.74779 10.5771 7.0291 10.8584 7.37611 10.8584H10.9513C11.2983 10.8584 11.5796 10.5771 11.5796 10.2301V10.2212C11.5796 9.87423 11.2983 9.59292 10.9513 9.59292Z" fill="black"/>
|
||||
<path opacity="0.845099" d="M9.23452 9.59292H5.65929C5.31228 9.59292 5.03098 9.87423 5.03098 10.2212V10.2301C5.03098 10.5771 5.31228 10.8584 5.65929 10.8584H9.23452C9.58153 10.8584 9.86283 10.5771 9.86283 10.2301V10.2212C9.86283 9.87423 9.58153 9.59292 9.23452 9.59292Z" fill="black"/>
|
||||
<path opacity="0.487119" d="M12.6062 11.0973H9.82744C9.48043 11.0973 9.19912 11.3787 9.19912 11.7257V11.7345C9.19912 12.0815 9.48043 12.3628 9.82744 12.3628H12.6062C12.9532 12.3628 13.2345 12.0815 13.2345 11.7345V11.7257C13.2345 11.3787 12.9532 11.0973 12.6062 11.0973Z" fill="black"/>
|
||||
<path opacity="0.845099" d="M10.7389 11.0973H7.96017C7.61316 11.0973 7.33186 11.3787 7.33186 11.7257V11.7345C7.33186 12.0815 7.61316 12.3628 7.96017 12.3628H10.7389C11.0859 12.3628 11.3673 12.0815 11.3673 11.7345V11.7257C11.3673 11.3787 11.0859 11.0973 10.7389 11.0973Z" fill="black"/>
|
||||
<path d="M11.646 2H4.35398C3.05391 2 2 3.05391 2 4.35398V11.646C2 12.9461 3.05391 14 4.35398 14H11.646C12.9461 14 14 12.9461 14 11.646V4.35398C14 3.05391 12.9461 2 11.646 2Z" stroke="#C6CAD0" stroke-width="1.11504"/>
|
||||
<path opacity="0.487119" d="M10.0177 3.60178H5.71681C5.3698 3.60178 5.08849 3.88309 5.08849 4.2301V4.23895C5.08849 4.58596 5.3698 4.86727 5.71681 4.86727H10.0177C10.3647 4.86727 10.646 4.58596 10.646 4.23895V4.2301C10.646 3.88309 10.3647 3.60178 10.0177 3.60178Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.845099" d="M8.33628 3.60178H4.03539C3.68838 3.60178 3.40707 3.88309 3.40707 4.2301V4.23895C3.40707 4.58596 3.68838 4.86727 4.03539 4.86727H8.33628C8.68329 4.86727 8.9646 4.58596 8.9646 4.23895V4.2301C8.9646 3.88309 8.68329 3.60178 8.33628 3.60178Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.487119" d="M12.2389 5.1062H7.93806C7.59105 5.1062 7.30974 5.38751 7.30974 5.73452V5.74337C7.30974 6.09038 7.59105 6.37169 7.93806 6.37169H12.2389C12.586 6.37169 12.8673 6.09038 12.8673 5.74337V5.73452C12.8673 5.38751 12.586 5.1062 12.2389 5.1062Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.845099" d="M10.5575 5.1062H6.25665C5.90964 5.1062 5.62833 5.38751 5.62833 5.73452V5.74337C5.62833 6.09038 5.90964 6.37169 6.25665 6.37169H10.5575C10.9045 6.37169 11.1858 6.09038 11.1858 5.74337V5.73452C11.1858 5.38751 10.9045 5.1062 10.5575 5.1062Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.487119" d="M11.0619 6.59293H6.76106C6.41405 6.59293 6.13274 6.87424 6.13274 7.22125V7.2301C6.13274 7.57711 6.41405 7.85842 6.76106 7.85842H11.0619C11.409 7.85842 11.6903 7.57711 11.6903 7.2301V7.22125C11.6903 6.87424 11.409 6.59293 11.0619 6.59293Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.845099" d="M9.36283 6.59293H5.06194C4.71493 6.59293 4.43362 6.87424 4.43362 7.22125V7.2301C4.43362 7.57711 4.71493 7.85842 5.06194 7.85842H9.36283C9.70979 7.85842 9.99119 7.57711 9.99119 7.2301V7.22125C9.99119 6.87424 9.70979 6.59293 9.36283 6.59293Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.487119" d="M9.6903 8.1062H5.38937C5.04236 8.1062 4.76105 8.38751 4.76105 8.73452V8.74337C4.76105 9.09038 5.04236 9.37169 5.38937 9.37169H9.6903C10.0373 9.37169 10.3186 9.09038 10.3186 8.74337V8.73452C10.3186 8.38751 10.0373 8.1062 9.6903 8.1062Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.845099" d="M8.00886 8.1062H3.70797C3.36096 8.1062 3.07965 8.38751 3.07965 8.73452V8.74337C3.07965 9.09038 3.36096 9.37169 3.70797 9.37169H8.00886C8.35587 9.37169 8.63717 9.09038 8.63717 8.74337V8.73452C8.63717 8.38751 8.35587 8.1062 8.00886 8.1062Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.487119" d="M10.4513 9.59293H6.87611C6.5291 9.59293 6.24779 9.87424 6.24779 10.2212V10.2301C6.24779 10.5771 6.5291 10.8584 6.87611 10.8584H10.4513C10.7983 10.8584 11.0796 10.5771 11.0796 10.2301V10.2212C11.0796 9.87424 10.7983 9.59293 10.4513 9.59293Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.845099" d="M8.73452 9.59293H5.15929C4.81228 9.59293 4.53098 9.87424 4.53098 10.2212V10.2301C4.53098 10.5771 4.81228 10.8584 5.15929 10.8584H8.73452C9.08153 10.8584 9.36283 10.5771 9.36283 10.2301V10.2212C9.36283 9.87424 9.08153 9.59293 8.73452 9.59293Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.487119" d="M12.1062 11.0973H9.32745C8.98044 11.0973 8.69913 11.3787 8.69913 11.7257V11.7345C8.69913 12.0815 8.98044 12.3628 9.32745 12.3628H12.1062C12.4532 12.3628 12.7345 12.0815 12.7345 11.7345V11.7257C12.7345 11.3787 12.4532 11.0973 12.1062 11.0973Z" fill="#C6CAD0"/>
|
||||
<path opacity="0.845099" d="M10.2389 11.0973H7.46017C7.11316 11.0973 6.83186 11.3787 6.83186 11.7257V11.7345C6.83186 12.0815 7.11316 12.3628 7.46017 12.3628H10.2389C10.5859 12.3628 10.8673 12.0815 10.8673 11.7345V11.7257C10.8673 11.3787 10.5859 11.0973 10.2389 11.0973Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 8.3 KiB After Width: | Height: | Size: 8.4 KiB |
|
|
@ -1,3 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M14.5768 6.73011C14.8987 5.77678 14.7879 4.73245 14.2731 3.86531C13.4989 2.53528 11.9427 1.85102 10.4227 2.17303C9.74656 1.42139 8.7751 0.993944 7.75664 1.00006C6.20301 0.996569 4.82452 1.98358 4.34655 3.44224C3.34849 3.64393 2.48699 4.26038 1.98286 5.13408C1.20294 6.46061 1.38074 8.13277 2.4227 9.27029C2.1008 10.2236 2.21164 11.268 2.72642 12.1351C3.50057 13.4651 5.05686 14.1494 6.57679 13.8274C7.25251 14.579 8.22441 15.0064 9.24287 14.9999C10.7974 15.0038 12.1763 14.0159 12.6543 12.556C13.6524 12.3543 14.5139 11.7379 15.018 10.8641C15.797 9.5376 15.6188 7.86676 14.5773 6.72924L14.5768 6.73011ZM9.24376 14.0851C8.62169 14.0859 8.01912 13.8711 7.5416 13.4778C7.56332 13.4664 7.60101 13.4459 7.6254 13.431L10.4507 11.821C10.5952 11.7401 10.6839 11.5882 10.683 11.4242V7.49401L11.877 8.17433C11.8899 8.18045 11.8983 8.1927 11.9001 8.2067V11.4614C11.8983 12.9086 10.7105 14.082 9.24376 14.0851ZM3.53116 11.6775C3.21946 11.1464 3.10729 10.5237 3.21414 9.91955C3.23498 9.9318 3.27178 9.95411 3.29794 9.96898L6.1232 11.5791C6.26642 11.6617 6.44377 11.6617 6.58743 11.5791L10.0365 9.61373V10.9744C10.0374 10.9884 10.0308 11.002 10.0197 11.0107L7.16383 12.6378C5.89175 13.3606 4.26674 12.9309 3.53116 11.6775ZM2.7876 5.59215C3.09797 5.06014 3.58792 4.65326 4.17141 4.44195C4.17141 4.46601 4.17008 4.50845 4.17008 4.5382V7.75869C4.1692 7.92232 4.25787 8.07414 4.40198 8.15508L7.85108 10.1199L6.65704 10.8002C6.64507 10.8081 6.62999 10.8094 6.61669 10.8037L3.76039 9.17535C2.49098 8.44995 2.05601 6.84692 2.7876 5.59215ZM12.598 7.84488L9.14887 5.8796L10.3429 5.19971C10.3549 5.19183 10.37 5.19052 10.3833 5.19621L13.2396 6.8233C14.5112 7.54826 14.947 9.15347 14.2124 10.4082C13.9015 10.9394 13.412 11.3463 12.829 11.5581V8.24127C12.8303 8.07764 12.7417 7.92626 12.598 7.84488ZM13.7863 6.07998C13.7654 6.06729 13.7286 6.04541 13.7025 6.03054L10.8772 4.42051C10.734 4.33782 10.5566 4.33782 10.413 4.42051L6.96386 6.3858V5.02514C6.96298 5.01114 6.96963 4.99758 6.98071 4.98883L9.83657 3.36305C11.1086 2.63898 12.735 3.06992 13.4683 4.32557C13.7783 4.85583 13.8914 5.47665 13.7863 6.07998ZM6.31475 8.50509L5.12026 7.82476C5.1074 7.81863 5.09898 7.80638 5.09721 7.79238V4.53776C5.09809 3.08873 6.28947 1.91446 7.75797 1.91533C8.37916 1.91533 8.98039 2.13059 9.45792 2.52259C9.43619 2.53397 9.39894 2.55453 9.37412 2.56941L6.54885 4.17944C6.40431 4.26038 6.31563 4.41176 6.31652 4.57582L6.31475 8.50509ZM6.96342 7.12518L8.49976 6.24973L10.0361 7.12475V8.87521L8.49976 9.75023L6.96342 8.87521V7.12518Z" fill="black"/>
|
||||
<path d="M14.0768 6.73011C14.3987 5.77678 14.2879 4.73245 13.7731 3.86531C12.9989 2.53528 11.4427 1.85102 9.9227 2.17303C9.24656 1.42139 8.2751 0.993949 7.25664 1.00006C5.70301 0.996574 4.32452 1.98358 3.84655 3.44224C2.84849 3.64393 1.98699 4.26038 1.48286 5.13408C0.702939 6.46061 0.880738 8.13278 1.9227 9.2703C1.6008 10.2236 1.71164 11.268 2.22642 12.1351C3.00057 13.4651 4.55686 14.1494 6.07679 13.8274C6.75251 14.579 7.72441 15.0064 8.74287 14.9999C10.2974 15.0038 11.6763 14.0159 12.1543 12.556C13.1524 12.3543 14.0139 11.7379 14.518 10.8641C15.297 9.53761 15.1188 7.86676 14.0773 6.72924L14.0768 6.73011ZM8.74376 14.0851C8.12169 14.0859 7.51912 13.8711 7.0416 13.4778C7.06332 13.4664 7.10101 13.4459 7.1254 13.431L9.9507 11.821C10.0952 11.7401 10.1839 11.5882 10.183 11.4242V7.49401L11.377 8.17433C11.3899 8.18045 11.3983 8.19271 11.4001 8.20671V11.4614C11.3983 12.9086 10.2105 14.082 8.74376 14.0851ZM3.03116 11.6775C2.71946 11.1464 2.60729 10.5237 2.71414 9.91955C2.73498 9.9318 2.77178 9.95411 2.79794 9.96898L5.6232 11.5791C5.76642 11.6617 5.94377 11.6617 6.08743 11.5791L9.5365 9.61374V10.9744C9.5374 10.9884 9.5308 11.002 9.5197 11.0107L6.66383 12.6378C5.39175 13.3606 3.76674 12.9309 3.03116 11.6775ZM2.2876 5.59215C2.59797 5.06014 3.08792 4.65326 3.67141 4.44195C3.67141 4.46601 3.67008 4.50845 3.67008 4.5382V7.75869C3.6692 7.92232 3.75787 8.07414 3.90198 8.15508L7.35108 10.1199L6.15704 10.8002C6.14507 10.8081 6.12999 10.8094 6.11669 10.8037L3.26039 9.17535C1.99098 8.44995 1.55601 6.84693 2.2876 5.59215ZM12.098 7.84488L8.64887 5.8796L9.8429 5.19971C9.8549 5.19183 9.87 5.19052 9.8833 5.19621L12.7396 6.8233C14.0112 7.54826 14.447 9.15348 13.7124 10.4082C13.4015 10.9394 12.912 11.3463 12.329 11.5581V8.24127C12.3303 8.07764 12.2417 7.92626 12.098 7.84488ZM13.2863 6.07998C13.2654 6.06729 13.2286 6.04541 13.2025 6.03054L10.3772 4.42051C10.234 4.33782 10.0566 4.33782 9.913 4.42051L6.46386 6.3858V5.02514C6.46298 5.01114 6.46963 4.99758 6.48071 4.98883L9.33657 3.36305C10.6086 2.63898 12.235 3.06992 12.9683 4.32557C13.2783 4.85583 13.3914 5.47665 13.2863 6.07998ZM5.81475 8.50509L4.62026 7.82476C4.6074 7.81863 4.59898 7.80638 4.59721 7.79238V4.53776C4.59809 3.08873 5.78947 1.91446 7.25797 1.91533C7.87916 1.91533 8.48039 2.13059 8.95792 2.52259C8.93619 2.53397 8.89894 2.55453 8.87412 2.56941L6.04885 4.17944C5.90431 4.26038 5.81563 4.41176 5.81652 4.57582L5.81475 8.50509ZM6.46342 7.12518L7.99976 6.24973L9.5361 7.12475V8.87521L7.99976 9.75023L6.46342 8.87521V7.12518Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
|
@ -1,3 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M12.8451 5.50949L13.1109 15H15.2342L15.5 2.05527L12.8451 5.50949ZM15.499 1H12.2574L7.17206 7.61904L8.79335 9.72761L15.499 1ZM1.5 14.999H4.73963L6.36092 12.8905L4.73963 10.7809L1.5 14.999ZM1.5 5.50851L8.79335 14.999H12.034L4.74061 5.50949L1.5 5.50851Z" fill="black"/>
|
||||
<path d="M12.3451 5.50949L12.6109 15H14.7342L15 2.05527L12.3451 5.50949ZM14.999 1H11.7574L6.67206 7.61904L8.29335 9.72761L14.999 1ZM1 14.999H4.23963L5.86092 12.8905L4.23963 10.7809L1 14.999ZM1 5.50851L8.29335 14.999H11.534L4.24061 5.50949L1 5.50851Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 379 B After Width: | Height: | Size: 371 B |
|
|
@ -1,3 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.625 2.75C3.4179 2.75 3.25 2.9179 3.25 3.125V11.375H2.5V3.125C2.5 2.50368 3.00368 2 3.625 2H13.6723C14.1735 2 14.4244 2.6059 14.0701 2.96025L7.88189 9.14843H9.625V8.375H10.375V9.33593C10.375 9.6466 10.1232 9.8984 9.8125 9.8984H7.13189L5.84282 11.1875H11.6875V6.5H12.4375V11.1875C12.4375 11.6017 12.1017 11.9375 11.6875 11.9375H5.09282L3.78032 13.25H13.375C13.5821 13.25 13.75 13.0821 13.75 12.875V4.625H14.5V12.875C14.5 13.4963 13.9963 14 13.375 14H3.32767C2.82653 14 2.57557 13.3941 2.92992 13.0397L9.09468 6.875H7.375V7.625H6.625V6.6875C6.625 6.37684 6.87684 6.125 7.1875 6.125H9.84468L11.1571 4.8125H5.3125V9.5H4.5625V4.8125C4.5625 4.39829 4.89829 4.0625 5.3125 4.0625H11.9071L13.2197 2.75H3.625Z" fill="black"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.125 2.75C2.9179 2.75 2.75 2.9179 2.75 3.125V11.375H2V3.125C2 2.50368 2.50368 2 3.125 2H13.1723C13.6735 2 13.9244 2.6059 13.5701 2.96025L7.38189 9.14843H9.125V8.375H9.875V9.33593C9.875 9.6466 9.6232 9.8984 9.3125 9.8984H6.63189L5.34282 11.1875H11.1875V6.5H11.9375V11.1875C11.9375 11.6017 11.6017 11.9375 11.1875 11.9375H4.59282L3.28032 13.25H12.875C13.0821 13.25 13.25 13.0821 13.25 12.875V4.625H14V12.875C14 13.4963 13.4963 14 12.875 14H2.82767C2.32653 14 2.07557 13.3941 2.42992 13.0397L8.59468 6.875H6.875V7.625H6.125V6.6875C6.125 6.37684 6.37684 6.125 6.6875 6.125H9.34468L10.6571 4.8125H4.8125V9.5H4.0625V4.8125C4.0625 4.39829 4.39829 4.0625 4.8125 4.0625H11.4071L12.7197 2.75H3.125Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 870 B After Width: | Height: | Size: 861 B |
3
assets/icons/bitbucket.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M2.38893 2.60654C2.33283 2.6058 2.27725 2.61737 2.2261 2.64042C2.17496 2.66347 2.12948 2.69745 2.09288 2.73996C2.05627 2.78247 2.02943 2.83249 2.01423 2.8865C1.99904 2.9405 1.99586 2.99718 2.00492 3.05254L3.63644 12.9576C3.67844 13.2076 3.89394 13.3916 4.14744 13.3941H11.975C12.0672 13.3951 12.1567 13.3631 12.2273 13.3039C12.2979 13.2446 12.345 13.1621 12.36 13.0711L13.995 3.05604C14.004 3.00072 14.0008 2.94409 13.9856 2.89015C13.9703 2.83621 13.9435 2.78626 13.9069 2.7438C13.8703 2.70134 13.8248 2.66741 13.7737 2.64439C13.7226 2.62137 13.6671 2.60982 13.611 2.61054L2.38893 2.60654ZM9.26 9.76511H6.76097L6.08496 6.23308H9.8655L9.26 9.76511Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 778 B |
|
|
@ -1,3 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M8 11C9.65685 11 11 9.65685 11 8C11 6.34315 9.65685 5 8 5C6.34315 5 5 6.34315 5 8C5 9.65685 6.34315 11 8 11Z" fill="black"/>
|
||||
<path d="M8 12C10.2091 12 12 10.2091 12 8C12 5.79087 10.2091 4 8 4C5.79087 4 4 5.79087 4 8C4 10.2091 5.79087 12 8 12Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 237 B After Width: | Height: | Size: 239 B |
3
assets/icons/codeberg.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M7.99947 2.00001C7.15863 1.99826 6.32573 2.16261 5.54858 2.48364C4.77144 2.80466 4.06536 3.27604 3.4709 3.87071C2.87644 4.46537 2.40529 5.1716 2.08452 5.94885C1.76376 6.7261 1.59968 7.55906 1.60172 8.39989C1.60172 9.6017 1.94029 10.7806 2.57906 11.7995L7.91309 4.90217C7.95148 4.85311 8.04692 4.85311 8.08531 4.90217L10.313 7.78246H8.71767L8.75233 7.90989H10.4122L10.8824 8.51666H8.92348L8.9784 8.71608H11.0365L11.4508 9.25087H9.12716L9.19914 9.5084H11.6481L12.0187 9.98507H9.33244L9.42042 10.2991H12.2602L12.5849 10.7177H9.53665L9.63369 11.0642H12.8531L13.1527 11.4519H9.74193L9.83951 11.7984H13.4209C14.0594 10.7799 14.3982 9.60205 14.3983 8.39989C14.4001 7.55903 14.2359 6.72608 13.9149 5.94885C13.594 5.17163 13.1228 4.46543 12.5283 3.8708C11.9337 3.27616 11.2276 2.8048 10.4504 2.48376C9.67326 2.16272 8.84033 1.99833 7.99947 2.00001ZM9.94774 12.1861L10.0448 12.5327H12.8846C12.9768 12.4239 13.0728 12.3018 13.1581 12.1861H9.94774ZM10.153 12.9203L10.249 13.2669H12.1488C12.273 13.1613 12.4073 13.0386 12.5284 12.9203H10.153ZM10.3572 13.6545L10.4543 14H11.0957C11.2855 13.8912 11.4609 13.7803 11.6513 13.6545H10.3572Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
|
Before Width: | Height: | Size: 6.3 KiB After Width: | Height: | Size: 6.3 KiB |
|
|
@ -1,3 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M13.2806 4.66818L8.26042 1.76982C8.09921 1.67673 7.9003 1.67673 7.73909 1.76982L2.71918 4.66818C2.58367 4.74642 2.5 4.89112 2.5 5.04785V10.8924C2.5 11.0489 2.58367 11.1938 2.71918 11.2721L7.73934 14.1704C7.90054 14.2635 8.09946 14.2635 8.26066 14.1704L13.2808 11.2721C13.4163 11.1938 13.5 11.0491 13.5 10.8924V5.04785C13.5 4.89136 13.4163 4.74642 13.2808 4.66818H13.2806ZM12.9653 5.28212L8.11901 13.676C8.08626 13.7326 7.99977 13.7095 7.99977 13.6439V8.14771C7.99977 8.03788 7.94107 7.9363 7.84586 7.88115L3.08613 5.13317C3.02957 5.10041 3.05266 5.0139 3.11818 5.0139H12.8106C12.9483 5.0139 13.0343 5.1631 12.9655 5.28236H12.9653V5.28212Z" fill="#C4CAD4"/>
|
||||
<path d="M13.2806 4.69807L8.26042 1.79971C8.09921 1.70662 7.9003 1.70662 7.73909 1.79971L2.71918 4.69807C2.58367 4.77631 2.5 4.92101 2.5 5.07774V10.9223C2.5 11.0788 2.58367 11.2237 2.71918 11.302L7.73934 14.2003C7.90054 14.2934 8.09946 14.2934 8.26066 14.2003L13.2808 11.302C13.4163 11.2237 13.5 11.079 13.5 10.9223V5.07774C13.5 4.92125 13.4161 4.77631 13.2806 4.69807ZM12.9653 5.31201L8.11901 13.7059C8.08626 13.7625 7.99977 13.7394 7.99977 13.6738V8.1776C7.99977 8.06777 7.94107 7.96619 7.84586 7.91104L3.08613 5.16306C3.02957 5.1303 3.05266 5.04379 3.11818 5.04379H12.8106C12.9483 5.04379 13.0341 5.19275 12.9653 5.31201Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 769 B After Width: | Height: | Size: 746 B |
|
|
@ -1,10 +1,8 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clip-path="url(#clip0_2716_663)">
|
||||
<path d="M8.47552 2.45453C11.5167 2.45457 13.9814 4.94501 13.9814 8.01623C13.9814 11.0875 11.5167 13.578 8.47552 13.5781C5.43427 13.5781 2.96948 11.0875 2.96948 8.01623C2.9695 4.94498 5.43429 2.45453 8.47552 2.45453ZM10.8795 4.70348C10.7605 4.16887 10.1328 3.85468 9.53627 3.96342C8.97622 4.06552 7.62871 4.45681 7.62057 4.45916C9.29414 4.44469 9.57429 4.4726 9.69939 4.64751C9.77324 4.7508 9.66576 4.89248 9.21944 4.96538C8.73515 5.04447 7.73014 5.13958 7.72343 5.14022C6.75441 5.19776 6.07177 5.20168 5.86705 5.63512C5.73334 5.91827 6.00968 6.16857 6.13082 6.32527C6.64271 6.89455 7.38215 7.20158 7.85809 7.42767C8.03716 7.51274 8.56257 7.67345 8.56257 7.67345C7.01855 7.58853 5.90474 8.06267 5.2514 8.60855C4.51246 9.29204 4.83937 10.1067 6.35327 10.6084C7.24742 10.9047 7.69094 11.0439 9.02473 10.9238C9.81031 10.8815 9.9342 10.9068 9.94203 10.9712C9.95275 11.062 9.06932 11.2874 8.82812 11.357C8.21455 11.534 6.60645 11.8913 6.59758 11.8932C6.60115 11.8935 7.06249 11.9257 7.65531 11.8735C7.89632 11.8522 8.81142 11.7624 9.49557 11.6123C9.49557 11.6123 10.3297 11.4338 10.7759 11.2693C11.2429 11.0973 11.497 10.9512 11.6113 10.7443C11.6063 10.7019 11.6465 10.5516 11.4313 10.4613C10.8807 10.2304 10.2423 10.2721 8.9789 10.2453C7.57789 10.1972 7.11184 9.9626 6.86356 9.77373C6.62548 9.58212 6.74518 9.05204 7.76528 8.5851C8.27917 8.33646 10.2935 7.87759 10.2935 7.87759C9.61511 7.54227 8.35014 6.95284 8.09005 6.82552C7.86199 6.71388 7.49701 6.54572 7.4179 6.34233C7.32824 6.14709 7.6297 5.97888 7.79813 5.9307C8.34057 5.77424 9.10635 5.67701 9.8033 5.66609C10.1536 5.66061 10.2105 5.63806 10.2105 5.63806C10.6939 5.55787 11.0121 5.22722 10.8795 4.70348Z" fill="black"/>
|
||||
<mask id="mask0_4385_22072" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="2" y="2" width="12" height="12">
|
||||
<path d="M14 2H2V14H14V2Z" fill="white"/>
|
||||
</mask>
|
||||
<g mask="url(#mask0_4385_22072)">
|
||||
<path d="M7.97552 2.45453C11.0167 2.45457 13.4814 4.94501 13.4814 8.01623C13.4814 11.0875 11.0167 13.578 7.97552 13.5781C4.93427 13.5781 2.46948 11.0875 2.46948 8.01623C2.4695 4.94498 4.93429 2.45453 7.97552 2.45453ZM10.3795 4.70348C10.2605 4.16887 9.6328 3.85468 9.03627 3.96342C8.47622 4.06552 7.12871 4.45681 7.12057 4.45916C8.79414 4.44469 9.07429 4.4726 9.19939 4.64751C9.27324 4.7508 9.16576 4.89248 8.71944 4.96538C8.23515 5.04447 7.23014 5.13958 7.22343 5.14022C6.25441 5.19776 5.57177 5.20168 5.36705 5.63512C5.23334 5.91827 5.50968 6.16857 5.63082 6.32527C6.14271 6.89455 6.88215 7.20158 7.35809 7.42767C7.53716 7.51274 8.06257 7.67345 8.06257 7.67345C6.51855 7.58853 5.40474 8.06267 4.7514 8.60855C4.01246 9.29204 4.33937 10.1067 5.85327 10.6084C6.74742 10.9047 7.19094 11.0439 8.52473 10.9238C9.31031 10.8815 9.4342 10.9068 9.44203 10.9712C9.45275 11.062 8.56932 11.2874 8.32812 11.357C7.71455 11.534 6.10645 11.8913 6.09758 11.8932C6.10115 11.8935 6.56249 11.9257 7.15531 11.8735C7.39632 11.8522 8.31142 11.7624 8.99557 11.6123C8.99557 11.6123 9.8297 11.4338 10.2759 11.2693C10.7429 11.0973 10.997 10.9512 11.1113 10.7443C11.1063 10.7019 11.1465 10.5516 10.9313 10.4613C10.3807 10.2304 9.7423 10.2721 8.4789 10.2453C7.07789 10.1972 6.61184 9.9626 6.36356 9.77373C6.12548 9.58212 6.24518 9.05204 7.26528 8.5851C7.77917 8.33646 9.7935 7.87759 9.7935 7.87759C9.11511 7.54227 7.85014 6.95284 7.59005 6.82552C7.36199 6.71388 6.99701 6.54572 6.9179 6.34233C6.82824 6.14709 7.1297 5.97888 7.29813 5.9307C7.84057 5.77424 8.60635 5.67701 9.3033 5.66609C9.6536 5.66061 9.7105 5.63806 9.7105 5.63806C10.1939 5.55787 10.5121 5.22722 10.3795 4.70348Z" fill="#C6CAD0"/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clip0_2716_663">
|
||||
<rect width="12" height="12" fill="white" transform="translate(2.5 2)"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.9 KiB |
|
|
@ -1,3 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M3.6725 13.9985C3.36161 13.9982 3.06354 13.8746 2.84371 13.6548C2.62388 13.435 2.50026 13.1369 2.5 12.826V7.494C2.5 6.8325 2.7675 6.185 3.2365 5.7165L6.219 2.736C6.45192 2.50247 6.72867 2.31724 7.03335 2.19094C7.33804 2.06464 7.66467 1.99975 7.9945 2H13.3275C13.6384 2.00027 13.9365 2.12388 14.1563 2.34371C14.3761 2.56354 14.4997 2.86162 14.5 3.1725V8.5045C14.4983 9.17074 14.2336 9.80936 13.7635 10.2815L10.781 13.264C10.5477 13.4976 10.2706 13.6829 9.96561 13.8092C9.66059 13.9355 9.33364 14.0003 9.0035 14V13.9985H3.6725ZM8.157 10.5715H5.243V11.257H8.157V10.5715ZM4.4815 5.257H11.243V12.0165L13.3715 9.888C13.7373 9.52036 13.9433 9.02316 13.9445 8.5045V3.1725C13.9445 2.8335 13.6685 2.5555 13.3275 2.5555H7.9945C7.73753 2.55499 7.483 2.6053 7.24556 2.70356C7.00813 2.80181 6.79246 2.94606 6.611 3.128L4.4815 5.257ZM4.3855 5.353L3.628 6.11C3.26258 6.47809 3.0569 6.97533 3.0555 7.494V12.826C3.0555 13.165 3.3315 13.443 3.6725 13.443H9.0055C9.26249 13.4434 9.51701 13.3929 9.75445 13.2946C9.99188 13.1963 10.2075 13.052 10.389 12.87L11.145 12.1145H4.3855V5.353Z" fill="black"/>
|
||||
<path d="M3.1725 13.9985C2.86161 13.9982 2.56354 13.8746 2.34371 13.6548C2.12388 13.435 2.00026 13.1369 2 12.826V7.494C2 6.8325 2.2675 6.185 2.7365 5.7165L5.719 2.736C5.95192 2.50247 6.22867 2.31724 6.53335 2.19094C6.83804 2.06464 7.16467 1.99975 7.4945 2H12.8275C13.1384 2.00027 13.4365 2.12388 13.6563 2.34371C13.8761 2.56354 13.9997 2.86162 14 3.1725V8.5045C13.9983 9.17074 13.7336 9.80936 13.2635 10.2815L10.281 13.264C10.0477 13.4976 9.7706 13.6829 9.46561 13.8092C9.16059 13.9355 8.83364 14.0003 8.5035 14V13.9985H3.1725ZM7.657 10.5715H4.743V11.257H7.657V10.5715ZM3.9815 5.257H10.743V12.0165L12.8715 9.888C13.2373 9.52036 13.4433 9.02316 13.4445 8.5045V3.1725C13.4445 2.8335 13.1685 2.5555 12.8275 2.5555H7.4945C7.23753 2.55499 6.983 2.6053 6.74556 2.70356C6.50813 2.80181 6.29246 2.94606 6.111 3.128L3.9815 5.257ZM3.8855 5.353L3.128 6.11C2.76258 6.47809 2.5569 6.97533 2.5555 7.494V12.826C2.5555 13.165 2.8315 13.443 3.1725 13.443H8.5055C8.76249 13.4434 9.01701 13.3929 9.25445 13.2946C9.49188 13.1963 9.7075 13.052 9.889 12.87L10.645 12.1145H3.8855V5.353Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 1.2 KiB |
|
|
@ -1,5 +1,5 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.0945 8.01611C13.0945 7.87619 12.9911 7.79551 12.8642 7.8356L4.13456 10.6038C4.00742 10.6441 3.90427 10.7904 3.90427 10.9301V13.7593C3.90427 13.8992 4.00742 13.9801 4.13456 13.9398L12.8642 11.1719C12.9911 11.1315 13.0945 10.9852 13.0945 10.8453V8.01611Z" fill="black"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.90427 7.92597C3.90427 8.06588 4.00742 8.21218 4.13456 8.25252L12.8655 11.0209C12.9926 11.0613 13.0958 10.9803 13.0958 10.8407V8.01124C13.0958 7.87158 12.9926 7.72529 12.8655 7.68494L4.13456 4.91652C4.00742 4.87618 3.90427 4.95686 3.90427 5.09677V7.92597Z" fill="black"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.0945 2.20248C13.0945 2.06256 12.9911 1.98163 12.8642 2.02197L4.13456 4.78988C4.00742 4.83022 3.90427 4.97652 3.90427 5.11644V7.94563C3.90427 8.08554 4.00742 8.16622 4.13456 8.12614L12.8642 5.35797C12.9911 5.31763 13.0945 5.17133 13.0945 5.03167V2.20248Z" fill="black"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.5945 8.03524C12.5945 7.89532 12.4911 7.81464 12.3642 7.85473L3.63453 10.6229C3.50739 10.6632 3.40424 10.8095 3.40424 10.9492V13.7784C3.40424 13.9183 3.50739 13.9992 3.63453 13.9589L12.3642 11.191C12.4911 11.1506 12.5945 11.0043 12.5945 10.8644V8.03524Z" fill="#C6CAD0"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M3.40424 7.9451C3.40424 8.08501 3.50739 8.23131 3.63453 8.27165L12.3655 11.04C12.4926 11.0804 12.5958 10.9994 12.5958 10.8598V8.03037C12.5958 7.89071 12.4926 7.74442 12.3655 7.70407L3.63453 4.93565C3.50739 4.89531 3.40424 4.97599 3.40424 5.1159V7.9451Z" fill="#C6CAD0"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M12.5945 2.22161C12.5945 2.08169 12.4911 2.00076 12.3642 2.0411L3.63453 4.80901C3.50739 4.84935 3.40424 4.99565 3.40424 5.13557V7.96476C3.40424 8.10467 3.50739 8.18535 3.63453 8.14527L12.3642 5.3771C12.4911 5.33676 12.5945 5.19046 12.5945 5.0508V2.22161Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 1 KiB After Width: | Height: | Size: 1 KiB |
|
|
@ -1,3 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M11.0094 13.9181C11.1984 13.9917 11.4139 13.987 11.6047 13.8952L14.0753 12.7064C14.3349 12.5814 14.5 12.3187 14.5 12.0305V3.9696C14.5 3.68136 14.3349 3.41862 14.0753 3.2937L11.6047 2.10485C11.3543 1.98438 11.0614 2.01389 10.8416 2.17363C10.8102 2.19645 10.7803 2.22193 10.7523 2.25001L6.02261 6.56498L3.96246 5.00115C3.77068 4.85558 3.50244 4.86751 3.32432 5.02953L2.66356 5.63059C2.44569 5.82877 2.44544 6.17152 2.66302 6.37004L4.44965 8.00001L2.66302 9.62998C2.44544 9.82849 2.44569 10.1713 2.66356 10.3694L3.32432 10.9705C3.50244 11.1325 3.77068 11.1444 3.96246 10.9989L6.02261 9.43504L10.7523 13.75C10.8271 13.8249 10.915 13.8812 11.0094 13.9181ZM11.5018 5.27587L7.91309 8.00001L11.5018 10.7241V5.27587Z" fill="black"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M10.5094 13.9181C10.6984 13.9917 10.9139 13.987 11.1047 13.8952L13.5753 12.7064C13.8349 12.5814 14 12.3187 14 12.0305V3.9696C14 3.68136 13.8349 3.41862 13.5753 3.2937L11.1047 2.10485C10.8543 1.98438 10.5614 2.01389 10.3416 2.17363C10.3102 2.19645 10.2803 2.22193 10.2523 2.25001L5.52261 6.56498L3.46246 5.00115C3.27068 4.85558 3.00244 4.86751 2.82432 5.02953L2.16356 5.63059C1.94569 5.82877 1.94544 6.17152 2.16302 6.37004L3.94965 8.00001L2.16302 9.62998C1.94544 9.82849 1.94569 10.1713 2.16356 10.3694L2.82432 10.9705C3.00244 11.1325 3.27068 11.1444 3.46246 10.9989L5.52261 9.43504L10.2523 13.75C10.3271 13.8249 10.415 13.8812 10.5094 13.9181ZM11.0018 5.27587L7.41309 8.00001L11.0018 10.7241V5.27587Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 876 B After Width: | Height: | Size: 872 B |
8
assets/icons/file_icons/ballerina.svg
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M4.57391 3.54203V5.2877L5.96882 5.81793C6.73561 6.10752 7.38411 6.35224 7.41674 6.36039C7.46161 6.37263 7.46977 5.96476 7.46977 4.08858V1.80044H6.02184H4.57391V3.54203Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
|
||||
<path d="M8.53021 4.08451C8.53021 5.34074 8.54245 6.36856 8.56284 6.36856C8.57916 6.36856 9.22359 6.12384 9.99853 5.8261L11.4057 5.28771L11.4179 3.54205L11.4261 1.80046H9.97814H8.53021V4.08451Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
|
||||
<path d="M4.57391 7.1435C4.57391 7.54728 4.58615 7.87766 4.60654 7.87766C4.66772 7.87766 6.49089 7.16797 6.49089 7.1435C6.49089 7.11902 4.66772 6.40934 4.60654 6.40934C4.58615 6.40934 4.57391 6.73971 4.57391 7.1435Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
|
||||
<path d="M10.4186 6.76826C9.91696 6.95996 9.50909 7.12718 9.50909 7.1435C9.50909 7.16797 11.3323 7.87766 11.3975 7.87766C11.4138 7.87766 11.4261 7.54728 11.4261 7.1435C11.4261 6.58064 11.4138 6.40934 11.3771 6.41341C11.3486 6.41749 10.9162 6.57656 10.4186 6.76826Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
|
||||
<path d="M5.9729 8.46498L4.57391 8.99929V11.5974V14.1996H5.32439C6.00553 14.1996 6.07894 14.1914 6.09933 14.1262C6.11157 14.0895 6.42563 13.0616 6.79679 11.8421L7.46977 9.63148V8.77496C7.46977 8.11422 7.45753 7.91844 7.42082 7.92252C7.39227 7.9266 6.73969 8.16724 5.9729 8.46498Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
|
||||
<path d="M8.53021 8.77904V9.63964L9.1828 11.785C9.5458 12.9678 9.85986 13.9957 9.88025 14.065L9.92512 14.1996H10.6756H11.4261L11.4179 11.5974L11.4057 8.99929L9.99853 8.45682C9.22359 8.16316 8.57916 7.91844 8.56284 7.91844C8.54245 7.91844 8.53021 8.30591 8.53021 8.77904Z" fill="#C6CAD0" stroke="#C6CAD0" stroke-width="0.483833"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.8 KiB |
3
assets/icons/forgejo.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M10.4889 1.74811C11.3234 1.74811 12 2.42467 12 3.25924C12 4.09382 11.3234 4.77032 10.4889 4.77032C9.92344 4.77032 9.43053 4.45981 9.17144 3.99993H8.4741C7.25904 3.99993 6.27176 4.97512 6.25212 6.18549L6.25176 7.28869C6.87559 6.81941 7.63228 6.56028 8.41283 6.54862L8.4741 6.5481L9.17144 6.5482C9.43053 6.08832 9.92344 5.77776 10.4889 5.77776C11.3234 5.77776 12 6.45432 12 7.28889C12 8.12347 11.3234 8.79998 10.4889 8.79998C9.92344 8.79998 9.43053 8.48947 9.17144 8.02959H8.4741C7.25904 8.02959 6.27176 9.00478 6.25212 10.2151L6.25176 11.4233C6.71164 11.6824 7.0222 12.1753 7.0222 12.7407C7.0222 13.5754 6.34564 14.2519 5.51107 14.2519C4.67654 14.2519 3.99998 13.5753 3.99998 12.7407C3.99998 12.1753 4.3105 11.6824 4.77043 11.4233L4.77032 6.22222C4.77032 4.19713 6.39555 2.55168 8.41283 2.51902L8.4741 2.5185H9.17144C9.43053 2.05872 9.92349 1.74811 10.4889 1.74811ZM5.51107 12.1185C5.16742 12.1185 4.88885 12.3971 4.88885 12.7407C4.88885 13.0844 5.16742 13.363 5.51107 13.363C5.85471 13.363 6.13334 13.0844 6.13334 12.7407C6.13334 12.3971 5.85471 12.1185 5.51107 12.1185ZM10.4889 6.66668C10.1453 6.66668 9.86665 6.94525 9.86665 7.28889C9.86665 7.63254 10.1453 7.91111 10.4889 7.91111C10.8326 7.91111 11.1111 7.63254 11.1111 7.28889C11.1111 6.94525 10.8326 6.66668 10.4889 6.66668ZM10.4889 2.63702C10.1453 2.63702 9.86665 2.9156 9.86665 3.25924C9.86665 3.60289 10.1453 3.88146 10.4889 3.88146C10.8326 3.88146 11.1111 3.60289 11.1111 3.25924C11.1111 2.9156 10.8326 2.63702 10.4889 2.63702Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
3
assets/icons/gitea.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M3.45524 3.60059C3.31116 3.60059 3.14899 3.61226 2.96524 3.65192C2.77099 3.69276 2.21858 3.81701 1.76707 4.25101C0.764907 5.14467 1.02041 6.56509 1.05191 6.77917C1.08982 7.03934 1.20532 7.76326 1.75774 8.39384C2.77799 9.64276 4.97366 9.61418 4.97366 9.61418C4.97366 9.61418 5.24316 10.2576 5.65499 10.8503C6.21208 11.587 6.78433 12.1616 7.34083 12.231C8.74433 12.231 11.5478 12.2287 11.5478 12.2287C11.5478 12.2287 11.815 12.231 12.1778 11.9988C12.4899 11.8098 12.7687 11.4779 12.7687 11.4779C12.7687 11.4779 13.0557 11.1705 13.4571 10.4688C13.5796 10.2529 13.6817 10.0435 13.7709 9.84576C13.7709 9.84576 15 7.23768 15 4.69901C14.9755 3.93017 14.7859 3.79484 14.7416 3.74992C14.6506 3.65892 14.5281 3.66067 14.5281 3.66067C14.5281 3.66067 11.9177 3.80767 10.5661 3.83917C10.2697 3.84559 9.97575 3.85259 9.68408 3.85492V6.46476L9.31425 6.28917C9.31425 5.47834 9.31191 3.85667 9.31191 3.85667C8.66616 3.86601 7.32566 3.80767 7.32566 3.80767C7.32566 3.80767 4.17624 3.65017 3.83324 3.61867C3.72416 3.61226 3.59933 3.60059 3.45524 3.60059ZM3.66174 4.66926H3.72649C3.72649 4.66926 3.88458 5.99284 4.07649 6.76751C4.23691 7.41792 4.62833 8.49884 4.62833 8.49884C4.62833 8.49884 4.04733 8.42943 3.67108 8.29584C3.09358 8.10684 2.84916 7.87934 2.84916 7.87934C2.84916 7.87934 2.42333 7.58126 2.20983 6.99268C1.84232 6.00801 2.17891 5.40717 2.17891 5.40717C2.17891 5.40717 2.36558 4.90609 3.03641 4.73926C3.26683 4.67742 3.53983 4.66926 3.66174 4.66926ZM8.52091 6.15909C8.67258 6.16084 8.81783 6.23317 8.81783 6.23317L9.32416 6.47934L9.01558 7.10642C8.94244 7.10526 8.87038 7.12417 8.80724 7.16109C8.74409 7.19801 8.69227 7.25153 8.65741 7.31584C8.62013 7.3853 8.60423 7.46422 8.61171 7.5427C8.61918 7.62117 8.64969 7.69567 8.69941 7.75684L8.15166 8.87918C8.0625 8.88053 7.97631 8.91146 7.90663 8.9671C7.83695 9.02274 7.78772 9.09994 7.76666 9.18659C7.74656 9.27272 7.75551 9.36308 7.79213 9.44358C7.82874 9.52409 7.89096 9.59022 7.96908 9.63168C8.05388 9.67515 8.15141 9.68693 8.24412 9.6649C8.33684 9.64287 8.41864 9.58848 8.47483 9.51151C8.52969 9.43471 8.55573 9.34103 8.54837 9.24693C8.541 9.15284 8.50072 9.06435 8.43458 8.99701L8.96891 7.90384C9.01532 7.90827 9.06215 7.90432 9.10716 7.89218C9.16538 7.87825 9.21952 7.85088 9.26525 7.81226C9.46902 7.89896 9.66699 7.99873 9.85791 8.11093C9.92725 8.14983 9.98487 8.20664 10.0247 8.27543C10.0673 8.39793 9.98216 8.60734 9.98216 8.60734C9.93141 8.77651 9.57266 9.51151 9.57266 9.51151C9.48573 9.50923 9.40039 9.53508 9.32933 9.58521C9.25828 9.63535 9.20532 9.70709 9.17833 9.78976C9.15763 9.85611 9.15471 9.92673 9.16985 9.99456C9.18498 10.0624 9.21765 10.1251 9.26459 10.1763C9.31153 10.2276 9.3711 10.2656 9.43734 10.2867C9.50359 10.3077 9.57419 10.311 9.6421 10.2962C9.71001 10.2814 9.77285 10.2491 9.82435 10.2024C9.87585 10.1557 9.9142 10.0963 9.93557 10.0302C9.95694 9.96406 9.96058 9.89347 9.94614 9.82548C9.93169 9.7575 9.89966 9.69449 9.85325 9.64276C9.89583 9.56051 9.9355 9.47826 9.97808 9.39134C10.0889 9.15976 10.2785 8.71468 10.2785 8.71468C10.2989 8.67618 10.4057 8.48484 10.3386 8.23984C10.2832 7.98609 10.0586 7.86768 10.0586 7.86768C9.78616 7.69209 9.40758 7.52934 9.40758 7.52934C9.40758 7.52934 9.40758 7.43834 9.38308 7.37184C9.36435 7.31951 9.33495 7.27164 9.29675 7.23126L9.59775 6.61176L11.2836 7.42901C11.2836 7.42901 11.5636 7.55618 11.6237 7.79009C11.6662 7.95459 11.6126 8.10159 11.5834 8.17334C11.4434 8.51576 10.3584 10.6916 10.3584 10.6916C10.3584 10.6916 10.2231 11.0148 9.92208 11.0346C9.8447 11.0402 9.76694 11.0313 9.69283 11.0083L9.575 10.9617L7.06083 9.73668C7.06083 9.73668 6.81758 9.60951 6.77499 9.38901C6.72658 9.20818 6.83566 8.98593 6.83566 8.98593L8.04491 6.49392C8.04491 6.49392 8.15166 6.27809 8.31675 6.20401C8.38086 6.17478 8.45045 6.15947 8.52091 6.15909Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
3
assets/icons/gitlab.svg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M14.0228 6.75008L14.0053 6.70533L12.3092 2.27915C12.2747 2.19237 12.2136 2.11876 12.1347 2.06887C12.0557 2.01987 11.9636 1.99627 11.8708 2.00128C11.7779 2.00628 11.6889 2.03964 11.6156 2.09686C11.5432 2.15571 11.4906 2.23546 11.4651 2.32525L10.32 5.82877H5.68303L4.53784 2.32525C4.513 2.23496 4.46031 2.1548 4.38727 2.09618C4.31401 2.03898 4.22496 2.00564 4.13214 2.00065C4.03932 1.99567 3.94721 2.01928 3.86824 2.0683C3.78948 2.11837 3.72842 2.1919 3.69368 2.27852L1.99452 6.70273L1.97764 6.74748C1.73349 7.38539 1.70335 8.08539 1.89177 8.74192C2.08018 9.39845 2.47694 9.97594 3.02221 10.3873L3.02808 10.3918L3.04365 10.4029L5.62716 12.3376L6.90542 13.305L7.68395 13.8928C7.77502 13.9619 7.88623 13.9994 8.00058 13.9994C8.11493 13.9994 8.22613 13.9619 8.31721 13.8928L9.09574 13.305L10.3739 12.3376L12.973 10.3912L12.9795 10.386C13.5236 9.97456 13.9194 9.39768 14.1075 8.74203C14.2957 8.08638 14.2659 7.38738 14.0228 6.75008Z" fill="#C6CAD0"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1 KiB |
5
assets/icons/share.svg
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M7.99689 2.05652L7.99929 9.98113" stroke="#C6CAD0" stroke-width="1.17299" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M11.1699 5.22637L8.00001 2.05652L4.83015 5.22637" stroke="#C6CAD0" stroke-width="1.17299" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M3.24522 8L3.24522 12.2653C3.24522 12.7104 3.37046 13.1372 3.59338 13.4519C3.81631 13.7667 4.11866 13.9435 4.43392 13.9435H11.5661C11.8813 13.9435 12.1837 13.7667 12.4066 13.4519C12.6295 13.1372 12.7548 12.7104 12.7548 12.2653V8" stroke="#C6CAD0" stroke-width="1.17299" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 711 B |
6
assets/icons/text_unwrap.svg
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M11.748 5.74794L14 7.99998L11.748 10.252" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M14 7.99997L3 7.99997" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 3L8 6" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M8 10L8 13" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 566 B |
5
assets/icons/text_wrap.svg
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M5.19924 8.90081L2.9472 6.64876L5.19924 4.39673" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M2.9472 6.64877H7.67649C8.00178 6.64877 8.32391 6.71285 8.6245 6.83734C8.92501 6.96184 9.19813 7.14431 9.42817 7.37434C9.6582 7.60437 9.84067 7.87746 9.96512 8.17802C10.0897 8.47856 10.1537 8.8007 10.1537 9.12601C10.1537 9.45131 10.0897 9.77345 9.96512 10.074C9.84067 10.3745 9.6582 10.6477 9.42817 10.8777C9.19813 11.1077 8.92501 11.2902 8.6245 11.4147C8.32391 11.5392 8.00178 11.6033 7.67649 11.6033H6.10005" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M13.0528 3.33331V12.6666" stroke="#C6CAD0" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 871 B |
|
|
@ -380,15 +380,7 @@
|
|||
"shift-backspace": "agent::ArchiveSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "RulesLibrary",
|
||||
"bindings": {
|
||||
"new": "rules_library::NewRule",
|
||||
"ctrl-n": "rules_library::NewRule",
|
||||
"ctrl-shift-s": "rules_library::ToggleDefaultRule",
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
"context": "BufferSearchBar",
|
||||
"bindings": {
|
||||
|
|
@ -729,6 +721,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"space": "menu::Confirm",
|
||||
"shift-r": "agent::RenameSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -1558,4 +1551,22 @@
|
|||
"shift-tab": "git_graph::FocusPreviousTabStop",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "SkillCreator",
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "SkillCreator > Editor",
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
},
|
||||
]
|
||||
|
|
|
|||
|
|
@ -427,15 +427,6 @@
|
|||
"backspace": "agent::ArchiveSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "RulesLibrary",
|
||||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"cmd-n": "rules_library::NewRule",
|
||||
"cmd-shift-s": "rules_library::ToggleDefaultRule",
|
||||
"cmd-w": "workspace::CloseWindow",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "BufferSearchBar",
|
||||
"use_key_equivalents": true,
|
||||
|
|
@ -785,6 +776,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"space": "menu::Confirm",
|
||||
"shift-r": "agent::RenameSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -1651,4 +1643,24 @@
|
|||
"shift-tab": "git_graph::FocusPreviousTabStop",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "SkillCreator",
|
||||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"cmd-w": "workspace::CloseWindow",
|
||||
"cmd-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "SkillCreator > Editor",
|
||||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"cmd-w": "workspace::CloseWindow",
|
||||
"cmd-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
},
|
||||
]
|
||||
|
|
|
|||
|
|
@ -383,15 +383,6 @@
|
|||
"shift-backspace": "agent::ArchiveSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "RulesLibrary",
|
||||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"ctrl-n": "rules_library::NewRule",
|
||||
"ctrl-shift-s": "rules_library::ToggleDefaultRule",
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "BufferSearchBar",
|
||||
"use_key_equivalents": true,
|
||||
|
|
@ -732,6 +723,7 @@
|
|||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"space": "menu::Confirm",
|
||||
"shift-r": "agent::RenameSelectedThread",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -1577,4 +1569,24 @@
|
|||
"shift-tab": "git_graph::FocusPreviousTabStop",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "SkillCreator",
|
||||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "SkillCreator > Editor",
|
||||
"use_key_equivalents": true,
|
||||
"bindings": {
|
||||
"ctrl-w": "workspace::CloseWindow",
|
||||
"ctrl-enter": "skill_creator::SaveSkill",
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
},
|
||||
]
|
||||
|
|
|
|||
|
|
@ -338,7 +338,7 @@
|
|||
"ctrl-x": "vim::Decrement",
|
||||
"shift-j": "vim::JoinLines",
|
||||
"i": "vim::InsertBefore",
|
||||
"a": "vim::InsertAfter",
|
||||
"a": "vim::HelixAppend",
|
||||
"o": "vim::InsertLineBelow",
|
||||
"shift-o": "vim::InsertLineAbove",
|
||||
"p": "vim::Paste",
|
||||
|
|
@ -494,6 +494,10 @@
|
|||
"n": "vim::HelixSelectNext",
|
||||
"shift-n": "vim::HelixSelectPrevious",
|
||||
|
||||
// Macros — Helix swaps Vim's q/Q: Q records, q replays
|
||||
"q": "vim::ReplayLastRecording",
|
||||
"shift-q": "vim::ToggleRecord",
|
||||
|
||||
// Goto mode
|
||||
"g e": "vim::EndOfDocument",
|
||||
"g h": "vim::StartOfLine",
|
||||
|
|
@ -503,6 +507,8 @@
|
|||
"g c": "vim::WindowMiddle",
|
||||
"g b": "vim::WindowBottom",
|
||||
"g r": "editor::FindAllReferences",
|
||||
"g i": "editor::GoToImplementation",
|
||||
"g a": "pane::AlternateFile",
|
||||
"g n": "pane::ActivateNextItem",
|
||||
"shift-l": "pane::ActivateNextItem", // not a helix default
|
||||
"g p": "pane::ActivatePreviousItem",
|
||||
|
|
@ -943,7 +949,7 @@
|
|||
"space w j": "workspace::ActivatePaneDown",
|
||||
"space w k": "workspace::ActivatePaneUp",
|
||||
"space w l": "workspace::ActivatePaneRight",
|
||||
"space w q": "pane::CloseActiveItem",
|
||||
"space w q": "pane::CloseActiveItem",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -1056,8 +1062,8 @@
|
|||
"ctrl-d": "git_graph::ScrollDown",
|
||||
"ctrl-u": "git_graph::ScrollUp",
|
||||
"shift-g": "menu::SelectLast",
|
||||
"g g": "menu::SelectFirst"
|
||||
}
|
||||
"g g": "menu::SelectFirst",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "GitPanel && ChangesList && !GitBranchSelector",
|
||||
|
|
@ -1205,4 +1211,18 @@
|
|||
"enter": "editor::Newline",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "SkillCreator",
|
||||
"bindings": {
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
},
|
||||
{
|
||||
"context": "SkillCreator > Editor",
|
||||
"bindings": {
|
||||
"tab": "skill_creator::FocusNextField",
|
||||
"shift-tab": "skill_creator::FocusPreviousField",
|
||||
},
|
||||
},
|
||||
]
|
||||
|
|
|
|||
|
|
@ -71,6 +71,8 @@
|
|||
"agent_ui_font_size": null,
|
||||
// The default font size for user messages in the agent panel.
|
||||
"agent_buffer_font_size": 12,
|
||||
// The default font size for the commit editor in the git panel and commit modal.
|
||||
"git_commit_buffer_font_size": 12,
|
||||
// How much to fade out unused code.
|
||||
"unnecessary_code_fade": 0.3,
|
||||
// Active pane styling settings.
|
||||
|
|
@ -1133,6 +1135,7 @@
|
|||
"spawn_agent": true,
|
||||
"terminal": true,
|
||||
"update_plan": true,
|
||||
"update_title": true,
|
||||
"search_web": true,
|
||||
},
|
||||
},
|
||||
|
|
@ -1153,6 +1156,7 @@
|
|||
"skill": true,
|
||||
"spawn_agent": true,
|
||||
"update_plan": true,
|
||||
"update_title": true,
|
||||
"search_web": true,
|
||||
},
|
||||
},
|
||||
|
|
@ -1496,6 +1500,10 @@
|
|||
// 4. Draw a background behind the color text..
|
||||
// "lsp_document_colors": "background",
|
||||
"lsp_document_colors": "inlay",
|
||||
// Whether to query and display LSP `textDocument/documentLink` links in the editor.
|
||||
//
|
||||
// Default: true
|
||||
"lsp_document_links": true,
|
||||
// Diagnostics configuration.
|
||||
"diagnostics": {
|
||||
// Whether to show the project diagnostics button in the status bar.
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ path = "src/acp_thread.rs"
|
|||
doctest = false
|
||||
|
||||
[features]
|
||||
test-support = ["gpui/test-support", "project/test-support", "dep:parking_lot", "dep:image"]
|
||||
test-support = ["gpui/test-support", "project/test-support", "dep:parking_lot"]
|
||||
|
||||
[dependencies]
|
||||
action_log.workspace = true
|
||||
|
|
@ -35,10 +35,10 @@ language_model.workspace = true
|
|||
log.workspace = true
|
||||
markdown.workspace = true
|
||||
parking_lot = { workspace = true, optional = true }
|
||||
image = { workspace = true, optional = true }
|
||||
image.workspace = true
|
||||
portable-pty.workspace = true
|
||||
project.workspace = true
|
||||
prompt_store.workspace = true
|
||||
sandbox.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
settings.workspace = true
|
||||
|
|
|
|||
|
|
@ -16,7 +16,9 @@ use gpui::{
|
|||
};
|
||||
use itertools::Itertools;
|
||||
use language::language_settings::FormatOnSave;
|
||||
use language::{Anchor, Buffer, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff};
|
||||
use language::{
|
||||
Anchor, Buffer, BufferEditSource, BufferSnapshot, LanguageRegistry, Point, ToPoint, text_diff,
|
||||
};
|
||||
use markdown::{Markdown, MarkdownOptions};
|
||||
pub use mention::*;
|
||||
use project::lsp_store::{FormatTrigger, LspFormatTarget};
|
||||
|
|
@ -648,9 +650,16 @@ impl Display for ToolCallStatus {
|
|||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub enum ContentBlock {
|
||||
Empty,
|
||||
Markdown { markdown: Entity<Markdown> },
|
||||
ResourceLink { resource_link: acp::ResourceLink },
|
||||
Image { image: Arc<gpui::Image> },
|
||||
Markdown {
|
||||
markdown: Entity<Markdown>,
|
||||
},
|
||||
ResourceLink {
|
||||
resource_link: acp::ResourceLink,
|
||||
},
|
||||
Image {
|
||||
image: Arc<gpui::Image>,
|
||||
dimensions: Option<gpui::Size<u32>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl ContentBlock {
|
||||
|
|
@ -692,8 +701,8 @@ impl ContentBlock {
|
|||
};
|
||||
}
|
||||
(ContentBlock::Empty, acp::ContentBlock::Image(image_content)) => {
|
||||
if let Some(image) = Self::decode_image(image_content) {
|
||||
*self = ContentBlock::Image { image };
|
||||
if let Some((image, dimensions)) = Self::decode_image(image_content) {
|
||||
*self = ContentBlock::Image { image, dimensions };
|
||||
} else {
|
||||
let new_content = Self::image_md(image_content);
|
||||
*self = Self::create_markdown_block(new_content, language_registry, cx);
|
||||
|
|
@ -721,14 +730,36 @@ impl ContentBlock {
|
|||
}
|
||||
}
|
||||
|
||||
fn decode_image(image_content: &acp::ImageContent) -> Option<Arc<gpui::Image>> {
|
||||
fn decode_image(
|
||||
image_content: &acp::ImageContent,
|
||||
) -> Option<(Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
|
||||
use base64::Engine as _;
|
||||
|
||||
let bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(image_content.data.as_bytes())
|
||||
.ok()?;
|
||||
let format = gpui::ImageFormat::from_mime_type(&image_content.mime_type)?;
|
||||
Some(Arc::new(gpui::Image::from_bytes(format, bytes)))
|
||||
let dimensions = Self::image_dimensions(&bytes, format);
|
||||
Some((Arc::new(gpui::Image::from_bytes(format, bytes)), dimensions))
|
||||
}
|
||||
|
||||
fn image_dimensions(bytes: &[u8], format: gpui::ImageFormat) -> Option<gpui::Size<u32>> {
|
||||
let format = match format {
|
||||
gpui::ImageFormat::Png => image::ImageFormat::Png,
|
||||
gpui::ImageFormat::Jpeg => image::ImageFormat::Jpeg,
|
||||
gpui::ImageFormat::Webp => image::ImageFormat::WebP,
|
||||
gpui::ImageFormat::Gif => image::ImageFormat::Gif,
|
||||
gpui::ImageFormat::Svg => return None,
|
||||
gpui::ImageFormat::Bmp => image::ImageFormat::Bmp,
|
||||
gpui::ImageFormat::Tiff => image::ImageFormat::Tiff,
|
||||
gpui::ImageFormat::Ico => image::ImageFormat::Ico,
|
||||
gpui::ImageFormat::Pnm => image::ImageFormat::Pnm,
|
||||
};
|
||||
|
||||
image::ImageReader::with_format(std::io::Cursor::new(bytes), format)
|
||||
.into_dimensions()
|
||||
.ok()
|
||||
.map(|(width, height)| gpui::Size { width, height })
|
||||
}
|
||||
|
||||
fn create_markdown_block(
|
||||
|
|
@ -744,6 +775,7 @@ impl ContentBlock {
|
|||
None,
|
||||
MarkdownOptions {
|
||||
render_mermaid_diagrams: true,
|
||||
render_metadata_blocks: true,
|
||||
..Default::default()
|
||||
},
|
||||
cx,
|
||||
|
|
@ -808,9 +840,9 @@ impl ContentBlock {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn image(&self) -> Option<&Arc<gpui::Image>> {
|
||||
pub fn image(&self) -> Option<(&Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
|
||||
match self {
|
||||
ContentBlock::Image { image } => Some(image),
|
||||
ContentBlock::Image { image, dimensions } => Some((image, *dimensions)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
|
@ -895,7 +927,7 @@ impl ToolCallContent {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn image(&self) -> Option<&Arc<gpui::Image>> {
|
||||
pub fn image(&self) -> Option<(&Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
|
||||
match self {
|
||||
Self::ContentBlock(content) => content.image(),
|
||||
_ => None,
|
||||
|
|
@ -2883,7 +2915,9 @@ impl AcpThread {
|
|||
});
|
||||
|
||||
let format_on_save = buffer.update(cx, |buffer, cx| {
|
||||
buffer.start_transaction();
|
||||
buffer.edit(edits, None, cx);
|
||||
buffer.end_transaction_with_source(BufferEditSource::Agent, cx);
|
||||
|
||||
let settings =
|
||||
language::language_settings::LanguageSettings::for_buffer(buffer, cx);
|
||||
|
|
@ -2926,6 +2960,7 @@ impl AcpThread {
|
|||
extra_env: Vec<acp::EnvVariable>,
|
||||
cwd: Option<PathBuf>,
|
||||
output_byte_limit: Option<u64>,
|
||||
sandbox_wrap: Option<SandboxWrap>,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<Entity<Terminal>>> {
|
||||
let env = match &cwd {
|
||||
|
|
@ -2966,6 +3001,8 @@ impl AcpThread {
|
|||
ShellBuilder::new(&Shell::Program(shell), is_windows)
|
||||
.redirect_stdin_to_dev_null()
|
||||
.build(Some(command.clone()), &args);
|
||||
let (task_command, task_args, sandbox_config) =
|
||||
apply_sandbox_wrap(task_command, task_args, sandbox_wrap)?;
|
||||
let terminal = project
|
||||
.update(cx, |project, cx| {
|
||||
project.create_terminal_task(
|
||||
|
|
@ -2989,6 +3026,7 @@ impl AcpThread {
|
|||
output_byte_limit.map(|l| l as usize),
|
||||
terminal,
|
||||
language_registry,
|
||||
sandbox_config,
|
||||
cx,
|
||||
)
|
||||
}))
|
||||
|
|
@ -3068,6 +3106,9 @@ impl AcpThread {
|
|||
output_byte_limit.map(|l| l as usize),
|
||||
terminal,
|
||||
language_registry,
|
||||
// External terminal providers manage their own sandboxing
|
||||
// (if any). We don't wrap their commands.
|
||||
None,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
|
|
|||
|
|
@ -7,14 +7,14 @@ use gpui::{Entity, SharedString, Task};
|
|||
use language_model::LanguageModelProviderId;
|
||||
use project::{AgentId, Project};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{any::Any, error::Error, fmt, path::PathBuf, rc::Rc, sync::Arc};
|
||||
use std::{any::Any, error::Error, fmt, path::PathBuf, rc::Rc};
|
||||
use task::{HideStrategy, SpawnInTerminal, TaskId};
|
||||
use ui::{App, IconName};
|
||||
use util::path_list::PathList;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
|
||||
pub struct UserMessageId(Arc<str>);
|
||||
pub struct UserMessageId(SharedString);
|
||||
|
||||
impl UserMessageId {
|
||||
pub fn new() -> Self {
|
||||
|
|
@ -115,6 +115,11 @@ pub trait AgentConnection {
|
|||
self.supports_load_session() || self.supports_resume_session()
|
||||
}
|
||||
|
||||
/// Whether this agent supports additional session directories.
|
||||
fn supports_session_additional_directories(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn auth_methods(&self) -> &[acp::AuthMethod];
|
||||
|
||||
fn terminal_auth_task(
|
||||
|
|
@ -127,6 +132,14 @@ pub trait AgentConnection {
|
|||
|
||||
fn authenticate(&self, method: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>>;
|
||||
|
||||
fn supports_logout(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn logout(&self, _cx: &mut App) -> Task<Result<()>> {
|
||||
Task::ready(Err(anyhow::Error::msg("Logout is not supported")))
|
||||
}
|
||||
|
||||
fn prompt(
|
||||
&self,
|
||||
user_message_id: UserMessageId,
|
||||
|
|
@ -310,7 +323,7 @@ pub trait AgentSessionList {
|
|||
cx: &mut App,
|
||||
) -> Task<Result<AgentSessionListResponse>>;
|
||||
|
||||
fn supports_delete(&self) -> bool {
|
||||
fn supports_delete(&self, _cx: &App) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
|
|
@ -694,6 +707,7 @@ mod test_support {
|
|||
permission_requests: HashMap<acp::ToolCallId, PermissionOptions>,
|
||||
next_prompt_updates: Arc<Mutex<Vec<acp::SessionUpdate>>>,
|
||||
supports_load_session: bool,
|
||||
supports_session_additional_directories: bool,
|
||||
agent_id: AgentId,
|
||||
telemetry_id: SharedString,
|
||||
}
|
||||
|
|
@ -716,6 +730,7 @@ mod test_support {
|
|||
permission_requests: HashMap::default(),
|
||||
sessions: Arc::default(),
|
||||
supports_load_session: false,
|
||||
supports_session_additional_directories: false,
|
||||
agent_id: AgentId::new("stub"),
|
||||
telemetry_id: "stub".into(),
|
||||
}
|
||||
|
|
@ -738,6 +753,14 @@ mod test_support {
|
|||
self
|
||||
}
|
||||
|
||||
pub fn with_supports_session_additional_directories(
|
||||
mut self,
|
||||
supports_session_additional_directories: bool,
|
||||
) -> Self {
|
||||
self.supports_session_additional_directories = supports_session_additional_directories;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_agent_id(mut self, agent_id: AgentId) -> Self {
|
||||
self.agent_id = agent_id;
|
||||
self
|
||||
|
|
@ -855,6 +878,10 @@ mod test_support {
|
|||
self.supports_load_session
|
||||
}
|
||||
|
||||
fn supports_session_additional_directories(&self) -> bool {
|
||||
self.supports_session_additional_directories
|
||||
}
|
||||
|
||||
fn load_session(
|
||||
self: Rc<Self>,
|
||||
session_id: acp::SessionId,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
use agent_client_protocol::schema as acp;
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use file_icons::FileIcons;
|
||||
use prompt_store::{PromptId, UserPromptId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
|
|
@ -37,10 +36,6 @@ pub enum MentionUri {
|
|||
id: acp::SessionId,
|
||||
name: String,
|
||||
},
|
||||
Rule {
|
||||
id: PromptId,
|
||||
name: String,
|
||||
},
|
||||
Diagnostics {
|
||||
#[serde(default = "default_include_errors")]
|
||||
include_errors: bool,
|
||||
|
|
@ -51,6 +46,8 @@ pub enum MentionUri {
|
|||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
abs_path: Option<PathBuf>,
|
||||
line_range: RangeInclusive<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
column: Option<u32>,
|
||||
},
|
||||
Fetch {
|
||||
url: Url,
|
||||
|
|
@ -105,6 +102,17 @@ impl MentionUri {
|
|||
Ok(start_line..=end_line)
|
||||
}
|
||||
|
||||
let parse_column =
|
||||
|input: Option<String>| -> Option<u32> { input?.parse::<u32>().ok()?.checked_sub(1) };
|
||||
let validate_query_params = |url: &Url, allowed: &[&str]| -> Result<()> {
|
||||
for (key, _) in url.query_pairs() {
|
||||
if !allowed.contains(&key.as_ref()) {
|
||||
bail!("invalid query parameter")
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
let parse_absolute_path = |input: &str| -> Result<Self> {
|
||||
let (path_input, fragment) = input
|
||||
.split_once('#')
|
||||
|
|
@ -114,6 +122,7 @@ impl MentionUri {
|
|||
return Ok(MentionUri::Selection {
|
||||
abs_path: Some(path_input.into()),
|
||||
line_range: fragment,
|
||||
column: None,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -123,10 +132,12 @@ impl MentionUri {
|
|||
let line = row
|
||||
.checked_sub(1)
|
||||
.context("Line numbers should be 1-based")?;
|
||||
// TODO: Preserve column info too.
|
||||
Ok(MentionUri::Selection {
|
||||
abs_path: Some(abs_path),
|
||||
line_range: line..=line,
|
||||
column: path_with_position
|
||||
.column
|
||||
.map(|column| column.saturating_sub(1)),
|
||||
})
|
||||
} else {
|
||||
Ok(MentionUri::File { abs_path })
|
||||
|
|
@ -156,8 +167,10 @@ impl MentionUri {
|
|||
let path = normalized.as_ref();
|
||||
|
||||
if let Some(fragment) = url.fragment() {
|
||||
validate_query_params(&url, &["symbol", "column"])?;
|
||||
let line_range = parse_line_range(fragment).log_err().unwrap_or(1..=1);
|
||||
if let Some(name) = single_query_param(&url, "symbol")? {
|
||||
let column = parse_column(query_param(&url, "column"));
|
||||
if let Some(name) = query_param(&url, "symbol") {
|
||||
Ok(Self::Symbol {
|
||||
name,
|
||||
abs_path: path.into(),
|
||||
|
|
@ -167,6 +180,7 @@ impl MentionUri {
|
|||
Ok(Self::Selection {
|
||||
abs_path: Some(path.into()),
|
||||
line_range,
|
||||
column,
|
||||
})
|
||||
}
|
||||
} else if input.ends_with("/") {
|
||||
|
|
@ -186,13 +200,6 @@ impl MentionUri {
|
|||
id: acp::SessionId::new(thread_id),
|
||||
name,
|
||||
})
|
||||
} else if let Some(rule_id) = path.strip_prefix("/agent/rule/") {
|
||||
let name = single_query_param(&url, "name")?.context("Missing rule name")?;
|
||||
let rule_id = UserPromptId(rule_id.parse()?);
|
||||
Ok(Self::Rule {
|
||||
id: rule_id.into(),
|
||||
name,
|
||||
})
|
||||
} else if path == "/agent/diagnostics" {
|
||||
let mut include_errors = default_include_errors();
|
||||
let mut include_warnings = false;
|
||||
|
|
@ -216,9 +223,11 @@ impl MentionUri {
|
|||
.fragment()
|
||||
.context("Missing fragment for untitled buffer selection")?;
|
||||
let line_range = parse_line_range(fragment)?;
|
||||
validate_query_params(&url, &["column"])?;
|
||||
Ok(Self::Selection {
|
||||
abs_path: None,
|
||||
line_range,
|
||||
column: parse_column(query_param(&url, "column")),
|
||||
})
|
||||
} else if let Some(name) = path.strip_prefix("/agent/symbol/") {
|
||||
let fragment = url
|
||||
|
|
@ -245,13 +254,15 @@ impl MentionUri {
|
|||
abs_path: path.into(),
|
||||
})
|
||||
} else if path.starts_with("/agent/selection") {
|
||||
validate_query_params(&url, &["path", "column"])?;
|
||||
let fragment = url.fragment().context("Missing fragment for selection")?;
|
||||
let line_range = parse_line_range(fragment)?;
|
||||
let path =
|
||||
single_query_param(&url, "path")?.context("Missing path for selection")?;
|
||||
let column = parse_column(query_param(&url, "column"));
|
||||
let path = query_param(&url, "path").context("Missing path for selection")?;
|
||||
Ok(Self::Selection {
|
||||
abs_path: Some(path.into()),
|
||||
line_range,
|
||||
column,
|
||||
})
|
||||
} else if path.starts_with("/agent/terminal-selection") {
|
||||
let line_count = single_query_param(&url, "lines")?
|
||||
|
|
@ -319,7 +330,6 @@ impl MentionUri {
|
|||
MentionUri::PastedImage { name } => name.clone(),
|
||||
MentionUri::Symbol { name, .. } => name.clone(),
|
||||
MentionUri::Thread { name, .. } => name.clone(),
|
||||
MentionUri::Rule { name, .. } => name.clone(),
|
||||
MentionUri::Diagnostics { .. } => "Diagnostics".to_string(),
|
||||
MentionUri::TerminalSelection { line_count } => {
|
||||
if *line_count == 1 {
|
||||
|
|
@ -342,13 +352,33 @@ impl MentionUri {
|
|||
..
|
||||
} => selection_name(path.as_deref(), line_range),
|
||||
MentionUri::Fetch { url } => url.to_string(),
|
||||
MentionUri::Skill { name, .. } => name.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a label for this mention at the given disambiguation `detail`
|
||||
/// level. `detail == 0` is the base name returned by [`Self::name`]; higher
|
||||
/// levels include progressively more context (e.g. additional parent path
|
||||
/// components for files, or the source for skills) until a fixed point is
|
||||
/// reached. Intended to be driven by [`util::disambiguate::compute_disambiguation_details`].
|
||||
pub fn disambiguated_name(&self, detail: usize) -> String {
|
||||
if detail == 0 {
|
||||
return self.name();
|
||||
}
|
||||
|
||||
match self {
|
||||
MentionUri::Skill { name, source, .. } => {
|
||||
if source.is_empty() {
|
||||
// Must match `SkillSource::display_label()` in agent_skills.
|
||||
format!("{} (global)", name)
|
||||
} else {
|
||||
format!("{} ({})", name, source)
|
||||
}
|
||||
}
|
||||
MentionUri::File { abs_path, .. } | MentionUri::Directory { abs_path, .. } => {
|
||||
project::path_suffix(abs_path, detail)
|
||||
}
|
||||
_ => self.name(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -400,7 +430,6 @@ impl MentionUri {
|
|||
.unwrap_or_else(|| IconName::Folder.path().into()),
|
||||
MentionUri::Symbol { .. } => IconName::Code.path().into(),
|
||||
MentionUri::Thread { .. } => IconName::Thread.path().into(),
|
||||
MentionUri::Rule { .. } => IconName::Reader.path().into(),
|
||||
MentionUri::Diagnostics { .. } => IconName::Warning.path().into(),
|
||||
MentionUri::TerminalSelection { .. } => IconName::Terminal.path().into(),
|
||||
MentionUri::Selection { .. } => IconName::Reader.path().into(),
|
||||
|
|
@ -440,6 +469,7 @@ impl MentionUri {
|
|||
abs_path,
|
||||
name,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
let mut url = Url::parse("file:///").unwrap();
|
||||
url.set_path(&abs_path.to_string_lossy());
|
||||
|
|
@ -454,6 +484,7 @@ impl MentionUri {
|
|||
MentionUri::Selection {
|
||||
abs_path,
|
||||
line_range,
|
||||
column,
|
||||
} => {
|
||||
let mut url = if let Some(path) = abs_path {
|
||||
let mut url = Url::parse("file:///").unwrap();
|
||||
|
|
@ -464,6 +495,10 @@ impl MentionUri {
|
|||
url.set_path("/agent/untitled-buffer");
|
||||
url
|
||||
};
|
||||
if let Some(column) = column {
|
||||
url.query_pairs_mut()
|
||||
.append_pair("column", &(column + 1).to_string());
|
||||
}
|
||||
url.set_fragment(Some(&format!(
|
||||
"L{}:{}",
|
||||
line_range.start() + 1,
|
||||
|
|
@ -477,12 +512,6 @@ impl MentionUri {
|
|||
url.query_pairs_mut().append_pair("name", name);
|
||||
url
|
||||
}
|
||||
MentionUri::Rule { name, id } => {
|
||||
let mut url = Url::parse("zed:///").unwrap();
|
||||
url.set_path(&format!("/agent/rule/{id}"));
|
||||
url.query_pairs_mut().append_pair("name", name);
|
||||
url
|
||||
}
|
||||
MentionUri::Diagnostics {
|
||||
include_errors,
|
||||
include_warnings,
|
||||
|
|
@ -544,6 +573,11 @@ fn default_include_errors() -> bool {
|
|||
true
|
||||
}
|
||||
|
||||
fn query_param(url: &Url, name: &'static str) -> Option<String> {
|
||||
url.query_pairs()
|
||||
.find_map(|(key, value)| (key == name).then(|| value.to_string()))
|
||||
}
|
||||
|
||||
fn single_query_param(url: &Url, name: &'static str) -> Result<Option<String>> {
|
||||
let pairs = url.query_pairs().collect::<Vec<_>>();
|
||||
match pairs.as_slice() {
|
||||
|
|
@ -678,6 +712,7 @@ mod tests {
|
|||
abs_path: path,
|
||||
name,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path, Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(name, "MySymbol");
|
||||
|
|
@ -697,6 +732,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(line_range.start(), &4);
|
||||
|
|
@ -728,6 +764,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: None,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(line_range.start(), &0);
|
||||
assert_eq!(line_range.end(), &9);
|
||||
|
|
@ -754,20 +791,6 @@ mod tests {
|
|||
assert_eq!(parsed.to_uri().to_string(), thread_uri);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_rule_uri() {
|
||||
let rule_uri = "zed:///agent/rule/d8694ff2-90d5-4b6f-be33-33c1763acd52?name=Some+rule";
|
||||
let parsed = MentionUri::parse(rule_uri, PathStyle::local()).unwrap();
|
||||
match &parsed {
|
||||
MentionUri::Rule { id, name } => {
|
||||
assert_eq!(id.to_string(), "d8694ff2-90d5-4b6f-be33-33c1763acd52");
|
||||
assert_eq!(name, "Some rule");
|
||||
}
|
||||
_ => panic!("Expected Rule variant"),
|
||||
}
|
||||
assert_eq!(parsed.to_uri().to_string(), rule_uri);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_skill_uri_round_trip() {
|
||||
let skill_uri = MentionUri::Skill {
|
||||
|
|
@ -875,6 +898,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
|
||||
assert_eq!(line_range.start(), &41);
|
||||
|
|
@ -884,6 +908,29 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_absolute_file_path_with_row_and_column() {
|
||||
let file_path = "/path/to/file.rs:42:5";
|
||||
let parsed = MentionUri::parse(file_path, PathStyle::Posix).unwrap();
|
||||
match &parsed {
|
||||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
column,
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
|
||||
assert_eq!(line_range.start(), &41);
|
||||
assert_eq!(line_range.end(), &41);
|
||||
assert_eq!(column, &Some(4));
|
||||
|
||||
let parsed_again = MentionUri::parse(parsed.to_uri().as_ref(), PathStyle::Posix)
|
||||
.expect("selection URI with column should parse");
|
||||
assert_eq!(parsed_again, parsed.clone());
|
||||
}
|
||||
_ => panic!("Expected Selection variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_absolute_file_path_with_fragment_line() {
|
||||
let file_path = "/path/to/file.rs#L42";
|
||||
|
|
@ -892,6 +939,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
|
||||
assert_eq!(line_range.start(), &41);
|
||||
|
|
@ -921,6 +969,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
path.as_ref().unwrap(),
|
||||
|
|
@ -941,6 +990,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
path.as_ref().unwrap(),
|
||||
|
|
@ -973,6 +1023,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new("/path/to/file.rs"));
|
||||
assert_eq!(line_range.start(), &41);
|
||||
|
|
@ -990,6 +1041,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(
|
||||
path.as_ref().unwrap(),
|
||||
|
|
@ -1011,6 +1063,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(line_range.start(), &1871);
|
||||
|
|
@ -1028,6 +1081,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(line_range.start(), &9);
|
||||
|
|
@ -1043,6 +1097,7 @@ mod tests {
|
|||
MentionUri::Selection {
|
||||
abs_path: path,
|
||||
line_range,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(path.as_ref().unwrap(), Path::new(path!("/path/to/file.rs")));
|
||||
assert_eq!(line_range.start(), &9);
|
||||
|
|
@ -1070,4 +1125,68 @@ mod tests {
|
|||
let parsed_single = MentionUri::parse(single_line_uri, PathStyle::local()).unwrap();
|
||||
assert_eq!(parsed_single.name(), "Terminal (1 line)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_disambiguated_name() {
|
||||
// Two files with the same name — should disambiguate with parent dir
|
||||
let file_a = MentionUri::File {
|
||||
abs_path: PathBuf::from(path!("/project/src/README.md")),
|
||||
};
|
||||
let file_b = MentionUri::File {
|
||||
abs_path: PathBuf::from(path!("/project/docs/README.md")),
|
||||
};
|
||||
assert_eq!(file_a.name(), "README.md");
|
||||
assert_eq!(file_b.name(), "README.md");
|
||||
assert_eq!(file_a.disambiguated_name(0), "README.md");
|
||||
assert_eq!(file_a.disambiguated_name(1), "src/README.md");
|
||||
assert_eq!(file_b.disambiguated_name(1), "docs/README.md");
|
||||
|
||||
// Files that still collide at one parent should grow further.
|
||||
let deep_a = MentionUri::File {
|
||||
abs_path: PathBuf::from(path!("/a/src/foo.rs")),
|
||||
};
|
||||
let deep_b = MentionUri::File {
|
||||
abs_path: PathBuf::from(path!("/b/src/foo.rs")),
|
||||
};
|
||||
assert_eq!(deep_a.disambiguated_name(1), "src/foo.rs");
|
||||
assert_eq!(deep_b.disambiguated_name(1), "src/foo.rs");
|
||||
assert_eq!(deep_a.disambiguated_name(2), "a/src/foo.rs");
|
||||
assert_eq!(deep_b.disambiguated_name(2), "b/src/foo.rs");
|
||||
|
||||
// Two skills with the same name — should disambiguate with source
|
||||
let global_skill = MentionUri::Skill {
|
||||
name: "create-skill".into(),
|
||||
source: "".into(),
|
||||
skill_file_path: PathBuf::from("/global/create-skill/SKILL.md"),
|
||||
};
|
||||
let project_skill = MentionUri::Skill {
|
||||
name: "create-skill".into(),
|
||||
source: "my-project".into(),
|
||||
skill_file_path: PathBuf::from("/project/create-skill/SKILL.md"),
|
||||
};
|
||||
assert_eq!(global_skill.name(), "create-skill");
|
||||
assert_eq!(global_skill.disambiguated_name(0), "create-skill");
|
||||
assert_eq!(global_skill.disambiguated_name(1), "create-skill (global)");
|
||||
assert_eq!(
|
||||
project_skill.disambiguated_name(1),
|
||||
"create-skill (my-project)"
|
||||
);
|
||||
|
||||
// A type without special disambiguation (Thread) — detail has no effect
|
||||
// (the value is a fixed point so the disambiguation loop terminates).
|
||||
let thread = MentionUri::Thread {
|
||||
id: acp::SessionId::new("123"),
|
||||
name: "My Thread".into(),
|
||||
};
|
||||
assert_eq!(thread.disambiguated_name(0), "My Thread");
|
||||
assert_eq!(thread.disambiguated_name(1), "My Thread");
|
||||
assert_eq!(thread.disambiguated_name(5), "My Thread");
|
||||
|
||||
// Edge case: file at filesystem root has no parent to show
|
||||
let root_file = MentionUri::File {
|
||||
abs_path: PathBuf::from(path!("/README.md")),
|
||||
};
|
||||
assert_eq!(root_file.disambiguated_name(1), "README.md");
|
||||
assert_eq!(root_file.disambiguated_name(5), "README.md");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,82 @@ use std::{
|
|||
use task::Shell;
|
||||
use util::get_default_system_shell_preferring_bash;
|
||||
|
||||
/// Request to run a terminal command inside an OS-level sandbox.
|
||||
///
|
||||
/// Passed to [`super::AcpThread::create_terminal`]. The actual sandboxing
|
||||
/// mechanism is platform-specific (today: macOS Seatbelt; nothing on other
|
||||
/// platforms — the wrap is silently a no-op there), so callers describe the
|
||||
/// *intent* with plain data here rather than constructing platform-specific
|
||||
/// types directly.
|
||||
///
|
||||
/// All-zero defaults are the fully-sandboxed run. Setting `allow_network` /
|
||||
/// `allow_fs_write` requests a relaxation; the caller is responsible for
|
||||
/// having obtained user approval before reaching this point.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SandboxWrap {
|
||||
/// Directory subtrees the sandbox should allow writes to. Pass the
|
||||
/// project's worktree paths (and any per-command scratch directory)
|
||||
/// here — *not* the command's working directory, which is model-
|
||||
/// controlled and would let the model widen its own writable scope.
|
||||
pub writable_paths: Vec<PathBuf>,
|
||||
/// Allow outbound network access for this command.
|
||||
pub allow_network: bool,
|
||||
/// Allow unrestricted filesystem writes (ignores `writable_paths`).
|
||||
pub allow_fs_write: bool,
|
||||
}
|
||||
|
||||
/// Opaque RAII handle the sandbox implementation hands back to keep its
|
||||
/// per-command resources (e.g. an on-disk Seatbelt config file) alive for
|
||||
/// the duration of the spawned command. `Terminal` holds it in a field
|
||||
/// whose only job is to drop with the entity.
|
||||
pub type SandboxConfigHandle = Box<dyn std::any::Any + Send>;
|
||||
|
||||
/// Apply a [`SandboxWrap`] to a `(program, args)` pair, substituting the
|
||||
/// platform's sandbox-launcher invocation in place of the original. The
|
||||
/// returned `SandboxConfigHandle` (when `Some`) must be kept alive for the
|
||||
/// duration of the spawned command — dropping it deletes any on-disk
|
||||
/// config the launcher reads at startup.
|
||||
///
|
||||
/// On non-macOS hosts this is a no-op: the inputs pass through unchanged
|
||||
/// and the returned handle is `None`. (We don't yet have a sandbox
|
||||
/// integration for other platforms.)
|
||||
pub(crate) fn apply_sandbox_wrap(
|
||||
program: String,
|
||||
args: Vec<String>,
|
||||
sandbox_wrap: Option<SandboxWrap>,
|
||||
) -> anyhow::Result<(String, Vec<String>, Option<SandboxConfigHandle>)> {
|
||||
let Some(sandbox_wrap) = sandbox_wrap else {
|
||||
return Ok((program, args, None));
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let writable: Vec<&std::path::Path> = sandbox_wrap
|
||||
.writable_paths
|
||||
.iter()
|
||||
.map(|p| p.as_path())
|
||||
.collect();
|
||||
let permissions = sandbox::macos_seatbelt::SandboxPermissions {
|
||||
allow_network: sandbox_wrap.allow_network,
|
||||
allow_fs_write: sandbox_wrap.allow_fs_write,
|
||||
};
|
||||
let (new_program, new_args, config_file) =
|
||||
sandbox::macos_seatbelt::wrap_invocation(&program, &args, &writable, permissions)?;
|
||||
Ok((
|
||||
new_program,
|
||||
new_args,
|
||||
Some(Box::new(config_file) as SandboxConfigHandle),
|
||||
))
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
// No sandbox integration available; ignore the wrap request and
|
||||
// let the command run with the agent's ambient permissions.
|
||||
let _ = sandbox_wrap;
|
||||
Ok((program, args, None))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Terminal {
|
||||
id: acp::TerminalId,
|
||||
command: Entity<Markdown>,
|
||||
|
|
@ -30,6 +106,10 @@ pub struct Terminal {
|
|||
/// (e.g., clicking the Stop button). This is set before kill() is called
|
||||
/// so that code awaiting wait_for_exit() can check it deterministically.
|
||||
user_stopped: Arc<AtomicBool>,
|
||||
/// RAII handle kept alive for the duration of the sandboxed command.
|
||||
/// `None` when the command isn't sandboxed (the common case for
|
||||
/// terminals not created by the agent).
|
||||
_sandbox_config: Option<SandboxConfigHandle>,
|
||||
}
|
||||
|
||||
pub struct TerminalOutput {
|
||||
|
|
@ -48,11 +128,13 @@ impl Terminal {
|
|||
output_byte_limit: Option<usize>,
|
||||
terminal: Entity<terminal::Terminal>,
|
||||
language_registry: Arc<LanguageRegistry>,
|
||||
sandbox_config: Option<SandboxConfigHandle>,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Self {
|
||||
let command_task = terminal.read(cx).wait_for_completed_task(cx);
|
||||
Self {
|
||||
id,
|
||||
_sandbox_config: sandbox_config,
|
||||
command: cx.new(|cx| {
|
||||
Markdown::new(
|
||||
format!("```\n{}\n```", command_label).into(),
|
||||
|
|
|
|||
|
|
@ -508,6 +508,7 @@ impl AcpTools {
|
|||
} else {
|
||||
CopyButtonVisibility::Hidden
|
||||
},
|
||||
wrap_button_visibility: markdown::WrapButtonVisibility::Hidden,
|
||||
border: false,
|
||||
},
|
||||
),
|
||||
|
|
|
|||
|
|
@ -936,7 +936,11 @@ impl ActionLog {
|
|||
let mut undo_buffers = Vec::new();
|
||||
let mut futures = Vec::new();
|
||||
|
||||
for buffer in self.changed_buffers(cx).into_keys() {
|
||||
for buffer in self
|
||||
.changed_buffers(cx)
|
||||
.map(|(buffer, _)| buffer)
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
let buffer_ranges = vec![Anchor::min_max_range_for_buffer(
|
||||
buffer.read(cx).remote_id(),
|
||||
)];
|
||||
|
|
@ -1023,17 +1027,19 @@ impl ActionLog {
|
|||
}
|
||||
|
||||
/// Returns the set of buffers that contain edits that haven't been reviewed by the user.
|
||||
pub fn changed_buffers(&self, cx: &App) -> BTreeMap<Entity<Buffer>, Entity<BufferDiff>> {
|
||||
pub fn changed_buffers(
|
||||
&self,
|
||||
cx: &App,
|
||||
) -> impl Iterator<Item = (Entity<Buffer>, Entity<BufferDiff>)> {
|
||||
self.tracked_buffers
|
||||
.iter()
|
||||
.filter(|(_, tracked)| tracked.has_edits(cx))
|
||||
.map(|(buffer, tracked)| (buffer.clone(), tracked.diff.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns the total number of lines added and removed across all unreviewed buffers.
|
||||
pub fn diff_stats(&self, cx: &App) -> DiffStats {
|
||||
DiffStats::all_files(&self.changed_buffers(cx), cx)
|
||||
DiffStats::all_files(self.changed_buffers(cx), cx)
|
||||
}
|
||||
|
||||
/// Iterate over buffers changed since last read or edited by the model
|
||||
|
|
@ -1079,7 +1085,7 @@ impl DiffStats {
|
|||
}
|
||||
|
||||
pub fn all_files(
|
||||
changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
|
||||
changed_buffers: impl IntoIterator<Item = (Entity<Buffer>, Entity<BufferDiff>)>,
|
||||
cx: &App,
|
||||
) -> Self {
|
||||
let mut total = DiffStats::default();
|
||||
|
|
@ -1334,7 +1340,7 @@ mod tests {
|
|||
use std::env;
|
||||
use util::{RandomCharIter, path};
|
||||
|
||||
#[ctor::ctor]
|
||||
#[ctor::ctor(unsafe)]
|
||||
fn init_logger() {
|
||||
zlog::init_test();
|
||||
}
|
||||
|
|
@ -3254,21 +3260,21 @@ mod tests {
|
|||
child_log_1
|
||||
.read(cx)
|
||||
.changed_buffers(cx)
|
||||
.into_keys()
|
||||
.map(|(buffer, _)| buffer)
|
||||
.collect()
|
||||
});
|
||||
let child_2_changed: Vec<_> = cx.read(|cx| {
|
||||
child_log_2
|
||||
.read(cx)
|
||||
.changed_buffers(cx)
|
||||
.into_keys()
|
||||
.map(|(buffer, _)| buffer)
|
||||
.collect()
|
||||
});
|
||||
let parent_changed: Vec<_> = cx.read(|cx| {
|
||||
parent_log
|
||||
.read(cx)
|
||||
.changed_buffers(cx)
|
||||
.into_keys()
|
||||
.map(|(buffer, _)| buffer)
|
||||
.collect()
|
||||
});
|
||||
|
||||
|
|
@ -3494,7 +3500,6 @@ mod tests {
|
|||
action_log
|
||||
.read(cx)
|
||||
.changed_buffers(cx)
|
||||
.into_iter()
|
||||
.map(|(buffer, diff)| {
|
||||
let snapshot = buffer.read(cx).snapshot();
|
||||
(
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ streaming_diff.workspace = true
|
|||
strsim.workspace = true
|
||||
task.workspace = true
|
||||
telemetry.workspace = true
|
||||
tempfile.workspace = true
|
||||
text.workspace = true
|
||||
thiserror.workspace = true
|
||||
ui.workspace = true
|
||||
|
|
@ -77,11 +78,13 @@ zed_env_vars.workspace = true
|
|||
zstd.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
assets.workspace = true
|
||||
async-io.workspace = true
|
||||
agent_servers = { workspace = true, "features" = ["test-support"] }
|
||||
client = { workspace = true, "features" = ["test-support"] }
|
||||
clock = { workspace = true, "features" = ["test-support"] }
|
||||
context_server = { workspace = true, "features" = ["test-support"] }
|
||||
criterion.workspace = true
|
||||
ctor.workspace = true
|
||||
db = { workspace = true, "features" = ["test-support"] }
|
||||
editor = { workspace = true, "features" = ["test-support"] }
|
||||
|
|
@ -99,10 +102,15 @@ project = { workspace = true, "features" = ["test-support"] }
|
|||
rand.workspace = true
|
||||
reqwest_client.workspace = true
|
||||
settings = { workspace = true, "features" = ["test-support"] }
|
||||
tempfile.workspace = true
|
||||
|
||||
theme = { workspace = true, "features" = ["test-support"] }
|
||||
theme_settings.workspace = true
|
||||
|
||||
unindent = { workspace = true }
|
||||
|
||||
zlog.workspace = true
|
||||
|
||||
[[bench]]
|
||||
name = "edit_file_tool"
|
||||
harness = false
|
||||
required-features = ["test-support"]
|
||||
|
|
|
|||
743
crates/agent/benches/edit_file_tool.rs
Normal file
|
|
@ -0,0 +1,743 @@
|
|||
use std::{
|
||||
any::Any,
|
||||
future::Future,
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use action_log::ActionLog;
|
||||
use agent::{
|
||||
AgentTool, ContextServerRegistry, EditFileTool, EditFileToolInput, EditFileToolOutput,
|
||||
Templates, Thread, ToolCallEventStream, ToolInput,
|
||||
};
|
||||
use agent_settings::{AgentSettings, ToolRules};
|
||||
use criterion::{
|
||||
BatchSize, BenchmarkId, Criterion, Throughput, black_box, criterion_group, criterion_main,
|
||||
};
|
||||
use editor::{Editor, EditorStyle};
|
||||
use futures::{StreamExt as _, pin_mut, task::noop_waker};
|
||||
use gpui::{
|
||||
AnyWindowHandle, AppContext as _, BackgroundExecutor, Entity, Focusable as _, TestAppContext,
|
||||
UpdateGlobal as _,
|
||||
};
|
||||
use language::{FakeLspAdapter, rust_lang};
|
||||
use language_model::fake_provider::FakeLanguageModel;
|
||||
use project::{FakeFs, Project};
|
||||
use prompt_store::ProjectContext;
|
||||
use rand::{Rng as _, SeedableRng as _, rngs::StdRng};
|
||||
use serde_json::{Value, json};
|
||||
use settings::{Settings as _, SettingsStore};
|
||||
use ui::IntoElement as _;
|
||||
|
||||
const SEED: u64 = 0x5EED_5EED;
|
||||
const OLD_TEXT_CHUNK_SIZE: usize = 512;
|
||||
const NEW_TEXT_CHUNK_SIZE: usize = 512;
|
||||
|
||||
const FILE_PROJECT_PATH: &str = "root/src/workspace_snapshot.rs";
|
||||
const FILE_ABS_PATH: &str = "/root/src/workspace_snapshot.rs";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct EditOp {
|
||||
old_text: String,
|
||||
new_text: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct EditFixture {
|
||||
name: &'static str,
|
||||
old_file_text: String,
|
||||
expected_file_text: String,
|
||||
edits: Vec<EditOp>,
|
||||
}
|
||||
|
||||
struct BenchmarkHarness {
|
||||
cx: Option<TestAppContext>,
|
||||
edit_tool: Option<Arc<EditFileTool>>,
|
||||
thread: Option<Entity<Thread>>,
|
||||
partial_payloads: Vec<Value>,
|
||||
final_payload: Value,
|
||||
expected_file_text: String,
|
||||
editor: Option<Entity<Editor>>,
|
||||
window: Option<AnyWindowHandle>,
|
||||
// Keeps the LSP buffer-registration handle and the fake language server alive
|
||||
// for the lifetime of the benchmark so `didChange`/diagnostics keep flowing
|
||||
// while edits are applied.
|
||||
keep_alive: Vec<Box<dyn Any>>,
|
||||
}
|
||||
|
||||
impl Drop for BenchmarkHarness {
|
||||
fn drop(&mut self) {
|
||||
// Release our handles to the entities first.
|
||||
self.edit_tool.take();
|
||||
self.thread.take();
|
||||
self.editor.take();
|
||||
self.keep_alive.clear();
|
||||
|
||||
if let Some(mut cx) = self.cx.take() {
|
||||
// Close the editor window so the editor entity and the buffer handles
|
||||
// it holds are released, then pump the executor so cancelled editor /
|
||||
// action-log background tasks drop their captured handles before the
|
||||
// leak detector runs on `TestAppContext` drop.
|
||||
if let Some(window) = self.window.take() {
|
||||
cx.update_window(window, |_, window, _| window.remove_window())
|
||||
.ok();
|
||||
}
|
||||
cx.update(|_| {});
|
||||
cx.executor().run_until_parked();
|
||||
cx.quit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn edit_file_tool_streaming(c: &mut Criterion) {
|
||||
let fixtures = fixtures();
|
||||
let mut group = c.benchmark_group("edit_file_tool_streaming");
|
||||
group.sample_size(10);
|
||||
|
||||
for fixture in fixtures {
|
||||
let new_bytes: usize = fixture.edits.iter().map(|edit| edit.new_text.len()).sum();
|
||||
group.throughput(Throughput::Bytes(new_bytes as u64));
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new(fixture.name, fixture.old_file_text.len()),
|
||||
&fixture,
|
||||
|bench, fixture| {
|
||||
bench.iter_batched(
|
||||
|| setup_harness(fixture.clone()),
|
||||
|mut harness| {
|
||||
let output = run_streamed_edit(&mut harness);
|
||||
let EditFileToolOutput::Success { new_text, .. } = &output else {
|
||||
panic!("expected edit_file tool to succeed");
|
||||
};
|
||||
assert_eq!(new_text, &harness.expected_file_text);
|
||||
// Return the harness as part of the output so its teardown (which has
|
||||
// to pump the executor to release `Entity<Buffer>` handles captured by
|
||||
// background tasks) runs in criterion's drop phase after the timer has
|
||||
// stopped, rather than inside the timed region.
|
||||
(black_box(output), harness)
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn setup_harness(fixture: EditFixture) -> BenchmarkHarness {
|
||||
let mut cx = init_context();
|
||||
let executor = cx.executor();
|
||||
let parts = block_on_executor(
|
||||
&executor,
|
||||
setup_editor_and_tool(&mut cx, fixture.old_file_text.clone()),
|
||||
);
|
||||
// Let the LSP handshake, initial parse, and first layout settle before timing.
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let partial_payloads = streamed_partial_payloads(&fixture.edits);
|
||||
let final_payload = json!({
|
||||
"path": FILE_PROJECT_PATH,
|
||||
"edits": fixture
|
||||
.edits
|
||||
.iter()
|
||||
.map(|edit| json!({ "old_text": edit.old_text, "new_text": edit.new_text }))
|
||||
.collect::<Vec<_>>(),
|
||||
});
|
||||
|
||||
BenchmarkHarness {
|
||||
cx: Some(cx),
|
||||
edit_tool: Some(parts.edit_tool),
|
||||
thread: Some(parts.thread),
|
||||
partial_payloads,
|
||||
final_payload,
|
||||
expected_file_text: fixture.expected_file_text,
|
||||
editor: Some(parts.editor),
|
||||
window: Some(parts.window),
|
||||
keep_alive: parts.keep_alive,
|
||||
}
|
||||
}
|
||||
|
||||
struct HarnessParts {
|
||||
edit_tool: Arc<EditFileTool>,
|
||||
thread: Entity<Thread>,
|
||||
editor: Entity<Editor>,
|
||||
window: AnyWindowHandle,
|
||||
keep_alive: Vec<Box<dyn Any>>,
|
||||
}
|
||||
|
||||
/// Builds a project + edit tool, opens the target buffer in an editor view inside
|
||||
/// a window, and attaches a fake Rust language server. This mirrors the real app:
|
||||
/// the edited file is open in a pane with a language server, so each buffer edit
|
||||
/// drives the editor's observer cascade (matching brackets, code actions, outline,
|
||||
/// bracket colorization), a tree-sitter reparse, and an LSP `didChange` +
|
||||
/// diagnostics round-trip — the costs that dominate a real agent edit.
|
||||
async fn setup_editor_and_tool(cx: &mut TestAppContext, file_text: String) -> HarnessParts {
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
"/root",
|
||||
json!({
|
||||
"src": {
|
||||
"workspace_snapshot.rs": file_text,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let project = Project::test(fs, [Path::new("/root")], cx).await;
|
||||
let language_registry = project.read_with(cx, |project, _cx| project.languages().clone());
|
||||
language_registry.add(rust_lang());
|
||||
let mut fake_servers = language_registry.register_fake_lsp(
|
||||
"Rust",
|
||||
FakeLspAdapter {
|
||||
capabilities: lsp::ServerCapabilities {
|
||||
text_document_sync: Some(lsp::TextDocumentSyncCapability::Kind(
|
||||
lsp::TextDocumentSyncKind::INCREMENTAL,
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
let context_server_registry =
|
||||
cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
|
||||
let model = Arc::new(FakeLanguageModel::default());
|
||||
let thread = cx.new(|cx| {
|
||||
Thread::new(
|
||||
project.clone(),
|
||||
cx.new(|_cx| ProjectContext::default()),
|
||||
context_server_registry,
|
||||
Templates::new(),
|
||||
Some(model),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
let action_log: Entity<ActionLog> =
|
||||
thread.read_with(cx, |thread, _cx| thread.action_log().clone());
|
||||
let edit_tool = Arc::new(EditFileTool::new(
|
||||
project.clone(),
|
||||
thread.downgrade(),
|
||||
action_log,
|
||||
language_registry,
|
||||
));
|
||||
|
||||
// Open the same buffer the tool will edit and register it with the language
|
||||
// servers so edits produce `didChange` notifications.
|
||||
let buffer = project
|
||||
.update(cx, |project, cx| {
|
||||
project.open_local_buffer(FILE_ABS_PATH, cx)
|
||||
})
|
||||
.await
|
||||
.expect("failed to open buffer");
|
||||
let lsp_handle = project.update(cx, |project, cx| {
|
||||
project.register_buffer_with_language_servers(&buffer, cx)
|
||||
});
|
||||
|
||||
let fake_server = fake_servers
|
||||
.next()
|
||||
.await
|
||||
.expect("fake language server should start");
|
||||
// Publish diagnostics on every edit, mirroring a real server reacting to
|
||||
// `didChange`, so the editor's diagnostics path runs per edit.
|
||||
let server = fake_server.clone();
|
||||
fake_server.handle_notification::<lsp::notification::DidChangeTextDocument, _>(
|
||||
move |params, _cx| {
|
||||
server.notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
|
||||
uri: params.text_document.uri.clone(),
|
||||
version: Some(params.text_document.version),
|
||||
diagnostics: vec![lsp::Diagnostic {
|
||||
range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 1)),
|
||||
severity: Some(lsp::DiagnosticSeverity::WARNING),
|
||||
message: "bench diagnostic".to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Attach an editor view in a window and lay it out once so the viewport-gated
|
||||
// observers (bracket colorization, selection highlights) have a visible range.
|
||||
let window = cx.add_window(|window, cx| {
|
||||
let mut editor = Editor::for_buffer(buffer.clone(), Some(project.clone()), window, cx);
|
||||
editor.set_style(EditorStyle::default(), window, cx);
|
||||
window.focus(&editor.focus_handle(cx), cx);
|
||||
editor
|
||||
});
|
||||
let editor = window.root(cx).expect("window should have an editor root");
|
||||
let window: AnyWindowHandle = window.into();
|
||||
// Lay out and paint a real frame so the editor establishes a viewport (this
|
||||
// is what makes the viewport-gated observers like bracket colorization run).
|
||||
{
|
||||
let mut visual_cx = gpui::VisualTestContext::from_window(window, &*cx);
|
||||
visual_cx.draw(
|
||||
gpui::point(gpui::px(0.0), gpui::px(0.0)),
|
||||
gpui::size(gpui::px(1024.0), gpui::px(768.0)),
|
||||
|_, _| editor.clone().into_any_element(),
|
||||
);
|
||||
}
|
||||
|
||||
let keep_alive: Vec<Box<dyn Any>> = vec![
|
||||
Box::new(lsp_handle),
|
||||
Box::new(fake_server),
|
||||
Box::new(fake_servers),
|
||||
Box::new(buffer),
|
||||
];
|
||||
|
||||
HarnessParts {
|
||||
edit_tool,
|
||||
thread,
|
||||
editor,
|
||||
window,
|
||||
keep_alive,
|
||||
}
|
||||
}
|
||||
|
||||
fn init_context() -> TestAppContext {
|
||||
let cx = TestAppContext::single();
|
||||
cx.update(|cx| {
|
||||
let settings_store = SettingsStore::test(cx);
|
||||
cx.set_global(settings_store);
|
||||
assets::Assets.load_test_fonts(cx);
|
||||
theme_settings::init(theme::LoadThemes::JustBase, cx);
|
||||
editor::init(cx);
|
||||
SettingsStore::update_global(cx, |store: &mut SettingsStore, cx| {
|
||||
store.update_user_settings(cx, |settings| {
|
||||
settings
|
||||
.project
|
||||
.all_languages
|
||||
.defaults
|
||||
.ensure_final_newline_on_save = Some(false);
|
||||
settings.project.all_languages.defaults.colorize_brackets = Some(true);
|
||||
});
|
||||
});
|
||||
|
||||
let mut agent_settings = AgentSettings::get_global(cx).clone();
|
||||
agent_settings.tool_permissions.tools.insert(
|
||||
EditFileTool::NAME.into(),
|
||||
ToolRules {
|
||||
default: Some(settings::ToolPermissionMode::Allow),
|
||||
always_allow: vec![],
|
||||
always_deny: vec![],
|
||||
always_confirm: vec![],
|
||||
invalid_patterns: vec![],
|
||||
},
|
||||
);
|
||||
AgentSettings::override_global(agent_settings, cx);
|
||||
});
|
||||
cx
|
||||
}
|
||||
|
||||
fn run_streamed_edit(harness: &mut BenchmarkHarness) -> EditFileToolOutput {
|
||||
let (mut sender, input): (_, ToolInput<EditFileToolInput>) = ToolInput::test();
|
||||
for payload in &harness.partial_payloads {
|
||||
sender.send_partial(payload.clone());
|
||||
}
|
||||
sender.send_full(harness.final_payload.clone());
|
||||
|
||||
let (event_stream, _event_rx) = ToolCallEventStream::test();
|
||||
let cx = harness
|
||||
.cx
|
||||
.as_ref()
|
||||
.expect("benchmark harness should have a cx");
|
||||
let task = cx.update(|cx| {
|
||||
harness
|
||||
.edit_tool
|
||||
.as_ref()
|
||||
.expect("benchmark harness should have an edit tool")
|
||||
.clone()
|
||||
.run(input, event_stream, cx)
|
||||
});
|
||||
|
||||
let executor = harness
|
||||
.cx
|
||||
.as_ref()
|
||||
.expect("benchmark harness should have a cx")
|
||||
.executor();
|
||||
block_on_executor(&executor, task).unwrap()
|
||||
}
|
||||
|
||||
fn block_on_executor<R>(executor: &BackgroundExecutor, future: impl Future<Output = R>) -> R {
|
||||
pin_mut!(future);
|
||||
let waker = noop_waker();
|
||||
let mut task_context = Context::from_waker(&waker);
|
||||
|
||||
for _ in 0..10_000 {
|
||||
if let Poll::Ready(output) = future.as_mut().poll(&mut task_context) {
|
||||
return output;
|
||||
}
|
||||
executor.run_until_parked();
|
||||
}
|
||||
|
||||
panic!("future did not complete while running edit_file_tool benchmark");
|
||||
}
|
||||
|
||||
/// Builds the streamed partial payloads for a (possibly multi-edit) session,
|
||||
/// mirroring how the agent reveals one edit at a time: earlier edits stay
|
||||
/// complete in the array while the current edit streams its `old_text` then its
|
||||
/// `new_text` in chunks.
|
||||
fn streamed_partial_payloads(edits: &[EditOp]) -> Vec<Value> {
|
||||
let path = FILE_PROJECT_PATH;
|
||||
let mut payloads = vec![json!({ "path": path }), json!({ "path": path })];
|
||||
|
||||
for index in 0..edits.len() {
|
||||
let completed: Vec<Value> = edits[..index]
|
||||
.iter()
|
||||
.map(|edit| json!({ "old_text": edit.old_text, "new_text": edit.new_text }))
|
||||
.collect();
|
||||
let edit = &edits[index];
|
||||
|
||||
for old_end in chunk_ends(&edit.old_text, OLD_TEXT_CHUNK_SIZE) {
|
||||
let mut arr = completed.clone();
|
||||
arr.push(json!({ "old_text": &edit.old_text[..old_end] }));
|
||||
payloads.push(json!({ "path": path, "edits": arr }));
|
||||
}
|
||||
|
||||
let mut arr = completed.clone();
|
||||
arr.push(json!({ "old_text": edit.old_text, "new_text": "" }));
|
||||
payloads.push(json!({ "path": path, "edits": arr }));
|
||||
|
||||
for new_end in chunk_ends(&edit.new_text, NEW_TEXT_CHUNK_SIZE) {
|
||||
let mut arr = completed.clone();
|
||||
arr.push(json!({ "old_text": edit.old_text, "new_text": &edit.new_text[..new_end] }));
|
||||
payloads.push(json!({ "path": path, "edits": arr }));
|
||||
}
|
||||
}
|
||||
|
||||
payloads
|
||||
}
|
||||
|
||||
fn chunk_ends(text: &str, chunk_size: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
let mut end = 0;
|
||||
std::iter::from_fn(move || {
|
||||
if end == text.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
end = (end + chunk_size).min(text.len());
|
||||
while !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
Some(end)
|
||||
})
|
||||
}
|
||||
|
||||
fn fixtures() -> Vec<EditFixture> {
|
||||
vec![
|
||||
make_fixture(
|
||||
"tiny_function_rewrite",
|
||||
2,
|
||||
EditPattern::LocalizedRewrite {
|
||||
start_line: 12,
|
||||
line_count: 6,
|
||||
},
|
||||
SEED,
|
||||
),
|
||||
make_fixture(
|
||||
"small_function_rewrite",
|
||||
5,
|
||||
EditPattern::LocalizedRewrite {
|
||||
start_line: 22,
|
||||
line_count: 12,
|
||||
},
|
||||
SEED + 1,
|
||||
),
|
||||
make_fixture(
|
||||
"medium_many_small_changes",
|
||||
8,
|
||||
EditPattern::ManySmallChanges { every_nth_line: 7 },
|
||||
SEED + 2,
|
||||
),
|
||||
make_fixture(
|
||||
"medium_insertions",
|
||||
8,
|
||||
EditPattern::InsertHelperBlocks { every_nth_line: 9 },
|
||||
SEED + 3,
|
||||
),
|
||||
make_large_multi_edit_fixture("large_multi_edit", 80, 16, SEED + 4),
|
||||
]
|
||||
}
|
||||
|
||||
enum EditPattern {
|
||||
LocalizedRewrite {
|
||||
start_line: usize,
|
||||
line_count: usize,
|
||||
},
|
||||
ManySmallChanges {
|
||||
every_nth_line: usize,
|
||||
},
|
||||
InsertHelperBlocks {
|
||||
every_nth_line: usize,
|
||||
},
|
||||
}
|
||||
|
||||
fn make_fixture(
|
||||
name: &'static str,
|
||||
function_count: usize,
|
||||
pattern: EditPattern,
|
||||
seed: u64,
|
||||
) -> EditFixture {
|
||||
let mut rng = StdRng::seed_from_u64(seed);
|
||||
let old_lines = random_rust_module(&mut rng, function_count);
|
||||
let edit_range = edit_range(&old_lines, &pattern);
|
||||
let old_text = old_lines[edit_range.clone()].join("\n");
|
||||
let mut new_lines = old_lines.clone();
|
||||
|
||||
match pattern {
|
||||
EditPattern::LocalizedRewrite { .. } => {
|
||||
rewrite_local_block(&mut new_lines[edit_range.clone()], &mut rng)
|
||||
}
|
||||
EditPattern::ManySmallChanges { every_nth_line } => {
|
||||
rewrite_many_small_lines(&mut new_lines[edit_range.clone()], every_nth_line, &mut rng)
|
||||
}
|
||||
EditPattern::InsertHelperBlocks { every_nth_line } => {
|
||||
insert_helper_blocks(&mut new_lines, edit_range.clone(), every_nth_line, &mut rng)
|
||||
}
|
||||
}
|
||||
|
||||
let new_text_end = edit_range.end + new_lines.len().saturating_sub(old_lines.len());
|
||||
let old_file_text = old_lines.join("\n");
|
||||
let expected_file_text = new_lines.join("\n");
|
||||
let new_text = new_lines[edit_range.start..new_text_end].join("\n");
|
||||
|
||||
EditFixture {
|
||||
name,
|
||||
old_file_text,
|
||||
expected_file_text,
|
||||
edits: vec![EditOp { old_text, new_text }],
|
||||
}
|
||||
}
|
||||
|
||||
fn make_large_multi_edit_fixture(
|
||||
name: &'static str,
|
||||
function_count: usize,
|
||||
edit_count: usize,
|
||||
seed: u64,
|
||||
) -> EditFixture {
|
||||
const HEADER_LINES: usize = 10;
|
||||
const FUNCTION_LINES: usize = 12;
|
||||
const FUNCTION_BODY_LINES: usize = 11;
|
||||
|
||||
let mut rng = StdRng::seed_from_u64(seed);
|
||||
let old_lines = random_rust_module(&mut rng, function_count);
|
||||
let old_file_text = old_lines.join("\n");
|
||||
|
||||
let step = (function_count / edit_count).max(1);
|
||||
let mut picks: Vec<usize> = (0..edit_count)
|
||||
.map(|k| (k * step).min(function_count - 1))
|
||||
.collect();
|
||||
picks.dedup();
|
||||
|
||||
let replacements: Vec<(usize, Vec<String>)> = picks
|
||||
.iter()
|
||||
.map(|&function_index| {
|
||||
(
|
||||
function_index,
|
||||
large_function_lines(&mut rng, function_index),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let edits = replacements
|
||||
.iter()
|
||||
.map(|(function_index, new_function)| {
|
||||
let start = HEADER_LINES + function_index * FUNCTION_LINES;
|
||||
let end = start + FUNCTION_BODY_LINES;
|
||||
EditOp {
|
||||
old_text: old_lines[start..end].join("\n"),
|
||||
new_text: new_function.join("\n"),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut new_lines = old_lines;
|
||||
for (function_index, new_function) in replacements.iter().rev() {
|
||||
let start = HEADER_LINES + function_index * FUNCTION_LINES;
|
||||
let end = start + FUNCTION_BODY_LINES;
|
||||
new_lines.splice(start..end, new_function.iter().cloned());
|
||||
}
|
||||
let expected_file_text = new_lines.join("\n");
|
||||
|
||||
EditFixture {
|
||||
name,
|
||||
old_file_text,
|
||||
expected_file_text,
|
||||
edits,
|
||||
}
|
||||
}
|
||||
|
||||
fn large_function_lines(rng: &mut StdRng, index: usize) -> Vec<String> {
|
||||
let function_name = identifier(rng, index + 40_000);
|
||||
let argument_name = identifier(rng, index + 41_000);
|
||||
|
||||
let mut lines = vec![
|
||||
format!(
|
||||
" pub fn {function_name}(&mut self, {argument_name}: usize) -> Result<usize> {{"
|
||||
),
|
||||
format!(" let mut accumulator = {argument_name};"),
|
||||
];
|
||||
|
||||
let body_lines = rng.random_range(30..42);
|
||||
for body_index in 0..body_lines {
|
||||
let local_name = identifier(rng, index + 50_000 + body_index);
|
||||
let multiplier = rng.random_range(2..19);
|
||||
let offset = rng.random_range(1..256);
|
||||
match body_index % 4 {
|
||||
0 => lines.push(format!(
|
||||
" let {local_name} = accumulator.saturating_mul({multiplier}).saturating_add({offset});"
|
||||
)),
|
||||
1 => lines.push(format!(
|
||||
" accumulator = {local_name}.saturating_sub(self.version % {offset}.max(1));"
|
||||
)),
|
||||
2 => lines.push(format!(
|
||||
" if {local_name} % {multiplier} == 0 {{ accumulator = accumulator.saturating_add({local_name}); }}"
|
||||
)),
|
||||
_ => lines.push(format!(
|
||||
" self.buffers.insert(\"{local_name}\".to_string(), accumulator);"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(" self.version = self.version.saturating_add(accumulator);".to_string());
|
||||
lines.push(" Ok(accumulator)".to_string());
|
||||
lines.push(" }".to_string());
|
||||
lines
|
||||
}
|
||||
|
||||
fn edit_range(lines: &[String], pattern: &EditPattern) -> std::ops::Range<usize> {
|
||||
let mut range = match pattern {
|
||||
EditPattern::LocalizedRewrite {
|
||||
start_line,
|
||||
line_count,
|
||||
} => *start_line..(*start_line + *line_count).min(lines.len()),
|
||||
EditPattern::ManySmallChanges { .. } | EditPattern::InsertHelperBlocks { .. } => {
|
||||
10..lines.len().saturating_sub(5)
|
||||
}
|
||||
};
|
||||
|
||||
while range.end > range.start && lines[range.end - 1].is_empty() {
|
||||
range.end -= 1;
|
||||
}
|
||||
|
||||
range
|
||||
}
|
||||
|
||||
fn random_rust_module(rng: &mut StdRng, function_count: usize) -> Vec<String> {
|
||||
let mut lines = vec![
|
||||
"use anyhow::{Context as _, Result};".to_string(),
|
||||
"use collections::HashMap;".to_string(),
|
||||
"".to_string(),
|
||||
"#[derive(Clone, Debug)]".to_string(),
|
||||
"pub struct WorkspaceSnapshot {".to_string(),
|
||||
" buffers: HashMap<String, usize>,".to_string(),
|
||||
" version: usize,".to_string(),
|
||||
"}".to_string(),
|
||||
"".to_string(),
|
||||
"impl WorkspaceSnapshot {".to_string(),
|
||||
];
|
||||
|
||||
for function_index in 0..function_count {
|
||||
let function_name = identifier(rng, function_index);
|
||||
let argument_name = identifier(rng, function_index + 1_000);
|
||||
let local_name = identifier(rng, function_index + 2_000);
|
||||
let branch_name = identifier(rng, function_index + 3_000);
|
||||
let multiplier = rng.random_range(2..17);
|
||||
let offset = rng.random_range(1..128);
|
||||
|
||||
lines.extend([
|
||||
format!(
|
||||
" pub fn {function_name}(&mut self, {argument_name}: usize) -> Result<usize> {{"
|
||||
),
|
||||
format!(" let mut {local_name} = {argument_name}.saturating_mul({multiplier});"),
|
||||
format!(" if {local_name} % 2 == 0 {{"),
|
||||
format!(
|
||||
" {local_name} = {local_name}.saturating_add(self.version + {offset});"
|
||||
),
|
||||
" } else {".to_string(),
|
||||
format!(" {local_name} = {local_name}.saturating_sub({offset});"),
|
||||
" }".to_string(),
|
||||
format!(" let {branch_name} = self.buffers.len().saturating_add({local_name});"),
|
||||
format!(" self.version = self.version.saturating_add({branch_name});"),
|
||||
format!(" Ok({branch_name})"),
|
||||
" }".to_string(),
|
||||
"".to_string(),
|
||||
]);
|
||||
}
|
||||
|
||||
lines.push("}".to_string());
|
||||
lines.push("".to_string());
|
||||
lines.push("pub fn normalize_path(path: &str) -> String {".to_string());
|
||||
lines.push(" path.replace('\\\\', \"/\")".to_string());
|
||||
lines.push("}".to_string());
|
||||
lines
|
||||
}
|
||||
|
||||
fn rewrite_local_block(lines: &mut [String], rng: &mut StdRng) {
|
||||
for (line_index, line) in lines.iter_mut().enumerate() {
|
||||
let suffix = identifier(rng, line_index + 10_000);
|
||||
if line.contains("saturating_add") {
|
||||
*line = format!(
|
||||
" let {suffix} = self.version.checked_add({line_index}).context(\"version overflow\")?;"
|
||||
);
|
||||
} else if line.contains("saturating_sub") {
|
||||
*line = format!(
|
||||
" {suffix}.saturating_sub({});",
|
||||
rng.random_range(8..256)
|
||||
);
|
||||
} else if line.trim().is_empty() {
|
||||
*line =
|
||||
format!(" tracing::trace!(target: \"agent_bench\", value = {line_index});");
|
||||
} else {
|
||||
*line = format!("{line} // updated {suffix}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rewrite_many_small_lines(lines: &mut [String], every_nth_line: usize, rng: &mut StdRng) {
|
||||
for (line_index, line) in lines.iter_mut().enumerate() {
|
||||
if line_index.is_multiple_of(every_nth_line) || line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let suffix = identifier(rng, line_index + 20_000);
|
||||
*line = format!("{line} // audited {suffix}");
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_helper_blocks(
|
||||
lines: &mut Vec<String>,
|
||||
range: std::ops::Range<usize>,
|
||||
every_nth_line: usize,
|
||||
rng: &mut StdRng,
|
||||
) {
|
||||
let mut line_index = range.start;
|
||||
while line_index < range.end.min(lines.len()) {
|
||||
if line_index.is_multiple_of(every_nth_line) && !lines[line_index].trim().is_empty() {
|
||||
let suffix = identifier(rng, line_index + 30_000);
|
||||
lines.splice(
|
||||
line_index..line_index,
|
||||
[
|
||||
format!(" let {suffix}_before = self.version;"),
|
||||
format!(" tracing::debug!(version = {suffix}_before);"),
|
||||
],
|
||||
);
|
||||
line_index += 2;
|
||||
}
|
||||
line_index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn identifier(rng: &mut StdRng, salt: usize) -> String {
|
||||
const PARTS: &[&str] = &[
|
||||
"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "theta", "lambda", "sigma", "omega",
|
||||
];
|
||||
format!(
|
||||
"{}_{}_{}",
|
||||
PARTS[rng.random_range(0..PARTS.len())],
|
||||
salt,
|
||||
rng.random_range(0..10_000)
|
||||
)
|
||||
}
|
||||
|
||||
criterion_group!(benches, edit_file_tool_streaming);
|
||||
criterion_main!(benches);
|
||||
|
|
@ -16,7 +16,7 @@ use sqlez::{
|
|||
connection::Connection,
|
||||
statement::Statement,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use std::{io::ErrorKind, path::PathBuf, sync::Arc};
|
||||
use ui::{App, SharedString};
|
||||
use util::path_list::PathList;
|
||||
use zed_env_vars::ZED_STATELESS;
|
||||
|
|
@ -53,7 +53,7 @@ impl From<&DbThreadMetadata> for acp_thread::AgentSessionInfo {
|
|||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct DbThread {
|
||||
pub title: SharedString,
|
||||
pub messages: Vec<DbMessage>,
|
||||
pub messages: Vec<Arc<DbMessage>>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub detailed_summary: Option<SharedString>,
|
||||
|
|
@ -81,6 +81,8 @@ pub struct DbThread {
|
|||
pub draft_prompt: Option<Vec<acp::ContentBlock>>,
|
||||
#[serde(default)]
|
||||
pub ui_scroll_position: Option<SerializedScrollPosition>,
|
||||
#[serde(default)]
|
||||
pub sandboxed_terminal_temp_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
|
|
@ -92,7 +94,7 @@ pub struct SerializedScrollPosition {
|
|||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SharedThread {
|
||||
pub title: SharedString,
|
||||
pub messages: Vec<DbMessage>,
|
||||
pub messages: Vec<Arc<DbMessage>>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub model: Option<DbLanguageModel>,
|
||||
|
|
@ -130,6 +132,7 @@ impl SharedThread {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -206,7 +209,7 @@ impl DbThread {
|
|||
crate::Message::User(UserMessage {
|
||||
// MessageId from old format can't be meaningfully converted, so generate a new one
|
||||
id,
|
||||
content,
|
||||
content: Arc::from(content),
|
||||
})
|
||||
}
|
||||
language_model::Role::Assistant => {
|
||||
|
|
@ -285,7 +288,7 @@ impl DbThread {
|
|||
}
|
||||
};
|
||||
|
||||
messages.push(message);
|
||||
messages.push(Arc::new(message));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
|
|
@ -309,6 +312,7 @@ impl DbThread {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -569,15 +573,7 @@ impl ThreadsDatabase {
|
|||
|
||||
let rows = select(id.0)?;
|
||||
if let Some((data_type, data)) = rows.into_iter().next() {
|
||||
let json_data = match data_type {
|
||||
DataType::Zstd => {
|
||||
let decompressed = zstd::decode_all(&data[..])?;
|
||||
String::from_utf8(decompressed)?
|
||||
}
|
||||
DataType::Json => String::from_utf8(data)?,
|
||||
};
|
||||
let thread = DbThread::from_json(json_data.as_bytes())?;
|
||||
Ok(Some(thread))
|
||||
Ok(Some(Self::deserialize_thread(data_type, data)?))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
|
|
@ -596,17 +592,71 @@ impl ThreadsDatabase {
|
|||
.spawn(async move { Self::save_thread_sync(&connection, id, thread, &folder_paths) })
|
||||
}
|
||||
|
||||
fn deserialize_thread(data_type: DataType, data: Vec<u8>) -> Result<DbThread> {
|
||||
let json_data = match data_type {
|
||||
DataType::Zstd => {
|
||||
let decompressed = zstd::decode_all(&data[..])?;
|
||||
String::from_utf8(decompressed)?
|
||||
}
|
||||
DataType::Json => String::from_utf8(data)?,
|
||||
};
|
||||
DbThread::from_json(json_data.as_bytes())
|
||||
}
|
||||
|
||||
fn sandboxed_terminal_temp_dir(data_type: DataType, data: Vec<u8>) -> Option<PathBuf> {
|
||||
match Self::deserialize_thread(data_type, data) {
|
||||
Ok(thread) => thread.sandboxed_terminal_temp_dir,
|
||||
Err(error) => {
|
||||
log::warn!("failed to deserialize thread before deleting it: {error:#}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_sandboxed_terminal_temp_dir(temp_dir: PathBuf) {
|
||||
match std::fs::remove_dir_all(&temp_dir) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => {}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"failed to remove sandboxed terminal temp directory {}: {error}",
|
||||
temp_dir.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_thread(&self, id: acp::SessionId) -> Task<Result<()>> {
|
||||
let connection = self.connection.clone();
|
||||
|
||||
self.executor.spawn(async move {
|
||||
let connection = connection.lock();
|
||||
let sandboxed_terminal_temp_dir = {
|
||||
let connection = connection.lock();
|
||||
|
||||
let mut delete = connection.exec_bound::<Arc<str>>(indoc! {"
|
||||
DELETE FROM threads WHERE id = ?
|
||||
"})?;
|
||||
let mut select =
|
||||
connection.select_bound::<Arc<str>, (DataType, Vec<u8>)>(indoc! {"
|
||||
SELECT data_type, data FROM threads WHERE id = ? LIMIT 1
|
||||
"})?;
|
||||
|
||||
delete(id.0)?;
|
||||
let sandboxed_terminal_temp_dir = select(id.0.clone())?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|(data_type, data)| {
|
||||
Self::sandboxed_terminal_temp_dir(data_type, data)
|
||||
});
|
||||
|
||||
let mut delete = connection.exec_bound::<Arc<str>>(indoc! {"
|
||||
DELETE FROM threads WHERE id = ?
|
||||
"})?;
|
||||
|
||||
delete(id.0)?;
|
||||
|
||||
sandboxed_terminal_temp_dir
|
||||
};
|
||||
|
||||
if let Some(temp_dir) = sandboxed_terminal_temp_dir {
|
||||
Self::remove_sandboxed_terminal_temp_dir(temp_dir);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
|
|
@ -616,13 +666,32 @@ impl ThreadsDatabase {
|
|||
let connection = self.connection.clone();
|
||||
|
||||
self.executor.spawn(async move {
|
||||
let connection = connection.lock();
|
||||
let sandboxed_terminal_temp_dirs = {
|
||||
let connection = connection.lock();
|
||||
|
||||
let mut delete = connection.exec_bound::<()>(indoc! {"
|
||||
DELETE FROM threads
|
||||
"})?;
|
||||
let mut select = connection.select_bound::<(), (DataType, Vec<u8>)>(indoc! {"
|
||||
SELECT data_type, data FROM threads
|
||||
"})?;
|
||||
|
||||
delete(())?;
|
||||
let sandboxed_terminal_temp_dirs = select(())?
|
||||
.into_iter()
|
||||
.filter_map(|(data_type, data)| {
|
||||
Self::sandboxed_terminal_temp_dir(data_type, data)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut delete = connection.exec_bound::<()>(indoc! {"
|
||||
DELETE FROM threads
|
||||
"})?;
|
||||
|
||||
delete(())?;
|
||||
|
||||
sandboxed_terminal_temp_dirs
|
||||
};
|
||||
|
||||
for temp_dir in sandboxed_terminal_temp_dirs {
|
||||
Self::remove_sandboxed_terminal_temp_dir(temp_dir);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
|
|
@ -694,6 +763,7 @@ mod tests {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -797,6 +867,78 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandboxed_terminal_temp_dir_defaults_to_none() {
|
||||
let json = r#"{
|
||||
"title": "Old Thread",
|
||||
"messages": [],
|
||||
"updated_at": "2024-01-01T00:00:00Z"
|
||||
}"#;
|
||||
|
||||
let db_thread: DbThread = serde_json::from_str(json).expect("Failed to deserialize");
|
||||
|
||||
assert!(
|
||||
db_thread.sandboxed_terminal_temp_dir.is_none(),
|
||||
"Legacy threads without sandboxed_terminal_temp_dir should default to None"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_sandboxed_terminal_temp_dir_roundtrips_through_save_load(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let database = ThreadsDatabase::new(cx.executor()).unwrap();
|
||||
let thread_id = session_id("sandbox-temp-dir-thread");
|
||||
let temp_dir = tempfile::Builder::new()
|
||||
.prefix("zed-agent-terminal-test-")
|
||||
.tempdir()
|
||||
.unwrap()
|
||||
.keep();
|
||||
let mut thread = make_thread(
|
||||
"Sandbox Temp Dir Thread",
|
||||
Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
|
||||
);
|
||||
thread.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
|
||||
|
||||
database
|
||||
.save_thread(thread_id.clone(), thread, PathList::default())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let loaded = database
|
||||
.load_thread(thread_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("thread should exist");
|
||||
assert_eq!(loaded.sandboxed_terminal_temp_dir, Some(temp_dir.clone()));
|
||||
std::fs::remove_dir_all(temp_dir).unwrap();
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_thread_removes_sandboxed_terminal_temp_dir(cx: &mut TestAppContext) {
|
||||
let database = ThreadsDatabase::new(cx.executor()).unwrap();
|
||||
let thread_id = session_id("sandbox-temp-dir-delete-thread");
|
||||
let temp_dir = tempfile::Builder::new()
|
||||
.prefix("zed-agent-terminal-test-")
|
||||
.tempdir()
|
||||
.unwrap()
|
||||
.keep();
|
||||
std::fs::write(temp_dir.join("sentinel"), b"content").unwrap();
|
||||
let mut thread = make_thread(
|
||||
"Sandbox Temp Dir Delete Thread",
|
||||
Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(),
|
||||
);
|
||||
thread.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
|
||||
|
||||
database
|
||||
.save_thread(thread_id.clone(), thread, PathList::default())
|
||||
.await
|
||||
.unwrap();
|
||||
database.delete_thread(thread_id).await.unwrap();
|
||||
|
||||
assert!(!temp_dir.exists());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_subagent_context_roundtrips_through_save_load(cx: &mut TestAppContext) {
|
||||
let database = ThreadsDatabase::new(cx.executor()).unwrap();
|
||||
|
|
|
|||
|
|
@ -9,9 +9,7 @@ use fs::Fs;
|
|||
use gpui::{App, Entity, Task};
|
||||
use language_model::{LanguageModelId, LanguageModelProviderId, LanguageModelRegistry};
|
||||
use project::{AgentId, Project};
|
||||
use prompt_store::PromptStore;
|
||||
use settings::{LanguageModelSelection, Settings as _, update_settings_file};
|
||||
use util::ResultExt as _;
|
||||
|
||||
use crate::{NativeAgent, NativeAgentConnection, ThreadStore, templates::Templates};
|
||||
|
||||
|
|
@ -45,15 +43,12 @@ impl AgentServer for NativeAgentServer {
|
|||
log::debug!("NativeAgentServer::connect");
|
||||
let fs = self.fs.clone();
|
||||
let thread_store = self.thread_store.clone();
|
||||
let prompt_store = PromptStore::global(cx);
|
||||
cx.spawn(async move |cx| {
|
||||
log::debug!("Creating templates for native agent");
|
||||
let templates = Templates::new();
|
||||
let prompt_store = prompt_store.await.log_err();
|
||||
|
||||
log::debug!("Creating native agent entity");
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, templates, prompt_store, fs, cx));
|
||||
let agent = cx.update(|cx| NativeAgent::new(thread_store, templates, fs, cx));
|
||||
|
||||
// Create the connection wrapper
|
||||
let connection = NativeAgentConnection(agent);
|
||||
|
|
|
|||
|
|
@ -11,10 +11,15 @@ pub const AUTO_OUTLINE_SIZE: usize = 16384;
|
|||
|
||||
/// Result of getting buffer content, which can be either full content or an outline.
|
||||
pub struct BufferContent {
|
||||
/// The actual content (either full text or outline)
|
||||
/// The actual content (either full text, a symbol outline, or a
|
||||
/// truncated fallback — see `is_synthetic`).
|
||||
pub text: String,
|
||||
/// Whether this is an outline (true) or full content (false)
|
||||
pub is_outline: bool,
|
||||
/// `true` when `text` is not the file's full content — either a symbol
|
||||
/// outline or the truncated first-1KB fallback used when no outline is
|
||||
/// available. Callers that prefix line numbers to file content must
|
||||
/// skip prefixing in this case, because line numbers in `text` would
|
||||
/// not correspond to the file's real line numbers.
|
||||
pub is_synthetic: bool,
|
||||
}
|
||||
|
||||
/// Returns either the full content of a buffer or its outline, depending on size.
|
||||
|
|
@ -44,7 +49,10 @@ pub async fn get_buffer_content_or_outline(
|
|||
.collect::<Vec<_>>()
|
||||
});
|
||||
|
||||
// If no outline exists, fall back to first 1KB so the agent has some context
|
||||
// If no outline exists, fall back to first 1KB so the agent has some context.
|
||||
// This is reported as `is_synthetic: true` because the returned text is not
|
||||
// the file's full content — it has a synthetic header and is truncated — so
|
||||
// callers must not attach real-file line numbers to it.
|
||||
if outline_items.is_empty() {
|
||||
let text = buffer.read_with(cx, |buffer, _| {
|
||||
let snapshot = buffer.snapshot();
|
||||
|
|
@ -59,7 +67,7 @@ pub async fn get_buffer_content_or_outline(
|
|||
|
||||
return Ok(BufferContent {
|
||||
text,
|
||||
is_outline: false,
|
||||
is_synthetic: true,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -72,14 +80,14 @@ pub async fn get_buffer_content_or_outline(
|
|||
};
|
||||
Ok(BufferContent {
|
||||
text,
|
||||
is_outline: true,
|
||||
is_synthetic: true,
|
||||
})
|
||||
} else {
|
||||
// File is small enough, return full content
|
||||
let text = buffer.read_with(cx, |buffer, _| buffer.text());
|
||||
Ok(BufferContent {
|
||||
text,
|
||||
is_outline: false,
|
||||
is_synthetic: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -196,10 +204,13 @@ mod tests {
|
|||
"Result did not contain content subset"
|
||||
);
|
||||
|
||||
// Should be marked as not an outline (it's truncated content)
|
||||
// Should be marked synthetic: the returned text is not the file's full
|
||||
// content (it's a truncated first-1KB fallback with a synthetic header), so
|
||||
// callers must treat it the same as the symbol-outline case and not attach
|
||||
// real-file line numbers to it.
|
||||
assert!(
|
||||
!result.is_outline,
|
||||
"Large file without outline should not be marked as outline"
|
||||
result.is_synthetic,
|
||||
"Truncated fallback should be reported as synthetic so callers skip line numbering"
|
||||
);
|
||||
|
||||
// Should be reasonably sized (much smaller than original)
|
||||
|
|
|
|||
25
crates/agent/src/sandboxing.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
//! Agent-side glue for the [`sandbox`] crate.
|
||||
//!
|
||||
//! Centralizes the "should agent-run terminal commands be sandboxed for this
|
||||
//! process?" check so the system prompt, the terminal tool, and any other
|
||||
//! caller see the same answer (and so the `target_os` gate lives in one
|
||||
//! place instead of scattered across the agent crate).
|
||||
//!
|
||||
//! The current policy is: enabled iff we're on macOS *and* the user has the
|
||||
//! `sandboxing` feature flag turned on. There's deliberately no settings or
|
||||
//! env-var override yet — the flag is the only switch.
|
||||
//!
|
||||
//! On non-macOS hosts we don't have a sandbox integration today, so this
|
||||
//! returns `false` regardless of the flag.
|
||||
//!
|
||||
//! Naming note: this module is about agent terminal sandboxing specifically.
|
||||
//! Other agent operations (e.g. file edits) are gated separately.
|
||||
|
||||
use feature_flags::{FeatureFlagAppExt as _, SandboxingFeatureFlag};
|
||||
use gpui::App;
|
||||
|
||||
/// Whether agent-run terminal commands should be wrapped in an OS-level
|
||||
/// sandbox for this process. See module docs for the policy.
|
||||
pub(crate) fn sandboxing_enabled(cx: &App) -> bool {
|
||||
cfg!(target_os = "macos") && cx.has_flag::<SandboxingFeatureFlag>()
|
||||
}
|
||||
|
|
@ -43,6 +43,12 @@ pub struct SystemPromptTemplate<'a> {
|
|||
/// Contents of the user-global `~/.config/zed/AGENTS.md` file (or the
|
||||
/// platform equivalent), if present and non-empty.
|
||||
pub user_agents_md: Option<SharedString>,
|
||||
/// Whether agent-run terminal commands are wrapped in an OS-level
|
||||
/// sandbox for this conversation. When `true`, the rendered prompt
|
||||
/// describes the sandbox's read/write/network rules and the
|
||||
/// per-command flags the model can request to relax them. When
|
||||
/// `false`, the prompt omits the sandbox section entirely.
|
||||
pub sandboxing: bool,
|
||||
}
|
||||
|
||||
impl Template for SystemPromptTemplate<'_> {
|
||||
|
|
@ -83,10 +89,11 @@ mod tests {
|
|||
let project = prompt_store::ProjectContext::default();
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into(), "update_plan".into()],
|
||||
available_tools: vec!["echo".into(), "update_plan".into(), "update_title".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
|
@ -94,6 +101,7 @@ mod tests {
|
|||
assert!(rendered.contains("Today's Date: 2026-01-01"));
|
||||
assert!(rendered.contains("## Fixing Diagnostics"));
|
||||
assert!(rendered.contains("## Planning"));
|
||||
assert!(rendered.contains("## Session Title"));
|
||||
assert!(rendered.contains("test-model"));
|
||||
}
|
||||
|
||||
|
|
@ -111,13 +119,14 @@ mod tests {
|
|||
project_entry_id: 1,
|
||||
}),
|
||||
}];
|
||||
let project = ProjectContext::new(worktrees, Vec::new());
|
||||
let project = ProjectContext::new(worktrees);
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: Some("always be concise".into()),
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
|
@ -135,6 +144,78 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_omits_sandbox_section_when_sandboxing_disabled() {
|
||||
let project = prompt_store::ProjectContext::default();
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
assert!(!rendered.contains("## Terminal sandbox"));
|
||||
assert!(!rendered.contains("allow_network"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_renders_sandbox_section_with_worktrees_when_enabled() {
|
||||
use prompt_store::{ProjectContext, WorktreeContext};
|
||||
|
||||
let worktrees = vec![
|
||||
WorktreeContext {
|
||||
root_name: "alpha".to_string(),
|
||||
abs_path: std::path::Path::new("/tmp/alpha").into(),
|
||||
rules_file: None,
|
||||
},
|
||||
WorktreeContext {
|
||||
root_name: "beta".to_string(),
|
||||
abs_path: std::path::Path::new("/tmp/beta").into(),
|
||||
rules_file: None,
|
||||
},
|
||||
];
|
||||
let project = ProjectContext::new(worktrees);
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: true,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
||||
assert!(rendered.contains("## Terminal sandbox"));
|
||||
assert!(rendered.contains("`/tmp/alpha`"));
|
||||
assert!(rendered.contains("`/tmp/beta`"));
|
||||
assert!(rendered.contains("allow_network: true"));
|
||||
assert!(rendered.contains("allow_fs_write: true"));
|
||||
assert!(rendered.contains("unsandboxed: true"));
|
||||
assert!(rendered.contains("remain in effect for the entire duration"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_sandbox_section_handles_zero_worktrees() {
|
||||
let project = prompt_store::ProjectContext::default();
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: true,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
||||
assert!(rendered.contains("## Terminal sandbox"));
|
||||
assert!(rendered.contains("No project directories are currently writable"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_omits_user_agents_md_section_when_absent() {
|
||||
let project = prompt_store::ProjectContext::default();
|
||||
|
|
@ -144,9 +225,28 @@ mod tests {
|
|||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
assert!(!rendered.contains("### Personal `AGENTS.md`"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_prompt_does_not_render_legacy_zed_rules_section() {
|
||||
let project = prompt_store::ProjectContext::default();
|
||||
let template = SystemPromptTemplate {
|
||||
project: &project,
|
||||
available_tools: vec!["echo".into()],
|
||||
model_name: Some("test-model".to_string()),
|
||||
date: "2026-01-01".to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
||||
assert!(!rendered.contains("The user has specified the following rules"));
|
||||
assert!(!rendered.contains("Rules title:"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,6 +52,17 @@ Use a plan when:
|
|||
- The user asked you to do more than one thing in a single prompt.
|
||||
- You discover additional steps while working and intend to complete them before yielding to the user.
|
||||
|
||||
{{/if}}
|
||||
{{#if (contains available_tools 'update_title') }}
|
||||
## Session Title
|
||||
|
||||
- Use the `update_title` tool to set the title shown to the user for the current session.
|
||||
- You MUST set a title at least once, even for small tasks. Do it early in the conversation, after the first user message, before you start working. There is no title to begin with, so you are responsible for setting one.
|
||||
- Update the title again whenever the goal changes materially.
|
||||
- Titles are very important to communicate to the user what you are working on. A session should always have a title.
|
||||
- Keep titles concise and specific. Prefer a short noun phrase over a full sentence, and do not wrap the title in quotes.
|
||||
- Do not mention that you changed the title unless it is directly relevant to the user.
|
||||
|
||||
{{/if}}
|
||||
## Searching and Reading
|
||||
|
||||
|
|
@ -162,12 +173,11 @@ The current project contains the following root directories:
|
|||
You are powered by the model named {{model_name}}.
|
||||
|
||||
{{/if}}
|
||||
{{#if (or has_rules has_user_rules)}}
|
||||
{{#if has_rules}}
|
||||
## User's Custom Instructions
|
||||
|
||||
The following additional instructions are provided by the user and should be followed to the best of your ability{{#if (gt (len available_tools) 0)}} without interfering with the tool use guidelines{{/if}}.
|
||||
|
||||
{{#if has_rules}}
|
||||
There are project rules that apply to these root directories:
|
||||
{{#each worktrees}}
|
||||
{{#if rules_file}}
|
||||
|
|
@ -178,17 +188,3 @@ There are project rules that apply to these root directories:
|
|||
{{/if}}
|
||||
{{/each}}
|
||||
{{/if}}
|
||||
|
||||
{{#if has_user_rules}}
|
||||
The user has specified the following rules that should be applied:
|
||||
{{#each user_rules}}
|
||||
|
||||
{{#if title}}
|
||||
Rules title: {{title}}
|
||||
{{/if}}
|
||||
``````
|
||||
{{contents}}
|
||||
``````
|
||||
{{/each}}
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
|
|
|
|||
|
|
@ -23,15 +23,13 @@ graph TD
|
|||
A[Start] --> B[End]
|
||||
```
|
||||
|
||||
The renderer supports the following diagram types: flowchart, sequence, class, state, ER, gantt, pie, gitgraph, mindmap, timeline, quadrant chart, xy chart, and journey. Other diagram types will only show as code.
|
||||
|
||||
Mermaid diagrams are automatically themed to match the user's editor theme. Do not include `%%{init}%%` directives or define your own `classDef` styles.
|
||||
|
||||
Do *NOT* include inline HTML elements in mermaid diagrams, as they cannot be rendered. It is better to simply skip formatting (e.g. bold/italic/etc.).
|
||||
|
||||
When you need accent colors for emphasis (e.g. color-coding layers, categories, or states), use the pre-defined classes `accent0` through `accent7` with the `:::` syntax:
|
||||
|
||||
A:::accent0 --> B:::accent1 --> C:::accent2
|
||||
|
||||
These classes automatically match the user's theme. Do not hardcode hex color values unless an exact color match is specifically required. Note that the rendered view may be narrow, so try to prioritize generating taller diagrams over wider ones.
|
||||
Mermaid diagrams are automatically color-coded using the user's theme accent palette. Do not hardcode hex color values unless an exact color match is specifically required. Note that the rendered view may be narrow, so try to prioritize generating taller diagrams over wider ones.
|
||||
|
||||
{{#if (gt (len available_tools) 0)}}
|
||||
## Tool Use
|
||||
|
|
@ -74,6 +72,17 @@ Use a plan when:
|
|||
- The user asked you to do more than one thing in a single prompt.
|
||||
- You discover additional steps while working and intend to complete them before yielding to the user.
|
||||
|
||||
{{/if}}
|
||||
{{#if (contains available_tools 'update_title') }}
|
||||
## Session Title
|
||||
|
||||
- Use the `update_title` tool to set the title shown to the user for the current session.
|
||||
- You MUST set a title at least once, even for small tasks. Do it early in the conversation, after the first user message, before you start working. There is no title to begin with, so you are responsible for setting one.
|
||||
- Update the title again whenever the goal changes materially.
|
||||
- Titles are very important to communicate to the user what you are working on. A session should always have a title.
|
||||
- Keep titles concise and specific. Prefer a short noun phrase over a full sentence, and do not wrap the title in quotes.
|
||||
- Do not mention that you changed the title unless it is directly relevant to the user.
|
||||
|
||||
{{/if}}
|
||||
## Searching and Reading
|
||||
|
||||
|
|
@ -178,6 +187,24 @@ The current project contains the following root directories:
|
|||
- `{{abs_path}}`
|
||||
{{/each}}
|
||||
|
||||
{{#if sandboxing}}
|
||||
## Terminal sandbox
|
||||
|
||||
The `terminal` tool runs commands inside a sandbox with these permissions:
|
||||
|
||||
- Reads: any path on the filesystem is readable.
|
||||
- Writes: a per-thread temporary directory exposed via `$TMPDIR`, `$TMP`, and `$TEMP` is writable and persists across `terminal` calls in this conversation{{#if worktrees}}, along with these project directories:
|
||||
{{#each worktrees}}
|
||||
- `{{abs_path}}`
|
||||
{{/each}}
|
||||
Writes anywhere else on the filesystem are blocked.{{else}}. No project directories are currently writable.{{/if}}
|
||||
- Network: outbound network access is blocked.
|
||||
|
||||
You can request elevated permissions on individual `terminal` calls by setting `allow_network: true`, `allow_fs_write: true`, or `unsandboxed: true`. The user will be prompted to approve before the command runs.
|
||||
|
||||
These sandbox settings are guaranteed to remain in effect for the entire duration of this conversation. If they ever change, you will be told.
|
||||
|
||||
{{/if}}
|
||||
{{#if model_name}}
|
||||
## Model Information
|
||||
|
||||
|
|
@ -212,7 +239,7 @@ To use a Skill:
|
|||
4. If the Skill references additional files, use `read_file` to access them. Paths inside a Skill resolve relative to that Skill's directory (the parent of its `SKILL.md`).
|
||||
|
||||
{{/if}}
|
||||
{{#if (or user_agents_md has_rules has_user_rules)}}
|
||||
{{#if (or user_agents_md has_rules)}}
|
||||
## User's Custom Instructions
|
||||
|
||||
The following additional instructions are provided by the user and should be followed to the best of your ability{{#if (gt (len available_tools) 0)}} without interfering with the tool use guidelines{{/if}}.
|
||||
|
|
@ -243,16 +270,4 @@ There are project rules that apply to these root directories:
|
|||
{{/each}}
|
||||
{{/if}}
|
||||
|
||||
{{#if has_user_rules}}
|
||||
The user has specified the following rules that should be applied:
|
||||
{{#each user_rules}}
|
||||
|
||||
{{#if title}}
|
||||
Rules title: {{title}}
|
||||
{{/if}}
|
||||
``````
|
||||
{{contents}}
|
||||
``````
|
||||
{{/each}}
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
|
|
|
|||
|
|
@ -26,10 +26,10 @@ use gpui::{
|
|||
use indoc::indoc;
|
||||
use language_model::{
|
||||
CompletionIntent, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
|
||||
LanguageModelId, LanguageModelProviderId, LanguageModelProviderName, LanguageModelRegistry,
|
||||
LanguageModelRequest, LanguageModelRequestMessage, LanguageModelToolResult,
|
||||
LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, Role, StopReason,
|
||||
TokenUsage,
|
||||
LanguageModelId, LanguageModelImageExt, LanguageModelProviderId, LanguageModelProviderName,
|
||||
LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
|
||||
LanguageModelToolResult, LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent,
|
||||
Role, StopReason, TokenUsage,
|
||||
fake_provider::{FakeLanguageModel, FakeLanguageModelProvider},
|
||||
};
|
||||
use pretty_assertions::assert_eq;
|
||||
|
|
@ -200,8 +200,10 @@ impl crate::ThreadEnvironment for FakeThreadEnvironment {
|
|||
fn create_terminal(
|
||||
&self,
|
||||
_command: String,
|
||||
_extra_env: Vec<acp::EnvVariable>,
|
||||
_cwd: Option<std::path::PathBuf>,
|
||||
_output_byte_limit: Option<u64>,
|
||||
_sandbox_wrap: Option<acp_thread::SandboxWrap>,
|
||||
_cx: &mut AsyncApp,
|
||||
) -> Task<Result<Rc<dyn crate::TerminalHandle>>> {
|
||||
self.terminal_creations.fetch_add(1, Ordering::SeqCst);
|
||||
|
|
@ -242,8 +244,10 @@ impl crate::ThreadEnvironment for MultiTerminalEnvironment {
|
|||
fn create_terminal(
|
||||
&self,
|
||||
_command: String,
|
||||
_extra_env: Vec<acp::EnvVariable>,
|
||||
_cwd: Option<std::path::PathBuf>,
|
||||
_output_byte_limit: Option<u64>,
|
||||
_sandbox_wrap: Option<acp_thread::SandboxWrap>,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Task<Result<Rc<dyn crate::TerminalHandle>>> {
|
||||
let handle = Rc::new(cx.update(|cx| FakeTerminalHandle::new_never_exits(cx)));
|
||||
|
|
@ -320,6 +324,7 @@ async fn test_terminal_tool_timeout_kills_handle(cx: &mut TestAppContext) {
|
|||
command: "sleep 1000".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: Some(5),
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -387,6 +392,7 @@ async fn test_terminal_tool_without_timeout_does_not_kill_handle(cx: &mut TestAp
|
|||
command: "sleep 1000".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1656,6 +1662,7 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
|
|||
|
||||
let (tool_call_params, tool_call_response) = mcp_tool_calls.next().await.unwrap();
|
||||
assert_eq!(tool_call_params.name, "screenshot");
|
||||
let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
|
||||
tool_call_response
|
||||
.send(context_server::types::CallToolResponse {
|
||||
content: vec![
|
||||
|
|
@ -1663,7 +1670,7 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
|
|||
text: "Some text".into(),
|
||||
},
|
||||
context_server::types::ToolResponseContent::Image {
|
||||
data: "aGVsbG8=".into(),
|
||||
data: image_data.into(),
|
||||
mime_type: "image/png".into(),
|
||||
},
|
||||
context_server::types::ToolResponseContent::Text {
|
||||
|
|
@ -1691,13 +1698,25 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
|
|||
})
|
||||
.expect("expected a tool result");
|
||||
assert_eq!(tool_result.tool_use_id, "tool_1".into());
|
||||
assert_eq!(tool_result.content.len(), 2);
|
||||
assert_eq!(tool_result.content.len(), 3);
|
||||
assert_eq!(
|
||||
tool_result.content[0],
|
||||
language_model::LanguageModelToolResultContent::Text(Arc::from("Some text"))
|
||||
);
|
||||
let expected_image =
|
||||
language_model::LanguageModelImage::from_base64_image(image_data, "image/png")
|
||||
.expect("image conversion should not error")
|
||||
.expect("image conversion should succeed");
|
||||
assert_eq!(
|
||||
tool_result.content[0],
|
||||
language_model::LanguageModelToolResultContent::Text(Arc::from("Some text"))
|
||||
);
|
||||
assert_eq!(
|
||||
tool_result.content[1],
|
||||
language_model::LanguageModelToolResultContent::Image(expected_image)
|
||||
);
|
||||
assert_eq!(
|
||||
tool_result.content[2],
|
||||
language_model::LanguageModelToolResultContent::Text(Arc::from("Some more text"))
|
||||
);
|
||||
fake_model.end_last_completion_stream();
|
||||
|
|
@ -3507,8 +3526,8 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
|
|||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
|
||||
// Create agent and connection
|
||||
let agent = cx
|
||||
.update(|cx| NativeAgent::new(thread_store, templates.clone(), None, fake_fs.clone(), cx));
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store, templates.clone(), fake_fs.clone(), cx));
|
||||
let connection = NativeAgentConnection(agent.clone());
|
||||
|
||||
// Create a thread using new_thread
|
||||
|
|
@ -3794,6 +3813,155 @@ async fn test_update_plan_tool_updates_thread_events(cx: &mut TestAppContext) {
|
|||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_tool_sets_thread_title(cx: &mut TestAppContext) {
|
||||
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
|
||||
let fake_model = model.as_fake();
|
||||
let summary_model = Arc::new(FakeLanguageModel::default());
|
||||
|
||||
cx.update(|cx| {
|
||||
cx.update_flags(true, vec!["update-title-tool".to_string()]);
|
||||
});
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
|
||||
thread.set_summarization_model(Some(summary_model.clone()), cx);
|
||||
});
|
||||
|
||||
let mut events = thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
|
||||
})
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
|
||||
let input = json!({
|
||||
"title": "Session title tool"
|
||||
});
|
||||
fake_model.send_last_completion_stream_event(LanguageModelCompletionEvent::ToolUse(
|
||||
LanguageModelToolUse {
|
||||
id: "title_1".into(),
|
||||
name: UpdateTitleTool::NAME.into(),
|
||||
raw_input: input.to_string(),
|
||||
input,
|
||||
is_input_complete: true,
|
||||
thought_signature: None,
|
||||
},
|
||||
));
|
||||
fake_model.end_last_completion_stream();
|
||||
cx.run_until_parked();
|
||||
|
||||
let tool_call = expect_tool_call(&mut events).await;
|
||||
assert_eq!(
|
||||
tool_call,
|
||||
acp::ToolCall::new("title_1", "Update title: Session title tool")
|
||||
.kind(acp::ToolKind::Think)
|
||||
.raw_input(json!({
|
||||
"title": "Session title tool"
|
||||
}))
|
||||
.meta(acp::Meta::from_iter([(
|
||||
"tool_name".into(),
|
||||
"update_title".into()
|
||||
)]))
|
||||
);
|
||||
|
||||
let update = expect_tool_call_update_fields(&mut events).await;
|
||||
assert_eq!(
|
||||
update,
|
||||
acp::ToolCallUpdate::new(
|
||||
"title_1",
|
||||
acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress)
|
||||
)
|
||||
);
|
||||
|
||||
let update = expect_tool_call_update_fields(&mut events).await;
|
||||
assert_eq!(
|
||||
update,
|
||||
acp::ToolCallUpdate::new(
|
||||
"title_1",
|
||||
acp::ToolCallUpdateFields::new()
|
||||
.status(acp::ToolCallStatus::Completed)
|
||||
.raw_output("Session title updated")
|
||||
)
|
||||
);
|
||||
|
||||
thread.read_with(cx, |thread, _| {
|
||||
assert_eq!(thread.title(), Some("Session title tool".into()));
|
||||
});
|
||||
assert_eq!(summary_model.pending_completions(), Vec::new());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_availability_suppresses_summary_title_generation(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
|
||||
let fake_model = model.as_fake();
|
||||
let summary_model = Arc::new(FakeLanguageModel::default());
|
||||
|
||||
cx.update(|cx| {
|
||||
cx.update_flags(true, vec!["update-title-tool".to_string()]);
|
||||
});
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
|
||||
thread.set_summarization_model(Some(summary_model.clone()), cx);
|
||||
});
|
||||
|
||||
let send = thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
|
||||
})
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
|
||||
fake_model.send_last_completion_stream_text_chunk("Done");
|
||||
fake_model.end_last_completion_stream();
|
||||
send.collect::<Vec<_>>().await;
|
||||
cx.run_until_parked();
|
||||
|
||||
thread.read_with(cx, |thread, _| {
|
||||
assert_eq!(thread.title(), None);
|
||||
});
|
||||
assert_eq!(summary_model.pending_completions(), Vec::new());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_flag_without_available_tool_falls_back_to_summary_title_generation(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
|
||||
let fake_model = model.as_fake();
|
||||
let summary_model = Arc::new(FakeLanguageModel::default());
|
||||
|
||||
cx.update(|cx| {
|
||||
cx.update_flags(true, vec!["update-title-tool".to_string()]);
|
||||
});
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.set_summarization_model(Some(summary_model.clone()), cx);
|
||||
});
|
||||
|
||||
let send = thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.send(UserMessageId::new(), ["Explore title tooling"], cx)
|
||||
})
|
||||
.unwrap();
|
||||
cx.run_until_parked();
|
||||
|
||||
fake_model.send_last_completion_stream_text_chunk("Done");
|
||||
fake_model.end_last_completion_stream();
|
||||
cx.run_until_parked();
|
||||
|
||||
assert_eq!(summary_model.pending_completions().len(), 1);
|
||||
|
||||
summary_model.send_last_completion_stream_text_chunk("Fallback title");
|
||||
summary_model.end_last_completion_stream();
|
||||
send.collect::<Vec<_>>().await;
|
||||
cx.run_until_parked();
|
||||
|
||||
thread.read_with(cx, |thread, _| {
|
||||
assert_eq!(thread.title(), Some("Fallback title".into()));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_send_no_retry_on_success(cx: &mut TestAppContext) {
|
||||
let ThreadTest { thread, model, .. } = setup(cx, TestModel::Fake).await;
|
||||
|
|
@ -3971,8 +4139,8 @@ async fn test_send_retry_finishes_tool_calls_on_error(cx: &mut TestAppContext) {
|
|||
events.collect::<Vec<_>>().await;
|
||||
thread.read_with(cx, |thread, _cx| {
|
||||
assert_eq!(
|
||||
thread.last_received_or_pending_message(),
|
||||
Some(Message::Agent(AgentMessage {
|
||||
thread.last_received_or_pending_message().as_deref(),
|
||||
Some(&Message::Agent(AgentMessage {
|
||||
content: vec![AgentMessageContent::Text("Done".into())],
|
||||
tool_results: IndexMap::default(),
|
||||
reasoning_details: None,
|
||||
|
|
@ -4307,6 +4475,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
|
|||
StreamingFailingEchoTool::NAME: true,
|
||||
TerminalTool::NAME: true,
|
||||
UpdatePlanTool::NAME: true,
|
||||
UpdateTitleTool::NAME: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -4389,7 +4558,7 @@ async fn setup(cx: &mut TestAppContext, model: TestModel) -> ThreadTest {
|
|||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[ctor::ctor]
|
||||
#[ctor::ctor(unsafe)]
|
||||
fn init_logger() {
|
||||
if std::env::var("RUST_LOG").is_ok() {
|
||||
env_logger::init();
|
||||
|
|
@ -4729,6 +4898,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
|
|||
command: "rm -rf /".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -4781,6 +4951,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
|
|||
command: "echo hello".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -4839,6 +5010,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
|
|||
command: "sudo rm file".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -4886,6 +5058,7 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) {
|
|||
command: "echo hello".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -4928,9 +5101,8 @@ async fn test_subagent_tool_call_end_to_end(cx: &mut TestAppContext) {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5063,9 +5235,8 @@ async fn test_subagent_tool_output_does_not_include_thinking(cx: &mut TestAppCon
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5211,9 +5382,8 @@ async fn test_subagent_tool_call_cancellation_during_task_prompt(cx: &mut TestAp
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5341,9 +5511,8 @@ async fn test_subagent_tool_resume_session(cx: &mut TestAppContext) {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -5874,9 +6043,8 @@ async fn test_subagent_context_window_warning(cx: &mut TestAppContext) {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -6000,9 +6168,8 @@ async fn test_subagent_no_context_window_warning_when_already_at_warning(cx: &mu
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
@ -6174,9 +6341,8 @@ async fn test_subagent_error_propagation(cx: &mut TestAppContext) {
|
|||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/a").as_ref()], cx).await;
|
||||
let thread_store = cx.new(|cx| ThreadStore::new(cx));
|
||||
let agent = cx.update(|cx| {
|
||||
NativeAgent::new(thread_store.clone(), Templates::new(), None, fs.clone(), cx)
|
||||
});
|
||||
let agent =
|
||||
cx.update(|cx| NativeAgent::new(thread_store.clone(), Templates::new(), fs.clone(), cx));
|
||||
let connection = Rc::new(NativeAgentConnection(agent.clone()));
|
||||
|
||||
let acp_thread = cx
|
||||
|
|
|
|||
|
|
@ -4,12 +4,14 @@ use crate::{
|
|||
FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool,
|
||||
ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, SpawnAgentTool,
|
||||
SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision,
|
||||
UpdatePlanTool, UserAgentsMd, WebSearchTool, WriteFileTool, decide_permission_from_settings,
|
||||
UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool, decide_permission_from_settings,
|
||||
};
|
||||
use acp_thread::{MentionUri, UserMessageId};
|
||||
use action_log::ActionLog;
|
||||
use agent_settings::UserAgentsMd;
|
||||
use feature_flags::{
|
||||
FeatureFlagAppExt as _, LspToolFeatureFlag, RenameToolFeatureFlag, UpdatePlanToolFeatureFlag,
|
||||
UpdateTitleToolFeatureFlag,
|
||||
};
|
||||
|
||||
use agent_client_protocol::schema as acp;
|
||||
|
|
@ -49,16 +51,16 @@ use serde::{Deserialize, Serialize};
|
|||
use settings::{
|
||||
LanguageModelSelection, Settings, SettingsStore, ToolPermissionMode, update_settings_file,
|
||||
};
|
||||
use std::fmt::Write;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
marker::PhantomData,
|
||||
ops::RangeInclusive,
|
||||
path::Path,
|
||||
path::{Path, PathBuf},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use std::{fmt::Write, path::PathBuf};
|
||||
use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
|
@ -121,7 +123,7 @@ enum RetryStrategy {
|
|||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Message {
|
||||
User(UserMessage),
|
||||
Agent(AgentMessage),
|
||||
|
|
@ -174,13 +176,16 @@ impl Message {
|
|||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct UserMessage {
|
||||
pub id: UserMessageId,
|
||||
pub content: Vec<UserMessageContent>,
|
||||
pub content: Arc<[UserMessageContent]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum UserMessageContent {
|
||||
Text(String),
|
||||
Mention { uri: MentionUri, content: String },
|
||||
Mention {
|
||||
uri: MentionUri,
|
||||
content: SharedString,
|
||||
},
|
||||
Image(LanguageModelImage),
|
||||
}
|
||||
|
||||
|
|
@ -188,7 +193,7 @@ impl UserMessage {
|
|||
pub fn to_markdown(&self) -> String {
|
||||
let mut markdown = String::new();
|
||||
|
||||
for content in &self.content {
|
||||
for content in &*self.content {
|
||||
match content {
|
||||
UserMessageContent::Text(text) => {
|
||||
markdown.push_str(text);
|
||||
|
|
@ -248,7 +253,7 @@ impl UserMessage {
|
|||
let mut merge_conflict_context = MERGE_CONFLICT_TAG.to_string();
|
||||
let mut skills_context = OPEN_SKILLS_TAG.to_string();
|
||||
|
||||
for chunk in &self.content {
|
||||
for chunk in &*self.content {
|
||||
let chunk = match chunk {
|
||||
UserMessageContent::Text(text) => {
|
||||
language_model::MessageContent::Text(text.clone())
|
||||
|
|
@ -264,7 +269,7 @@ impl UserMessage {
|
|||
"\n{}",
|
||||
MarkdownCodeBlock {
|
||||
tag: &codeblock_tag(abs_path, None),
|
||||
text: &content.to_string(),
|
||||
text: content,
|
||||
}
|
||||
)
|
||||
.ok();
|
||||
|
|
@ -311,17 +316,6 @@ impl UserMessage {
|
|||
MentionUri::Thread { .. } => {
|
||||
write!(&mut thread_context, "\n{}\n", content).ok();
|
||||
}
|
||||
MentionUri::Rule { .. } => {
|
||||
write!(
|
||||
&mut rules_context,
|
||||
"\n{}",
|
||||
MarkdownCodeBlock {
|
||||
tag: "",
|
||||
text: content
|
||||
}
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
MentionUri::Fetch { url } => {
|
||||
write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
|
||||
}
|
||||
|
|
@ -364,11 +358,7 @@ impl UserMessage {
|
|||
.ok();
|
||||
}
|
||||
MentionUri::Skill { name, source, .. } => {
|
||||
let label = if source.is_empty() {
|
||||
format!("{} (global)", name)
|
||||
} else {
|
||||
format!("{} ({})", name, source)
|
||||
};
|
||||
let label = format!("{} ({})", name, source);
|
||||
write!(&mut skills_context, "\nSkill: {}\n{}\n", label, content).ok();
|
||||
}
|
||||
}
|
||||
|
|
@ -629,9 +619,9 @@ impl AgentMessage {
|
|||
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AgentMessage {
|
||||
pub content: Vec<AgentMessageContent>,
|
||||
pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
|
||||
pub reasoning_details: Option<serde_json::Value>,
|
||||
pub(crate) content: Vec<AgentMessageContent>,
|
||||
pub(crate) tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
|
||||
pub(crate) reasoning_details: Option<Arc<serde_json::Value>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -667,8 +657,10 @@ pub trait ThreadEnvironment {
|
|||
fn create_terminal(
|
||||
&self,
|
||||
command: String,
|
||||
extra_env: Vec<acp::EnvVariable>,
|
||||
cwd: Option<PathBuf>,
|
||||
output_byte_limit: Option<u64>,
|
||||
sandbox_wrap: Option<acp_thread::SandboxWrap>,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Task<Result<Rc<dyn TerminalHandle>>>;
|
||||
|
||||
|
|
@ -965,7 +957,7 @@ pub struct Thread {
|
|||
title_generation_failed: bool,
|
||||
pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
|
||||
summary: Option<SharedString>,
|
||||
messages: Vec<Message>,
|
||||
messages: Vec<Arc<Message>>,
|
||||
user_store: Entity<UserStore>,
|
||||
/// Holds the task that handles agent interaction until the end of the turn.
|
||||
/// Survives across multiple requests as the model performs tool calls and
|
||||
|
|
@ -1004,6 +996,7 @@ pub struct Thread {
|
|||
/// Weak references to running subagent threads for cancellation propagation
|
||||
running_subagents: Vec<WeakEntity<Thread>>,
|
||||
inherits_parent_model_settings: bool,
|
||||
sandboxed_terminal_temp_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Thread {
|
||||
|
|
@ -1130,6 +1123,7 @@ impl Thread {
|
|||
ui_scroll_position: None,
|
||||
running_subagents: Vec::new(),
|
||||
inherits_parent_model_settings: true,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1173,6 +1167,30 @@ impl Thread {
|
|||
&self.id
|
||||
}
|
||||
|
||||
pub(crate) fn sandboxed_terminal_temp_dir(
|
||||
&mut self,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Result<PathBuf> {
|
||||
if let Some(temp_dir) = &self.sandboxed_terminal_temp_dir {
|
||||
std::fs::create_dir_all(temp_dir).with_context(|| {
|
||||
format!(
|
||||
"failed to recreate sandboxed terminal temp directory {}",
|
||||
temp_dir.display()
|
||||
)
|
||||
})?;
|
||||
return Ok(temp_dir.clone());
|
||||
}
|
||||
|
||||
let temp_dir = tempfile::Builder::new()
|
||||
.prefix("zed-agent-terminal-")
|
||||
.tempdir()
|
||||
.context("failed to create sandboxed terminal temp directory")?;
|
||||
let temp_dir = temp_dir.keep();
|
||||
self.sandboxed_terminal_temp_dir = Some(temp_dir.clone());
|
||||
cx.notify();
|
||||
Ok(temp_dir)
|
||||
}
|
||||
|
||||
/// Returns true if this thread was imported from a shared thread.
|
||||
pub fn is_imported(&self) -> bool {
|
||||
self.imported
|
||||
|
|
@ -1185,7 +1203,7 @@ impl Thread {
|
|||
let (tx, rx) = mpsc::unbounded();
|
||||
let stream = ThreadEventStream(tx);
|
||||
for message in &self.messages {
|
||||
match message {
|
||||
match &**message {
|
||||
Message::User(user_message) => stream.send_user_message(user_message),
|
||||
Message::Agent(assistant_message) => {
|
||||
for content in &assistant_message.content {
|
||||
|
|
@ -1219,10 +1237,10 @@ impl Thread {
|
|||
stream: &ThreadEventStream,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
// Extract saved output and status first, so they're available even if tool is not found
|
||||
let output = tool_result
|
||||
.as_ref()
|
||||
.and_then(|result| result.output.clone());
|
||||
let replay_content = tool_result.and_then(Self::tool_result_content_for_replay);
|
||||
let status = tool_result
|
||||
.as_ref()
|
||||
.map_or(acp::ToolCallStatus::Failed, |result| {
|
||||
|
|
@ -1251,21 +1269,25 @@ impl Thread {
|
|||
// but still display the saved result if available.
|
||||
// We need to send both ToolCall and ToolCallUpdate events because the UI
|
||||
// only converts raw_output to displayable content in update_fields, not from_acp.
|
||||
let title = Self::title_for_replayed_tool_use(tool_use);
|
||||
stream
|
||||
.0
|
||||
.unbounded_send(Ok(ThreadEvent::ToolCall(
|
||||
acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
|
||||
acp::ToolCall::new(tool_use.id.to_string(), title.clone())
|
||||
.status(status)
|
||||
.raw_input(tool_use.input.clone()),
|
||||
)))
|
||||
.ok();
|
||||
stream.update_tool_call_fields(
|
||||
&tool_use.id,
|
||||
acp::ToolCallUpdateFields::new()
|
||||
.status(status)
|
||||
.raw_output(output),
|
||||
None,
|
||||
);
|
||||
let mut fields = acp::ToolCallUpdateFields::new()
|
||||
.status(status)
|
||||
.raw_output(output);
|
||||
if tool_use.name.as_ref() == UpdateTitleTool::NAME {
|
||||
fields = fields.title(title);
|
||||
}
|
||||
if let Some(content) = replay_content {
|
||||
fields = fields.content(content);
|
||||
}
|
||||
stream.update_tool_call_fields(&tool_use.id, fields, None);
|
||||
return;
|
||||
};
|
||||
|
||||
|
|
@ -1279,6 +1301,14 @@ impl Thread {
|
|||
tool_use.input.clone(),
|
||||
);
|
||||
|
||||
if let Some(content) = replay_content {
|
||||
stream.update_tool_call_fields(
|
||||
&tool_use.id,
|
||||
acp::ToolCallUpdateFields::new().content(content),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(output) = output.clone() {
|
||||
// For replay, we use a dummy cancellation receiver since the tool already completed
|
||||
let (_cancellation_tx, cancellation_rx) = watch::channel(false);
|
||||
|
|
@ -1301,6 +1331,55 @@ impl Thread {
|
|||
);
|
||||
}
|
||||
|
||||
fn title_for_replayed_tool_use(tool_use: &LanguageModelToolUse) -> String {
|
||||
if tool_use.name.as_ref() == UpdateTitleTool::NAME {
|
||||
let input = serde_json::from_value(tool_use.input.clone())
|
||||
.map_err(|_| serde_json::Value::String(tool_use.raw_input.clone()));
|
||||
UpdateTitleTool::title_for_input(input).to_string()
|
||||
} else {
|
||||
tool_use.name.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn tool_result_content_for_replay(
|
||||
tool_result: &LanguageModelToolResult,
|
||||
) -> Option<Vec<acp::ToolCallContent>> {
|
||||
let has_image = tool_result
|
||||
.content
|
||||
.iter()
|
||||
.any(|part| matches!(part, LanguageModelToolResultContent::Image(_)));
|
||||
if !has_image && tool_result.output.is_some() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let content = tool_result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|part| match part {
|
||||
LanguageModelToolResultContent::Text(text) => {
|
||||
if text.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(acp::ToolCallContent::Content(acp::Content::new(
|
||||
acp::ContentBlock::Text(acp::TextContent::new(text.to_string())),
|
||||
)))
|
||||
}
|
||||
}
|
||||
LanguageModelToolResultContent::Image(image) => Some(
|
||||
acp::ToolCallContent::Content(acp::Content::new(acp::ContentBlock::Image(
|
||||
acp::ImageContent::new(image.source.clone(), "image/png"),
|
||||
))),
|
||||
),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if content.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(content)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_db(
|
||||
id: acp::SessionId,
|
||||
db_thread: DbThread,
|
||||
|
|
@ -1387,6 +1466,7 @@ impl Thread {
|
|||
}),
|
||||
running_subagents: Vec::new(),
|
||||
inherits_parent_model_settings: true,
|
||||
sandboxed_terminal_temp_dir: db_thread.sandboxed_terminal_temp_dir,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1417,6 +1497,7 @@ impl Thread {
|
|||
offset_in_item: lo.offset_in_item.as_f32(),
|
||||
}
|
||||
}),
|
||||
sandboxed_terminal_temp_dir: self.sandboxed_terminal_temp_dir.clone(),
|
||||
};
|
||||
|
||||
cx.background_spawn(async move {
|
||||
|
|
@ -1580,13 +1661,13 @@ impl Thread {
|
|||
}
|
||||
|
||||
pub fn last_message(&self) -> Option<&Message> {
|
||||
self.messages.last()
|
||||
self.messages.last().map(std::ops::Deref::deref)
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn last_received_or_pending_message(&self) -> Option<Message> {
|
||||
pub fn last_received_or_pending_message(&self) -> Option<Arc<Message>> {
|
||||
if let Some(message) = self.pending_message.clone() {
|
||||
Some(Message::Agent(message))
|
||||
Some(Arc::new(Message::Agent(message)))
|
||||
} else {
|
||||
self.messages.last().cloned()
|
||||
}
|
||||
|
|
@ -1627,6 +1708,9 @@ impl Thread {
|
|||
if cx.has_flag::<UpdatePlanToolFeatureFlag>() {
|
||||
self.add_tool(UpdatePlanTool);
|
||||
}
|
||||
if cx.has_flag::<UpdateTitleToolFeatureFlag>() {
|
||||
self.add_tool(UpdateTitleTool::new(cx.weak_entity()));
|
||||
}
|
||||
self.add_tool(ReadFileTool::new(
|
||||
self.project.clone(),
|
||||
self.action_log.clone(),
|
||||
|
|
@ -1740,13 +1824,13 @@ impl Thread {
|
|||
// and we don't want that content to be added after we truncate
|
||||
self.pending_message.take();
|
||||
let Some(position) = self.messages.iter().position(
|
||||
|msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
|
||||
|msg| matches!(&**msg, Message::User(UserMessage { id, .. }) if id == &message_id),
|
||||
) else {
|
||||
return Err(anyhow!("Message not found"));
|
||||
};
|
||||
|
||||
for message in self.messages.drain(position..) {
|
||||
match message {
|
||||
match &*message {
|
||||
Message::User(message) => {
|
||||
self.request_token_usage.remove(&message.id);
|
||||
}
|
||||
|
|
@ -1788,7 +1872,7 @@ impl Thread {
|
|||
let mut previous_user_message_id: Option<&UserMessageId> = None;
|
||||
|
||||
for message in &self.messages {
|
||||
if let Message::User(user_msg) = message {
|
||||
if let Message::User(user_msg) = &**message {
|
||||
if &user_msg.id == target_id {
|
||||
let prev_id = previous_user_message_id?;
|
||||
let usage = self.request_token_usage.get(prev_id)?;
|
||||
|
|
@ -1833,7 +1917,7 @@ impl Thread {
|
|||
&mut self,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
|
||||
self.messages.push(Message::Resume);
|
||||
self.messages.push(Arc::new(Message::Resume));
|
||||
cx.notify();
|
||||
|
||||
log::debug!("Total messages in thread: {}", self.messages.len());
|
||||
|
|
@ -1852,11 +1936,11 @@ impl Thread {
|
|||
where
|
||||
T: Into<UserMessageContent>,
|
||||
{
|
||||
let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
|
||||
let content = content.into_iter().map(Into::into).collect::<Arc<_>>();
|
||||
log::debug!("Thread::send content: {:?}", content);
|
||||
|
||||
self.messages
|
||||
.push(Message::User(UserMessage { id, content }));
|
||||
.push(Arc::new(Message::User(UserMessage { id, content })));
|
||||
cx.notify();
|
||||
|
||||
self.send_existing(cx)
|
||||
|
|
@ -1887,9 +1971,9 @@ impl Thread {
|
|||
let content = blocks
|
||||
.into_iter()
|
||||
.map(|block| UserMessageContent::from_content_block(block, path_style))
|
||||
.collect::<Vec<_>>();
|
||||
.collect::<Arc<_>>();
|
||||
self.messages
|
||||
.push(Message::User(UserMessage { id, content }));
|
||||
.push(Arc::new(Message::User(UserMessage { id, content })));
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
|
|
@ -1907,10 +1991,10 @@ impl Thread {
|
|||
_ => "[unknown]".to_string(),
|
||||
};
|
||||
|
||||
self.messages.push(Message::Agent(AgentMessage {
|
||||
self.messages.push(Arc::new(Message::Agent(AgentMessage {
|
||||
content: vec![AgentMessageContent::Text(text)],
|
||||
..Default::default()
|
||||
}));
|
||||
})));
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
|
|
@ -2140,7 +2224,7 @@ impl Thread {
|
|||
|
||||
this.update(cx, |this, cx| {
|
||||
this.flush_pending_message(cx);
|
||||
if this.title.is_none() && this.pending_title_generation.is_none() {
|
||||
if this.title.is_none() {
|
||||
this.generate_title(cx);
|
||||
}
|
||||
})?;
|
||||
|
|
@ -2168,10 +2252,10 @@ impl Thread {
|
|||
}
|
||||
}
|
||||
this.update(cx, |this, _cx| {
|
||||
if let Some(Message::Agent(message)) = this.messages.last() {
|
||||
if let Some(Message::Agent(message)) = this.last_message() {
|
||||
if message.tool_results.is_empty() {
|
||||
intent = CompletionIntent::UserPrompt;
|
||||
this.messages.push(Message::Resume);
|
||||
this.messages.push(Arc::new(Message::Resume));
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
|
@ -2294,12 +2378,12 @@ impl Thread {
|
|||
let last_message = self.pending_message();
|
||||
// Store the last non-empty reasoning_details (overwrites earlier ones)
|
||||
// This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
|
||||
if let serde_json::Value::Array(ref arr) = details {
|
||||
if let serde_json::Value::Array(arr) = &details {
|
||||
if !arr.is_empty() {
|
||||
last_message.reasoning_details = Some(details);
|
||||
last_message.reasoning_details = Some(Arc::new(details));
|
||||
}
|
||||
} else {
|
||||
last_message.reasoning_details = Some(details);
|
||||
last_message.reasoning_details = Some(Arc::new(details));
|
||||
}
|
||||
}
|
||||
ToolUse(tool_use) => {
|
||||
|
|
@ -2669,6 +2753,20 @@ impl Thread {
|
|||
self.title_generation_failed
|
||||
}
|
||||
|
||||
pub fn can_generate_title(&self, cx: &App) -> bool {
|
||||
self.pending_title_generation.is_none()
|
||||
&& self.summarization_model.is_some()
|
||||
&& !self.update_title_tool_available(cx)
|
||||
}
|
||||
|
||||
fn update_title_tool_available(&self, cx: &App) -> bool {
|
||||
if let Some(running_turn) = self.running_turn.as_ref() {
|
||||
running_turn.tools.contains_key(UpdateTitleTool::NAME)
|
||||
} else {
|
||||
self.enabled_tools(cx).contains_key(UpdateTitleTool::NAME)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
|
||||
if let Some(summary) = self.summary.as_ref() {
|
||||
return Task::ready(Some(summary.clone())).shared();
|
||||
|
|
@ -2730,6 +2828,10 @@ impl Thread {
|
|||
}
|
||||
|
||||
pub fn generate_title(&mut self, cx: &mut Context<Self>) {
|
||||
if !self.can_generate_title(cx) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.title_generation_failed = false;
|
||||
let Some(model) = self.summarization_model.clone() else {
|
||||
return;
|
||||
|
|
@ -2815,7 +2917,7 @@ impl Thread {
|
|||
self.messages
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|message| match message {
|
||||
.find_map(|message| match &**message {
|
||||
Message::User(user_message) => Some(user_message),
|
||||
Message::Agent(_) => None,
|
||||
Message::Resume => None,
|
||||
|
|
@ -2856,7 +2958,7 @@ impl Thread {
|
|||
}
|
||||
}
|
||||
|
||||
self.messages.push(Message::Agent(message));
|
||||
self.messages.push(Arc::new(Message::Agent(message)));
|
||||
self.updated_at = Utc::now();
|
||||
self.clear_summary();
|
||||
cx.notify()
|
||||
|
|
@ -3088,6 +3190,7 @@ impl Thread {
|
|||
model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
|
||||
date: Local::now().format("%Y-%m-%d").to_string(),
|
||||
user_agents_md,
|
||||
sandboxing: crate::sandboxing::sandboxing_enabled(cx),
|
||||
}
|
||||
.render(&self.templates)
|
||||
.context("failed to build system prompt")
|
||||
|
|
@ -3119,7 +3222,7 @@ impl Thread {
|
|||
if ix > 0 {
|
||||
markdown.push('\n');
|
||||
}
|
||||
match message {
|
||||
match &**message {
|
||||
Message::User(_) => markdown.push_str("## User\n\n"),
|
||||
Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
|
||||
Message::Resume => {}
|
||||
|
|
@ -4331,7 +4434,7 @@ impl UserMessageContent {
|
|||
match MentionUri::parse(&resource_link.uri, path_style) {
|
||||
Ok(uri) => Self::Mention {
|
||||
uri,
|
||||
content: String::new(),
|
||||
content: SharedString::default(),
|
||||
},
|
||||
Err(err) => {
|
||||
log::error!("Failed to parse mention link: {}", err);
|
||||
|
|
@ -4344,7 +4447,7 @@ impl UserMessageContent {
|
|||
match MentionUri::parse(&resource.uri, path_style) {
|
||||
Ok(uri) => Self::Mention {
|
||||
uri,
|
||||
content: resource.text,
|
||||
content: resource.text.into(),
|
||||
},
|
||||
Err(err) => {
|
||||
log::error!("Failed to parse mention link: {}", err);
|
||||
|
|
@ -4394,7 +4497,6 @@ impl From<UserMessageContent> for acp::ContentBlock {
|
|||
fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
|
||||
LanguageModelImage {
|
||||
source: image_content.data.into(),
|
||||
size: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -4459,6 +4561,259 @@ mod tests {
|
|||
})
|
||||
}
|
||||
|
||||
struct ReplayImageTool;
|
||||
|
||||
impl AgentTool for ReplayImageTool {
|
||||
type Input = ();
|
||||
type Output = String;
|
||||
|
||||
const NAME: &'static str = "registered_image_tool";
|
||||
|
||||
fn kind() -> acp::ToolKind {
|
||||
acp::ToolKind::Other
|
||||
}
|
||||
|
||||
fn initial_title(
|
||||
&self,
|
||||
_input: Result<Self::Input, serde_json::Value>,
|
||||
_cx: &mut App,
|
||||
) -> SharedString {
|
||||
"Registered Image Tool".into()
|
||||
}
|
||||
|
||||
fn run(
|
||||
self: Arc<Self>,
|
||||
_input: ToolInput<Self::Input>,
|
||||
_event_stream: ToolCallEventStream,
|
||||
_cx: &mut App,
|
||||
) -> Task<Result<Self::Output, Self::Output>> {
|
||||
Task::ready(Ok(String::new()))
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_replay_tool_call_replays_image_content(cx: &mut TestAppContext) {
|
||||
let (thread, _event_stream) = setup_thread_for_test(cx).await;
|
||||
|
||||
let registered_tool_use_id = LanguageModelToolUseId::from("registered_tool_id");
|
||||
let missing_tool_use_id = LanguageModelToolUseId::from("missing_tool_id");
|
||||
let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
|
||||
let image = LanguageModelImage {
|
||||
source: image_data.into(),
|
||||
};
|
||||
|
||||
let mut replay_events = cx.update(|cx| {
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.add_tool(ReplayImageTool);
|
||||
|
||||
let registered_tool_use = LanguageModelToolUse {
|
||||
id: registered_tool_use_id.clone(),
|
||||
name: ReplayImageTool::NAME.into(),
|
||||
raw_input: "null".to_string(),
|
||||
input: json!(null),
|
||||
is_input_complete: true,
|
||||
thought_signature: None,
|
||||
};
|
||||
let missing_tool_use = LanguageModelToolUse {
|
||||
id: missing_tool_use_id.clone(),
|
||||
name: "missing_image_tool".into(),
|
||||
raw_input: "{}".to_string(),
|
||||
input: json!({}),
|
||||
is_input_complete: true,
|
||||
thought_signature: None,
|
||||
};
|
||||
|
||||
let mut tool_results = IndexMap::default();
|
||||
tool_results.insert(
|
||||
registered_tool_use_id.clone(),
|
||||
LanguageModelToolResult {
|
||||
tool_use_id: registered_tool_use_id.clone(),
|
||||
tool_name: ReplayImageTool::NAME.into(),
|
||||
is_error: false,
|
||||
content: vec![
|
||||
LanguageModelToolResultContent::Text("before".into()),
|
||||
LanguageModelToolResultContent::Image(image.clone()),
|
||||
LanguageModelToolResultContent::Text("after".into()),
|
||||
],
|
||||
output: Some(json!("raw output")),
|
||||
},
|
||||
);
|
||||
tool_results.insert(
|
||||
missing_tool_use_id.clone(),
|
||||
LanguageModelToolResult {
|
||||
tool_use_id: missing_tool_use_id.clone(),
|
||||
tool_name: "missing_image_tool".into(),
|
||||
is_error: false,
|
||||
content: vec![LanguageModelToolResultContent::Image(image.clone())],
|
||||
output: Some(json!("raw output")),
|
||||
},
|
||||
);
|
||||
|
||||
thread.messages.push(Arc::new(Message::Agent(AgentMessage {
|
||||
content: vec![
|
||||
AgentMessageContent::ToolUse(registered_tool_use),
|
||||
AgentMessageContent::ToolUse(missing_tool_use),
|
||||
],
|
||||
tool_results,
|
||||
reasoning_details: None,
|
||||
})));
|
||||
|
||||
thread.replay(cx)
|
||||
})
|
||||
});
|
||||
|
||||
let mut tool_use_ids_with_image_content = HashSet::default();
|
||||
while let Some(event) = replay_events.next().await {
|
||||
let event = event.unwrap();
|
||||
if let ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update)) =
|
||||
event
|
||||
&& let Some(content) = &update.fields.content
|
||||
&& content.iter().any(|content| {
|
||||
matches!(
|
||||
content,
|
||||
acp::ToolCallContent::Content(acp::Content {
|
||||
content: acp::ContentBlock::Image(_),
|
||||
..
|
||||
})
|
||||
)
|
||||
})
|
||||
{
|
||||
tool_use_ids_with_image_content.insert(update.tool_call_id.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
assert!(tool_use_ids_with_image_content.contains(®istered_tool_use_id.to_string()));
|
||||
assert!(tool_use_ids_with_image_content.contains(&missing_tool_use_id.to_string()));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_tool_replay_does_not_reenter_thread(cx: &mut TestAppContext) {
|
||||
let (thread, _event_stream) = setup_thread_for_test(cx).await;
|
||||
|
||||
let tool_use_id = LanguageModelToolUseId::from("title_tool_id");
|
||||
let mut replay_events = cx.update(|cx| {
|
||||
thread.update(cx, |thread, cx| {
|
||||
thread.add_tool(UpdateTitleTool::new(cx.weak_entity()));
|
||||
push_completed_update_title_tool_call(thread, tool_use_id.clone());
|
||||
|
||||
thread.replay(cx)
|
||||
})
|
||||
});
|
||||
|
||||
let mut saw_tool_call_title = false;
|
||||
let mut saw_replayed_title_update = false;
|
||||
let mut saw_completed_update = false;
|
||||
while let Some(event) = replay_events.next().await {
|
||||
let event = event.unwrap();
|
||||
match event {
|
||||
ThreadEvent::ToolCall(tool_call)
|
||||
if tool_call.tool_call_id.to_string() == tool_use_id.to_string()
|
||||
&& tool_call.title == "Update title: Replayed title" =>
|
||||
{
|
||||
saw_tool_call_title = true;
|
||||
}
|
||||
ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
|
||||
if update.tool_call_id.to_string() == tool_use_id.to_string() =>
|
||||
{
|
||||
if update.fields.title == Some("Update title: Replayed title".to_string()) {
|
||||
saw_replayed_title_update = true;
|
||||
}
|
||||
if update.fields.status == Some(acp::ToolCallStatus::Completed) {
|
||||
saw_completed_update = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(saw_tool_call_title);
|
||||
assert!(saw_replayed_title_update);
|
||||
assert!(saw_completed_update);
|
||||
thread.read_with(cx, |thread, _cx| {
|
||||
assert_eq!(thread.title(), None);
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_update_title_tool_replay_title_when_tool_not_registered(cx: &mut TestAppContext) {
|
||||
let (thread, _event_stream) = setup_thread_for_test(cx).await;
|
||||
|
||||
let tool_use_id = LanguageModelToolUseId::from("title_tool_id");
|
||||
let mut replay_events = cx.update(|cx| {
|
||||
thread.update(cx, |thread, cx| {
|
||||
push_completed_update_title_tool_call(thread, tool_use_id.clone());
|
||||
thread.replay(cx)
|
||||
})
|
||||
});
|
||||
|
||||
let mut saw_tool_call_title = false;
|
||||
let mut saw_replayed_title_update = false;
|
||||
let mut saw_completed_update = false;
|
||||
while let Some(event) = replay_events.next().await {
|
||||
let event = event.unwrap();
|
||||
match event {
|
||||
ThreadEvent::ToolCall(tool_call)
|
||||
if tool_call.tool_call_id.to_string() == tool_use_id.to_string()
|
||||
&& tool_call.title == "Update title: Replayed title" =>
|
||||
{
|
||||
saw_tool_call_title = true;
|
||||
}
|
||||
ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(update))
|
||||
if update.tool_call_id.to_string() == tool_use_id.to_string() =>
|
||||
{
|
||||
if update.fields.title == Some("Update title: Replayed title".to_string()) {
|
||||
saw_replayed_title_update = true;
|
||||
}
|
||||
if update.fields.status == Some(acp::ToolCallStatus::Completed) {
|
||||
saw_completed_update = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(saw_tool_call_title);
|
||||
assert!(saw_replayed_title_update);
|
||||
assert!(saw_completed_update);
|
||||
thread.read_with(cx, |thread, _cx| {
|
||||
assert_eq!(thread.title(), None);
|
||||
});
|
||||
}
|
||||
|
||||
fn push_completed_update_title_tool_call(
|
||||
thread: &mut Thread,
|
||||
tool_use_id: LanguageModelToolUseId,
|
||||
) {
|
||||
let tool_use = LanguageModelToolUse {
|
||||
id: tool_use_id.clone(),
|
||||
name: UpdateTitleTool::NAME.into(),
|
||||
raw_input: json!({ "title": "Replayed title" }).to_string(),
|
||||
input: json!({ "title": "Replayed title" }),
|
||||
is_input_complete: true,
|
||||
thought_signature: None,
|
||||
};
|
||||
|
||||
let mut tool_results = IndexMap::default();
|
||||
tool_results.insert(
|
||||
tool_use_id.clone(),
|
||||
LanguageModelToolResult {
|
||||
tool_use_id,
|
||||
tool_name: UpdateTitleTool::NAME.into(),
|
||||
is_error: false,
|
||||
content: vec![LanguageModelToolResultContent::Text(
|
||||
"Session title updated".into(),
|
||||
)],
|
||||
output: Some(json!("Session title updated")),
|
||||
},
|
||||
);
|
||||
|
||||
thread.messages.push(Arc::new(Message::Agent(AgentMessage {
|
||||
content: vec![AgentMessageContent::ToolUse(tool_use)],
|
||||
tool_results,
|
||||
reasoning_details: None,
|
||||
})));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
|
||||
let (parent, _event_stream) = setup_thread_for_test(cx).await;
|
||||
|
|
|
|||
|
|
@ -167,6 +167,7 @@ mod tests {
|
|||
thinking_effort: None,
|
||||
draft_prompt: None,
|
||||
ui_scroll_position: None,
|
||||
sandboxed_terminal_temp_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ mod symbol_locator;
|
|||
mod terminal_tool;
|
||||
mod tool_permissions;
|
||||
mod update_plan_tool;
|
||||
mod update_title_tool;
|
||||
mod web_search_tool;
|
||||
mod write_file_tool;
|
||||
|
||||
|
|
@ -80,6 +81,7 @@ pub use symbol_locator::*;
|
|||
pub use terminal_tool::*;
|
||||
pub use tool_permissions::*;
|
||||
pub use update_plan_tool::*;
|
||||
pub use update_title_tool::*;
|
||||
pub use web_search_tool::*;
|
||||
pub use write_file_tool::*;
|
||||
|
||||
|
|
@ -172,6 +174,7 @@ tools! {
|
|||
SpawnAgentTool,
|
||||
TerminalTool,
|
||||
UpdatePlanTool,
|
||||
UpdateTitleTool,
|
||||
WebSearchTool,
|
||||
WriteFileTool,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use collections::{BTreeMap, HashMap};
|
|||
use context_server::{ContextServerId, client::NotificationSubscription};
|
||||
use futures::FutureExt as _;
|
||||
use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task};
|
||||
use language_model::LanguageModelToolResultContent;
|
||||
use language_model::{LanguageModelImage, LanguageModelImageExt, LanguageModelToolResultContent};
|
||||
use project::context_server_store::{ContextServerStatus, ContextServerStore};
|
||||
use std::sync::Arc;
|
||||
use util::ResultExt;
|
||||
|
|
@ -261,7 +261,8 @@ impl ContextServerRegistry {
|
|||
}
|
||||
ContextServerStatus::Stopped
|
||||
| ContextServerStatus::Error(_)
|
||||
| ContextServerStatus::AuthRequired => {
|
||||
| ContextServerStatus::AuthRequired
|
||||
| ContextServerStatus::ClientSecretRequired { .. } => {
|
||||
if let Some(registered_server) = self.registered_servers.remove(server_id) {
|
||||
if !registered_server.tools.is_empty() {
|
||||
cx.emit(ContextServerRegistryEvent::ToolsChanged);
|
||||
|
|
@ -346,7 +347,7 @@ impl AnyAgentTool for ContextServerTool {
|
|||
let authorize =
|
||||
event_stream.authorize_third_party_tool(initial_title, tool_id, display_name, cx);
|
||||
|
||||
cx.spawn(async move |_cx| {
|
||||
cx.spawn(async move |cx| {
|
||||
let input = input
|
||||
.recv()
|
||||
.await
|
||||
|
|
@ -394,15 +395,50 @@ impl AnyAgentTool for ContextServerTool {
|
|||
}
|
||||
|
||||
let mut llm_output = Vec::new();
|
||||
let mut tool_call_content = Vec::new();
|
||||
let mut concatenated_text = String::new();
|
||||
for content in response.content {
|
||||
match content {
|
||||
context_server::types::ToolResponseContent::Text { text } => {
|
||||
concatenated_text.push_str(&text);
|
||||
tool_call_content.push(acp::ToolCallContent::Content(acp::Content::new(
|
||||
acp::ContentBlock::Text(acp::TextContent::new(text.clone())),
|
||||
)));
|
||||
llm_output.push(LanguageModelToolResultContent::Text(text.into()));
|
||||
}
|
||||
context_server::types::ToolResponseContent::Image { .. } => {
|
||||
log::warn!("Ignoring image content from tool response");
|
||||
context_server::types::ToolResponseContent::Image { data, mime_type } => {
|
||||
tool_call_content.push(acp::ToolCallContent::Content(acp::Content::new(
|
||||
acp::ContentBlock::Image(acp::ImageContent::new(
|
||||
data.clone(),
|
||||
mime_type.clone(),
|
||||
)),
|
||||
)));
|
||||
let language_model_image = cx
|
||||
.background_spawn({
|
||||
let mime_type = mime_type.clone();
|
||||
async move {
|
||||
LanguageModelImage::from_base64_image(&data, &mime_type)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
match language_model_image {
|
||||
Ok(Some(image)) => {
|
||||
llm_output.push(LanguageModelToolResultContent::Image(image));
|
||||
}
|
||||
Ok(None) => {
|
||||
log::warn!(
|
||||
"Skipping MCP tool response image with MIME type `{}` because it cannot be converted for language model input",
|
||||
mime_type
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"Failed to convert MCP tool response image with MIME type `{}` for language model input: {:#}",
|
||||
mime_type,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
context_server::types::ToolResponseContent::Audio { .. } => {
|
||||
log::warn!("Ignoring audio content from tool response");
|
||||
|
|
@ -415,6 +451,10 @@ impl AnyAgentTool for ContextServerTool {
|
|||
}
|
||||
}
|
||||
}
|
||||
if !tool_call_content.is_empty() {
|
||||
event_stream
|
||||
.update_fields(acp::ToolCallUpdateFields::new().content(tool_call_content));
|
||||
}
|
||||
let raw_output = serde_json::Value::String(concatenated_text);
|
||||
Ok(AgentToolOutput {
|
||||
raw_output,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
use super::tool_permissions::{
|
||||
authorize_symlink_escapes, canonicalize_worktree_roots, collect_symlink_escapes,
|
||||
resolve_creatable_global_skill_descendant_path, resolve_global_skill_descendant_path,
|
||||
sensitive_settings_kind,
|
||||
};
|
||||
use crate::{
|
||||
|
|
@ -23,6 +24,7 @@ use util::markdown::MarkdownInlineCode;
|
|||
///
|
||||
/// This tool should be used when it's desirable to create a copy of a file or directory without modifying the original.
|
||||
/// It's much more efficient than doing this by separately reading and then writing the file or directory's contents, so this tool should be preferred over that approach whenever copying is the goal.
|
||||
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CopyPathToolInput {
|
||||
/// The source path of the file or directory to copy.
|
||||
|
|
@ -100,6 +102,15 @@ impl AgentTool for CopyPathTool {
|
|||
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
|
||||
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
|
||||
|
||||
let global_source_path =
|
||||
resolve_global_skill_descendant_path(Path::new(&input.source_path), fs.as_ref())
|
||||
.await;
|
||||
let global_destination_path = resolve_creatable_global_skill_descendant_path(
|
||||
Path::new(&input.destination_path),
|
||||
fs.as_ref(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let symlink_escapes: Vec<(&str, std::path::PathBuf)> =
|
||||
project.read_with(cx, |project, cx| {
|
||||
collect_symlink_escapes(
|
||||
|
|
@ -160,6 +171,63 @@ impl AgentTool for CopyPathTool {
|
|||
authorize.await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if global_source_path.is_some() || global_destination_path.is_some() {
|
||||
let source_path = if let Some(global_source_path) = global_source_path {
|
||||
global_source_path
|
||||
} else {
|
||||
project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&input.source_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} was not found in the project.", input.source_path)
|
||||
})?;
|
||||
project.entry_for_path(&project_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} was not found in the project.", input.source_path)
|
||||
})?;
|
||||
project.absolute_path(&project_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} could not be resolved.", input.source_path)
|
||||
})
|
||||
})?
|
||||
};
|
||||
|
||||
let destination_path = if let Some(global_destination_path) = global_destination_path
|
||||
{
|
||||
global_destination_path
|
||||
} else {
|
||||
project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&input.destination_path, cx).ok_or_else(|| {
|
||||
format!(
|
||||
"Destination path {} was outside the project.",
|
||||
input.destination_path
|
||||
)
|
||||
})?;
|
||||
project.absolute_path(&project_path, cx).ok_or_else(|| {
|
||||
format!(
|
||||
"Destination path {} could not be resolved.",
|
||||
input.destination_path
|
||||
)
|
||||
})
|
||||
})?
|
||||
};
|
||||
|
||||
futures::select! {
|
||||
result = fs::copy_recursive(
|
||||
fs.as_ref(),
|
||||
&source_path,
|
||||
&destination_path,
|
||||
fs::CopyOptions::default(),
|
||||
).fuse() => {
|
||||
result.map_err(|e| format!("Copying {} to {}: {e}", input.source_path, input.destination_path))?;
|
||||
}
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Copy cancelled by user".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!(
|
||||
"Copied {} to {}",
|
||||
input.source_path, input.destination_path
|
||||
));
|
||||
}
|
||||
|
||||
let copy_task = project.update(cx, |project, cx| {
|
||||
match project
|
||||
.find_project_path(&input.source_path, cx)
|
||||
|
|
@ -222,6 +290,124 @@ mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_copy_path_global_skill_directory_to_project(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(CopyPathTool::new(project));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(CopyPathToolInput {
|
||||
source_path: input_path,
|
||||
destination_path: path!("/root/project/my-skill").to_string(),
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should copy after approval: {result:?}");
|
||||
assert!(fs.is_dir(&skill_dir).await);
|
||||
assert_eq!(
|
||||
fs.load(path!("/root/project/my-skill/SKILL.md").as_ref())
|
||||
.await
|
||||
.unwrap(),
|
||||
"content"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_copy_path_project_directory_to_global_skill_directory(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/root/project"),
|
||||
json!({ "exported-skill": { "SKILL.md": "content" } }),
|
||||
)
|
||||
.await;
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_dir(&skills_dir).await.unwrap();
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(CopyPathTool::new(project));
|
||||
let destination_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("exported-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(CopyPathToolInput {
|
||||
source_path: path!("/root/project/exported-skill").to_string(),
|
||||
destination_path,
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should copy after approval: {result:?}");
|
||||
assert!(
|
||||
fs.is_dir(path!("/root/project/exported-skill").as_ref())
|
||||
.await
|
||||
);
|
||||
assert_eq!(
|
||||
fs.load(skills_dir.join("exported-skill").join("SKILL.md").as_ref())
|
||||
.await
|
||||
.unwrap(),
|
||||
"content"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_copy_path_symlink_escape_source_requests_authorization(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use super::tool_permissions::{
|
||||
authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape,
|
||||
sensitive_settings_kind,
|
||||
resolve_creatable_global_skill_path, sensitive_settings_kind,
|
||||
};
|
||||
use agent_client_protocol::schema as acp;
|
||||
use agent_settings::AgentSettings;
|
||||
|
|
@ -22,6 +22,7 @@ use std::path::Path;
|
|||
/// Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.
|
||||
///
|
||||
/// This tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct CreateDirectoryToolInput {
|
||||
/// The path of the new directory.
|
||||
|
|
@ -34,6 +35,10 @@ pub struct CreateDirectoryToolInput {
|
|||
///
|
||||
/// You can create a new directory by providing a path of "directory1/new_directory"
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To create a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.
|
||||
/// </example>
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
|
|
@ -144,6 +149,21 @@ impl AgentTool for CreateDirectoryTool {
|
|||
authorize.await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if let Some(global_skill_directory) =
|
||||
resolve_creatable_global_skill_path(Path::new(&input.path), fs.as_ref()).await
|
||||
{
|
||||
futures::select! {
|
||||
result = fs.create_dir(&global_skill_directory).fuse() => {
|
||||
result.map_err(|e| format!("Creating directory {destination_path}: {e}"))?;
|
||||
}
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Create directory cancelled by user".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!("Created directory {destination_path}"));
|
||||
}
|
||||
|
||||
let create_entry = project.update(cx, |project, cx| {
|
||||
match project.find_project_path(&input.path, cx) {
|
||||
Some(project_path) => Ok(project.create_entry(project_path, true, cx)),
|
||||
|
|
@ -190,6 +210,96 @@ mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_create_directory_allows_global_skill_directory(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(CreateDirectoryTool::new(project));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let created_path = agent_skills::global_skills_dir().join("my-skill");
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(CreateDirectoryToolInput { path: input_path }),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"Tool should create global skill directory: {result:?}"
|
||||
);
|
||||
assert!(fs.is_dir(&created_path).await);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_create_directory_rejects_other_global_paths(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(CreateDirectoryTool::new(project));
|
||||
let outside_path = agent_skills::global_skills_dir()
|
||||
.parent()
|
||||
.expect("global skills directory should have a parent")
|
||||
.join("not-skills");
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let result = cx
|
||||
.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(CreateDirectoryToolInput {
|
||||
path: outside_path.to_string_lossy().into_owned(),
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
result.is_err(),
|
||||
"Tool should reject paths outside the project and global skills directory"
|
||||
);
|
||||
assert!(!fs.is_dir(&outside_path).await);
|
||||
assert!(
|
||||
!matches!(
|
||||
event_rx.try_recv(),
|
||||
Ok(Ok(crate::ThreadEvent::ToolCallAuthorization(_)))
|
||||
),
|
||||
"Non-skill global path should not emit an agent-skills authorization prompt",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_create_directory_symlink_escape_requests_authorization(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use super::tool_permissions::{
|
||||
authorize_symlink_access, canonicalize_worktree_roots, detect_symlink_escape,
|
||||
sensitive_settings_kind,
|
||||
resolve_global_skill_descendant_path, resolves_to_global_skills_dir, sensitive_settings_kind,
|
||||
};
|
||||
use crate::{
|
||||
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
|
||||
|
|
@ -20,6 +20,8 @@ use std::sync::Arc;
|
|||
use util::markdown::MarkdownInlineCode;
|
||||
|
||||
/// Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.
|
||||
///
|
||||
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct DeletePathToolInput {
|
||||
/// The path of the file or directory to delete.
|
||||
|
|
@ -95,6 +97,16 @@ impl AgentTool for DeletePathTool {
|
|||
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
|
||||
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
|
||||
|
||||
if resolves_to_global_skills_dir(Path::new(&path), fs.as_ref()).await {
|
||||
return Err(
|
||||
"Cannot delete the global agent skills directory itself. Delete a skill directory or file beneath it instead."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let global_skill_path =
|
||||
resolve_global_skill_descendant_path(Path::new(&path), fs.as_ref()).await;
|
||||
|
||||
let symlink_escape_target = project.read_with(cx, |project, cx| {
|
||||
detect_symlink_escape(project, &path, &canonical_roots, cx)
|
||||
.map(|(_, target)| target)
|
||||
|
|
@ -147,6 +159,38 @@ impl AgentTool for DeletePathTool {
|
|||
authorize.await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if let Some(global_skill_path) = global_skill_path {
|
||||
let metadata = fs
|
||||
.metadata(&global_skill_path)
|
||||
.await
|
||||
.map_err(|e| format!("Deleting {path}: {e}"))?
|
||||
.ok_or_else(|| format!("Deleting {path}: path not found"))?;
|
||||
|
||||
futures::select! {
|
||||
result = async {
|
||||
if metadata.is_dir {
|
||||
fs.remove_dir(
|
||||
&global_skill_path,
|
||||
fs::RemoveOptions {
|
||||
recursive: true,
|
||||
..fs::RemoveOptions::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
fs.remove_file(&global_skill_path, fs::RemoveOptions::default()).await
|
||||
}
|
||||
}.fuse() => {
|
||||
result.map_err(|e| format!("Deleting {path}: {e}"))?;
|
||||
}
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Delete cancelled by user".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!("Deleted {path}"));
|
||||
}
|
||||
|
||||
let (project_path, worktree_snapshot) = project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&path, cx).ok_or_else(|| {
|
||||
format!("Couldn't delete {path} because that path isn't in this project.")
|
||||
|
|
@ -248,6 +292,145 @@ mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_path_global_skill_directory(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
let skill_dir = skills_dir.join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(DeletePathTool::new(project, action_log));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(DeletePathToolInput { path: input_path }),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should delete after approval: {result:?}");
|
||||
assert!(fs.is_dir(&skills_dir).await);
|
||||
assert!(!fs.is_dir(&skill_dir).await);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_path_global_skill_file(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skill_file = agent_skills::global_skills_dir()
|
||||
.join("my-skill")
|
||||
.join("references")
|
||||
.join("notes.md");
|
||||
fs.create_dir(skill_file.parent().unwrap()).await.unwrap();
|
||||
fs.insert_file(&skill_file, b"notes".to_vec()).await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(DeletePathTool::new(project, action_log));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.join("references")
|
||||
.join("notes.md")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(DeletePathToolInput { path: input_path }),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should delete after approval: {result:?}");
|
||||
assert!(!fs.is_file(&skill_file).await);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_path_rejects_global_skills_root(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_dir(&skills_dir).await.unwrap();
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(DeletePathTool::new(project, action_log));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let result = cx
|
||||
.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(DeletePathToolInput { path: input_path }),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(result.is_err(), "should reject deleting skills root");
|
||||
assert!(fs.is_dir(&skills_dir).await);
|
||||
assert!(
|
||||
!matches!(
|
||||
event_rx.try_recv(),
|
||||
Ok(Ok(crate::ThreadEvent::ToolCallAuthorization(_)))
|
||||
),
|
||||
"Deleting the skills root should fail before requesting authorization",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_delete_path_symlink_escape_requests_authorization(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -1,16 +1,18 @@
|
|||
use crate::{AgentTool, ToolCallEventStream, ToolInput};
|
||||
use agent_client_protocol::schema as acp;
|
||||
use anyhow::Result;
|
||||
use futures::FutureExt as _;
|
||||
use gpui::{App, Entity, Task};
|
||||
use futures::{Future, FutureExt as _};
|
||||
use gpui::{App, AsyncApp, Entity, Task};
|
||||
use language::{DiagnosticSeverity, OffsetRangeExt};
|
||||
use project::Project;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use std::{fmt::Write, sync::Arc};
|
||||
use ui::SharedString;
|
||||
use util::markdown::MarkdownInlineCode;
|
||||
|
||||
type Result<T, E = String> = core::result::Result<T, E>;
|
||||
|
||||
/// Get errors and warnings for the project or a specific file.
|
||||
///
|
||||
/// This tool can be invoked after a series of edits to determine if further edits are necessary, or if the user asks to fix errors or warnings in their codebase.
|
||||
|
|
@ -18,6 +20,11 @@ use util::markdown::MarkdownInlineCode;
|
|||
/// When a path is provided, shows all diagnostics for that specific file.
|
||||
/// When no path is provided, shows a summary of error and warning counts for all files in the project.
|
||||
///
|
||||
/// This tool attempts to refresh diagnostics before returning.
|
||||
/// If refreshing diagnostics fails (for example, if the language server does not support pull-based diagnostics), it will return any diagnostics already present.
|
||||
/// Note that, in this case, the results may be out-of-date, and may or may not reflect the most recent edits.
|
||||
/// If this happens, do not attempt to re-run this tool in the hope that refreshing will later succeed. Failures are typically persistent.
|
||||
///
|
||||
/// <example>
|
||||
/// To get diagnostics for a specific file:
|
||||
/// {
|
||||
|
|
@ -60,6 +67,71 @@ impl DiagnosticsTool {
|
|||
}
|
||||
}
|
||||
|
||||
async fn with_cancellation<T>(f: impl Future<Output = T>, s: &ToolCallEventStream) -> Result<T> {
|
||||
futures::select! {
|
||||
result = f.fuse() => Ok(result),
|
||||
_ = s.cancelled_by_user().fuse() => {
|
||||
Err("Diagnostics cancelled by user".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn freshness_message(refreshed: bool) -> &'static str {
|
||||
if refreshed {
|
||||
"Diagnostics successfully refreshed."
|
||||
} else {
|
||||
"Failed to refresh diagnostics. Diagnostics may be stale."
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempt to pull fresh diagnostics from the LSP before reading them.
|
||||
///
|
||||
/// Returns `Ok(true)` if diagnostics were successfully refreshed,
|
||||
/// `Ok(false)` if the pull failed (callers should fall through to
|
||||
/// read cached diagnostics), or `Err` if cancelled by the user.
|
||||
async fn pull_diagnostics(
|
||||
project: &Entity<Project>,
|
||||
path: Option<&Path>,
|
||||
event_stream: &ToolCallEventStream,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Result<bool, String> {
|
||||
match path {
|
||||
Some(path) => {
|
||||
let open_buffer_task = project.update(cx, |project, cx| {
|
||||
let Some(project_path) = project.find_project_path(path, cx) else {
|
||||
return Err(format!("Could not find path {} in project", path.display()));
|
||||
};
|
||||
Ok(project.open_buffer(project_path, cx))
|
||||
})?;
|
||||
|
||||
let buffer = with_cancellation(open_buffer_task, event_stream)
|
||||
.await?
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let lsp_store = project.read_with(cx, |project, _cx| project.lsp_store());
|
||||
let pull_task = lsp_store.update(cx, |lsp_store, cx| {
|
||||
lsp_store.pull_diagnostics_for_buffer(buffer, cx)
|
||||
});
|
||||
let pull_result = with_cancellation(pull_task, event_stream).await?;
|
||||
if let Err(error) = &pull_result {
|
||||
log::warn!("Failed to pull diagnostics, using cached: {error:#}");
|
||||
}
|
||||
Ok(pull_result.is_ok())
|
||||
}
|
||||
None => {
|
||||
let lsp_store = project.read_with(cx, |project, _cx| project.lsp_store());
|
||||
let pull_task = lsp_store.update(cx, |lsp_store, cx| {
|
||||
lsp_store.pull_workspace_diagnostics_once(cx)
|
||||
});
|
||||
let succeeded = with_cancellation(pull_task, event_stream).await?;
|
||||
if !succeeded {
|
||||
log::warn!("Failed to pull workspace diagnostics, using cached");
|
||||
}
|
||||
Ok(succeeded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentTool for DiagnosticsTool {
|
||||
type Input = DiagnosticsToolInput;
|
||||
type Output = String;
|
||||
|
|
@ -96,21 +168,22 @@ impl AgentTool for DiagnosticsTool {
|
|||
let input = input.recv().await.map_err(|e| e.to_string())?;
|
||||
|
||||
match input.path {
|
||||
Some(path) if !path.is_empty() => {
|
||||
let (_project_path, open_buffer_task) = project.update(cx, |project, cx| {
|
||||
let Some(project_path) = project.find_project_path(&path, cx) else {
|
||||
Some(ref path) if !path.is_empty() => {
|
||||
let refreshed =
|
||||
pull_diagnostics(&project, Some(Path::new(path)), &event_stream, cx)
|
||||
.await?;
|
||||
|
||||
let open_buffer_task = project.update(cx, |project, cx| {
|
||||
let Some(project_path) = project.find_project_path(path, cx) else {
|
||||
return Err(format!("Could not find path {path} in project"));
|
||||
};
|
||||
let task = project.open_buffer(project_path.clone(), cx);
|
||||
Ok((project_path, task))
|
||||
Ok(project.open_buffer(project_path, cx))
|
||||
})?;
|
||||
|
||||
let buffer = futures::select! {
|
||||
result = open_buffer_task.fuse() => result.map_err(|e| e.to_string())?,
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Diagnostics cancelled by user".to_string());
|
||||
}
|
||||
};
|
||||
let buffer = with_cancellation(open_buffer_task, &event_stream)
|
||||
.await?
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut output = String::new();
|
||||
let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
|
||||
|
||||
|
|
@ -133,13 +206,18 @@ impl AgentTool for DiagnosticsTool {
|
|||
.ok();
|
||||
}
|
||||
|
||||
let freshness = freshness_message(refreshed);
|
||||
if output.is_empty() {
|
||||
Ok("File doesn't have errors or warnings!".to_string())
|
||||
Ok(format!(
|
||||
"{freshness}\n\nFile doesn't have errors or warnings!"
|
||||
))
|
||||
} else {
|
||||
Ok(output)
|
||||
Ok(format!("{freshness}\n\n{output}"))
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let refreshed = pull_diagnostics(&project, None, &event_stream, cx).await?;
|
||||
|
||||
let (output, has_diagnostics) = project.read_with(cx, |project, cx| {
|
||||
let mut output = String::new();
|
||||
let mut has_diagnostics = false;
|
||||
|
|
@ -165,10 +243,13 @@ impl AgentTool for DiagnosticsTool {
|
|||
(output, has_diagnostics)
|
||||
});
|
||||
|
||||
let freshness = freshness_message(refreshed);
|
||||
if has_diagnostics {
|
||||
Ok(output)
|
||||
Ok(format!("{freshness}\n\n{output}"))
|
||||
} else {
|
||||
Ok("No errors or warnings found in the project.".into())
|
||||
Ok(format!(
|
||||
"{freshness}\n\nNo errors or warnings found in the project."
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,13 +23,21 @@ const DEFAULT_UI_TEXT: &str = "Editing file";
|
|||
|
||||
/// This is a tool for applying edits to an existing file.
|
||||
///
|
||||
/// Before using this tool, use the `read_file` tool to understand the file's contents and context
|
||||
/// Before using this tool, use the `read_file` tool to understand the file's contents and context.
|
||||
/// To create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.
|
||||
///
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
///
|
||||
/// `read_file` prefixes each line of its output with a line number right-aligned in a
|
||||
/// 6-character field followed by a single tab, then the line's actual content. When you
|
||||
/// derive `old_text` or `new_text` from that output, strip this prefix and keep only what
|
||||
/// comes after the tab, preserving the original indentation (tabs and spaces) exactly.
|
||||
/// Never include any part of the line number prefix in `old_text` or `new_text`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct EditFileToolInput {
|
||||
/// The full path of the file to edit in the project.
|
||||
///
|
||||
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories.
|
||||
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.
|
||||
///
|
||||
/// The following examples assume we have two root directories in the project:
|
||||
/// - /a/b/backend
|
||||
|
|
@ -44,6 +52,10 @@ pub struct EditFileToolInput {
|
|||
/// <example>
|
||||
/// `frontend/db.js`
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To edit a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
|
||||
/// </example>
|
||||
pub path: PathBuf,
|
||||
|
||||
/// List of edit operations to apply sequentially.
|
||||
|
|
@ -253,6 +265,7 @@ impl AgentTool for EditFileTool {
|
|||
run_session(
|
||||
self.process_streaming_edits(&mut input, &event_stream, cx)
|
||||
.await,
|
||||
&event_stream,
|
||||
cx,
|
||||
)
|
||||
.await
|
||||
|
|
@ -457,6 +470,63 @@ mod tests {
|
|||
assert_eq!(input_path, None);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_edit_global_skill_file(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = project::FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root"), json!({})).await;
|
||||
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "old content\n" }))
|
||||
.await;
|
||||
let (edit_tool, _project, _action_log, fs, _thread) =
|
||||
setup_test_with_fs(cx, fs, &[path!("/root").as_ref()]).await;
|
||||
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
let skill_file = agent_skills::global_skills_dir()
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
edit_tool.clone().run(
|
||||
ToolInput::resolved(EditFileToolInput {
|
||||
path: input_path,
|
||||
edits: vec![Edit {
|
||||
old_text: "old content".into(),
|
||||
new_text: "new content".into(),
|
||||
}],
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
event_rx.expect_update_fields().await;
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let EditFileToolOutput::Success { new_text, .. } = task.await.unwrap() else {
|
||||
panic!("expected success");
|
||||
};
|
||||
assert_eq!(new_text, "new content\n");
|
||||
assert_eq!(fs.load(&skill_file).await.unwrap(), "new content\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_edit_failed_match(cx: &mut TestAppContext) {
|
||||
let (edit_tool, _project, _action_log, _fs, _thread) =
|
||||
|
|
@ -486,6 +556,69 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
/// When the edit fails after a session is created but before any edits are
|
||||
/// actually applied (e.g., the first `old_text` doesn't match), the empty
|
||||
/// diff placeholder in the UI should be replaced with the error message.
|
||||
#[gpui::test]
|
||||
async fn test_streaming_edit_surfaces_error_when_no_edits_applied(cx: &mut TestAppContext) {
|
||||
async fn find_first_text_content_in_events(
|
||||
receiver: &mut crate::ToolCallEventStreamReceiver,
|
||||
) -> Option<String> {
|
||||
use futures::StreamExt as _;
|
||||
while let Some(event) = receiver.next().await {
|
||||
let Ok(crate::ThreadEvent::ToolCallUpdate(
|
||||
acp_thread::ToolCallUpdate::UpdateFields(update),
|
||||
)) = event
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(content) = update.fields.content else {
|
||||
continue;
|
||||
};
|
||||
for item in content {
|
||||
if let acp::ToolCallContent::Content(c) = item
|
||||
&& let acp::ContentBlock::Text(text) = c.content
|
||||
{
|
||||
return Some(text.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
let (edit_tool, _project, _action_log, _fs, _thread) =
|
||||
setup_test(cx, json!({"file.txt": "hello world"})).await;
|
||||
let (event_stream, mut receiver) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
edit_tool.clone().run(
|
||||
ToolInput::resolved(EditFileToolInput {
|
||||
path: "root/file.txt".into(),
|
||||
edits: vec![Edit {
|
||||
old_text: "nonexistent text that is not in the file".into(),
|
||||
new_text: "replacement".into(),
|
||||
}],
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let EditFileToolOutput::Error { error, diff, .. } = task.await.unwrap_err() else {
|
||||
panic!("expected error");
|
||||
};
|
||||
assert!(
|
||||
diff.is_empty(),
|
||||
"sanity check: no edits should have been applied",
|
||||
);
|
||||
|
||||
let content_text = find_first_text_content_in_events(&mut receiver).await;
|
||||
assert_eq!(
|
||||
content_text.as_deref(),
|
||||
Some(error.as_str()),
|
||||
"expected the failure message to be surfaced as tool call content",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_early_buffer_open(cx: &mut TestAppContext) {
|
||||
let (edit_tool, _project, _action_log, _fs, _thread) =
|
||||
|
|
@ -2475,7 +2608,8 @@ mod tests {
|
|||
|
||||
cx.run_until_parked();
|
||||
|
||||
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
|
||||
let changed =
|
||||
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
|
||||
assert!(
|
||||
!changed.is_empty(),
|
||||
"action_log.changed_buffers() should be non-empty after streaming edit,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ mod reindent;
|
|||
mod streaming_fuzzy_matcher;
|
||||
mod streaming_parser;
|
||||
|
||||
use super::tool_permissions::resolve_creatable_global_skill_path;
|
||||
use crate::{Thread, ToolCallEventStream};
|
||||
use acp_thread::Diff;
|
||||
use action_log::ActionLog;
|
||||
|
|
@ -11,7 +12,7 @@ use collections::HashSet;
|
|||
use futures::{FutureExt, channel::oneshot};
|
||||
use gpui::{App, AppContext, AsyncApp, Entity, Task, WeakEntity};
|
||||
use language::language_settings::{self, FormatOnSave};
|
||||
use language::{Buffer, BufferEvent, LanguageRegistry};
|
||||
use language::{Buffer, BufferEditSource, BufferEvent, LanguageRegistry};
|
||||
use language_model::LanguageModelToolResultContent;
|
||||
use project::lsp_store::{FormatTrigger, LspFormatTarget};
|
||||
use project::{AgentLocation, Project, ProjectPath};
|
||||
|
|
@ -277,6 +278,7 @@ pub(crate) enum EditSessionResult {
|
|||
|
||||
pub(crate) async fn run_session(
|
||||
result: EditSessionResult,
|
||||
event_stream: &ToolCallEventStream,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Result<EditSessionOutput, EditSessionOutput> {
|
||||
match result {
|
||||
|
|
@ -302,6 +304,11 @@ pub(crate) async fn run_session(
|
|||
.ensure_buffer_saved(&session.buffer, cx)
|
||||
.await;
|
||||
let (_new_text, diff) = session.compute_new_text_and_diff(cx).await;
|
||||
if diff.is_empty() {
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
|
||||
acp::ToolCallContent::Content(acp::Content::new(error.clone())),
|
||||
]));
|
||||
}
|
||||
Err(EditSessionOutput::Error {
|
||||
error,
|
||||
input_path: Some(session.input_path),
|
||||
|
|
@ -311,11 +318,16 @@ pub(crate) async fn run_session(
|
|||
EditSessionResult::Failed {
|
||||
error,
|
||||
session: None,
|
||||
} => Err(EditSessionOutput::Error {
|
||||
error,
|
||||
input_path: None,
|
||||
diff: String::new(),
|
||||
}),
|
||||
} => {
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
|
||||
acp::ToolCallContent::Content(acp::Content::new(error.clone())),
|
||||
]));
|
||||
Err(EditSessionOutput::Error {
|
||||
error,
|
||||
input_path: None,
|
||||
diff: String::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -352,6 +364,16 @@ pub(crate) struct EditSession {
|
|||
_finalize_diff_guard: Deferred<Box<dyn FnOnce()>>,
|
||||
}
|
||||
|
||||
/// The destination of an edit session, identified by its absolute path on
|
||||
/// disk. `project_path` is `Some` for files that live inside one of the
|
||||
/// project's worktrees (i.e. that the standard project-path machinery can
|
||||
/// resolve), and `None` for global skill files reached through the
|
||||
/// `~/.agents/skills` allowlist.
|
||||
struct EditSessionTarget {
|
||||
abs_path: PathBuf,
|
||||
project_path: Option<ProjectPath>,
|
||||
}
|
||||
|
||||
enum Pipeline {
|
||||
Write(WritePipeline),
|
||||
Edit(EditPipeline),
|
||||
|
|
@ -598,21 +620,14 @@ impl EditPipeline {
|
|||
|
||||
log::debug!("new_text_chunk: done=true, final_text='{}'", final_text);
|
||||
|
||||
if !final_text.is_empty() {
|
||||
let char_ops = streaming_diff.push_new(&final_text);
|
||||
apply_char_operations(
|
||||
&char_ops,
|
||||
buffer,
|
||||
&original_snapshot,
|
||||
&mut edit_cursor,
|
||||
&context.action_log,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
let remaining_ops = streaming_diff.finish();
|
||||
let mut char_ops = if final_text.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
streaming_diff.push_new(&final_text)
|
||||
};
|
||||
char_ops.extend(streaming_diff.finish());
|
||||
apply_char_operations(
|
||||
&remaining_ops,
|
||||
&char_ops,
|
||||
buffer,
|
||||
&original_snapshot,
|
||||
&mut edit_cursor,
|
||||
|
|
@ -639,16 +654,34 @@ impl EditSession {
|
|||
event_stream: &ToolCallEventStream,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Result<Self, String> {
|
||||
let project_path = cx.update(|cx| resolve_path(mode, &path, &context.project, cx))?;
|
||||
let target = if let Some(abs_path) =
|
||||
resolve_global_skill_path_for_edit_session(mode, &path, &context, cx).await?
|
||||
{
|
||||
EditSessionTarget {
|
||||
abs_path,
|
||||
project_path: None,
|
||||
}
|
||||
} else {
|
||||
let project_path = cx.update(|cx| resolve_path(mode, &path, &context.project, cx))?;
|
||||
|
||||
let Some(abs_path) =
|
||||
cx.update(|cx| context.project.read(cx).absolute_path(&project_path, cx))
|
||||
else {
|
||||
return Err(format!(
|
||||
"Worktree at '{}' does not exist",
|
||||
path.to_string_lossy()
|
||||
));
|
||||
let Some(abs_path) =
|
||||
cx.update(|cx| context.project.read(cx).absolute_path(&project_path, cx))
|
||||
else {
|
||||
return Err(format!(
|
||||
"Worktree at '{}' does not exist",
|
||||
path.to_string_lossy()
|
||||
));
|
||||
};
|
||||
|
||||
EditSessionTarget {
|
||||
abs_path,
|
||||
project_path: Some(project_path),
|
||||
}
|
||||
};
|
||||
let EditSessionTarget {
|
||||
abs_path,
|
||||
project_path,
|
||||
} = target;
|
||||
|
||||
event_stream.update_fields(
|
||||
ToolCallUpdateFields::new().locations(vec![ToolCallLocation::new(abs_path.clone())]),
|
||||
|
|
@ -658,11 +691,20 @@ impl EditSession {
|
|||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let buffer = context
|
||||
.project
|
||||
.update(cx, |project, cx| project.open_buffer(project_path, cx))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let buffer = match project_path {
|
||||
Some(project_path) => context
|
||||
.project
|
||||
.update(cx, |project, cx| project.open_buffer(project_path, cx))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?,
|
||||
None => context
|
||||
.project
|
||||
.update(cx, |project, cx| {
|
||||
project.open_local_buffer(abs_path.clone(), cx)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?,
|
||||
};
|
||||
|
||||
let file_changed_since_last_read =
|
||||
ensure_buffer_saved(&buffer, &abs_path, mode, &context, event_stream, cx).await?;
|
||||
|
|
@ -853,16 +895,17 @@ fn apply_char_operations(
|
|||
action_log: &Entity<ActionLog>,
|
||||
cx: &mut AsyncApp,
|
||||
) {
|
||||
let mut edits: Vec<_> = Vec::new();
|
||||
for op in ops {
|
||||
match op {
|
||||
CharOperation::Insert { text } => {
|
||||
let anchor = snapshot.anchor_after(*edit_cursor);
|
||||
agent_edit_buffer(&buffer, [(anchor..anchor, text.as_str())], action_log, cx);
|
||||
edits.push((anchor..anchor, text.as_str().into()));
|
||||
}
|
||||
CharOperation::Delete { bytes } => {
|
||||
let delete_end = *edit_cursor + bytes;
|
||||
let anchor_range = snapshot.anchor_range_inside(*edit_cursor..delete_end);
|
||||
agent_edit_buffer(&buffer, [(anchor_range, "")], action_log, cx);
|
||||
edits.push((anchor_range, Arc::<str>::from("")));
|
||||
*edit_cursor = delete_end;
|
||||
}
|
||||
CharOperation::Keep { bytes } => {
|
||||
|
|
@ -870,6 +913,9 @@ fn apply_char_operations(
|
|||
}
|
||||
}
|
||||
}
|
||||
if !edits.is_empty() {
|
||||
agent_edit_buffer(buffer, edits, action_log, cx);
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_match(
|
||||
|
|
@ -926,7 +972,9 @@ fn agent_edit_buffer<I, S, T>(
|
|||
{
|
||||
cx.update(|cx| {
|
||||
buffer.update(cx, |buffer, cx| {
|
||||
buffer.start_transaction();
|
||||
buffer.edit(edits, None, cx);
|
||||
buffer.end_transaction_with_source(BufferEditSource::Agent, cx);
|
||||
});
|
||||
action_log.update(cx, |log, cx| log.buffer_edited(buffer.clone(), cx));
|
||||
});
|
||||
|
|
@ -1055,6 +1103,72 @@ async fn resolve_dirty_buffer(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Mirrors [`resolve_path`]'s pre-auth validation for the global-skill
|
||||
/// branch: returns `Ok(Some(abs_path))` if the path lives under
|
||||
/// `~/.agents/skills` and is in a valid state for the requested mode,
|
||||
/// `Ok(None)` if the path isn't a global skill at all (so the caller should
|
||||
/// fall through to project-path resolution), or `Err(message)` if the path
|
||||
/// is a global skill but can't be used (missing in Edit mode, parent
|
||||
/// missing in Write mode, etc.).
|
||||
///
|
||||
/// Errors returned from here surface to the model as tool-result errors
|
||||
/// without prompting the user — same contract as [`resolve_path`]. The
|
||||
/// idea is that "file doesn't exist" or "parent isn't a directory" are
|
||||
/// model mistakes, not decisions the user should be asked to approve.
|
||||
async fn resolve_global_skill_path_for_edit_session(
|
||||
mode: EditSessionMode,
|
||||
path: &PathBuf,
|
||||
context: &EditSessionContext,
|
||||
cx: &mut AsyncApp,
|
||||
) -> Result<Option<PathBuf>, String> {
|
||||
let fs = context
|
||||
.project
|
||||
.read_with(cx, |project, _cx| project.fs().clone());
|
||||
let Some(abs_path) = resolve_creatable_global_skill_path(path, fs.as_ref()).await else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
match mode {
|
||||
EditSessionMode::Edit => {
|
||||
let metadata = fs
|
||||
.metadata(&abs_path)
|
||||
.await
|
||||
.map_err(|e| format!("Can't edit file: {e}"))?
|
||||
.ok_or_else(|| "Can't edit file: path not found".to_string())?;
|
||||
if metadata.is_dir {
|
||||
return Err("Can't edit file: path is a directory".to_string());
|
||||
}
|
||||
}
|
||||
EditSessionMode::Write => {
|
||||
if let Some(metadata) = fs
|
||||
.metadata(&abs_path)
|
||||
.await
|
||||
.map_err(|e| format!("Can't write to file: {e}"))?
|
||||
{
|
||||
if metadata.is_dir {
|
||||
return Err("Can't write to file: path is a directory".to_string());
|
||||
}
|
||||
} else {
|
||||
let parent_path = abs_path
|
||||
.parent()
|
||||
.ok_or_else(|| "Can't create file: incorrect path".to_string())?;
|
||||
let parent_metadata = fs
|
||||
.metadata(parent_path)
|
||||
.await
|
||||
.map_err(|e| format!("Can't create file: {e}"))?
|
||||
.ok_or_else(|| {
|
||||
"Can't create file: parent directory doesn't exist".to_string()
|
||||
})?;
|
||||
if !parent_metadata.is_dir {
|
||||
return Err("Can't create file: parent is not a directory".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(abs_path))
|
||||
}
|
||||
|
||||
fn resolve_path(
|
||||
mode: EditSessionMode,
|
||||
path: &PathBuf,
|
||||
|
|
|
|||
|
|
@ -113,7 +113,7 @@ impl StreamingParser {
|
|||
{
|
||||
if partial.new_text.is_some() && !state.buffer_new_text_until_old_text_done {
|
||||
// new_text appeared after old_text, so old_text is done — emit everything.
|
||||
let start = state.old_text_emitted_len.min(old_text.len());
|
||||
let start = find_char_boundary(old_text, state.old_text_emitted_len);
|
||||
let chunk = normalize_done_chunk(old_text[start..].to_string());
|
||||
state.old_text_done = true;
|
||||
state.old_text_emitted_len = old_text.len();
|
||||
|
|
@ -124,9 +124,10 @@ impl StreamingParser {
|
|||
});
|
||||
} else {
|
||||
let safe_end = safe_emit_end_for_edit_text(old_text);
|
||||
let safe_start = find_char_boundary(old_text, state.old_text_emitted_len);
|
||||
|
||||
if safe_end > state.old_text_emitted_len {
|
||||
let chunk = old_text[state.old_text_emitted_len..safe_end].to_string();
|
||||
if safe_end > safe_start {
|
||||
let chunk = old_text[safe_start..safe_end].to_string();
|
||||
state.old_text_emitted_len = safe_end;
|
||||
events.push(EditEvent::OldTextChunk {
|
||||
edit_index: index,
|
||||
|
|
@ -143,9 +144,10 @@ impl StreamingParser {
|
|||
&& !state.new_text_done
|
||||
{
|
||||
let safe_end = safe_emit_end_for_edit_text(new_text);
|
||||
let safe_start = find_char_boundary(new_text, state.new_text_emitted_len);
|
||||
|
||||
if safe_end > state.new_text_emitted_len {
|
||||
let chunk = new_text[state.new_text_emitted_len..safe_end].to_string();
|
||||
if safe_end > safe_start {
|
||||
let chunk = new_text[safe_start..safe_end].to_string();
|
||||
state.new_text_emitted_len = safe_end;
|
||||
events.push(EditEvent::NewTextChunk {
|
||||
edit_index: index,
|
||||
|
|
@ -343,8 +345,10 @@ impl StreamingParser {
|
|||
/// held back because it may be an artifact of the partial JSON fixer closing
|
||||
/// an incomplete escape sequence (e.g. turning a half-received `\n` into `\\`).
|
||||
/// The next partial will reveal the correct character.
|
||||
///
|
||||
/// The returned position is always a valid UTF-8 character boundary.
|
||||
fn safe_emit_end(text: &str) -> usize {
|
||||
if text.as_bytes().last() == Some(&b'\\') {
|
||||
if text.ends_with('\\') {
|
||||
text.len() - 1
|
||||
} else {
|
||||
text.len()
|
||||
|
|
@ -353,13 +357,35 @@ fn safe_emit_end(text: &str) -> usize {
|
|||
|
||||
fn safe_emit_end_for_edit_text(text: &str) -> usize {
|
||||
let safe_end = safe_emit_end(text);
|
||||
if safe_end > 0 && text.as_bytes()[safe_end - 1] == b'\n' {
|
||||
// Use string slicing to check the last character, ensuring we respect UTF-8 boundaries.
|
||||
if safe_end > 0 && text[..safe_end].ends_with('\n') {
|
||||
safe_end - 1
|
||||
} else {
|
||||
safe_end
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds a valid UTF-8 character boundary at or before the target position.
|
||||
///
|
||||
/// When streaming partial JSON, the text structure can change between updates
|
||||
/// (e.g., an escape sequence being completed). This means a byte position that
|
||||
/// was valid in one partial may land inside a multi-byte character in the next.
|
||||
/// This function finds the nearest valid boundary at or before the target.
|
||||
fn find_char_boundary(text: &str, target: usize) -> usize {
|
||||
if target >= text.len() {
|
||||
return text.len();
|
||||
}
|
||||
if text.is_char_boundary(target) {
|
||||
return target;
|
||||
}
|
||||
// Walk backwards to find a valid boundary.
|
||||
let mut pos = target;
|
||||
while pos > 0 && !text.is_char_boundary(pos) {
|
||||
pos -= 1;
|
||||
}
|
||||
pos
|
||||
}
|
||||
|
||||
fn normalize_done_chunk(mut chunk: String) -> String {
|
||||
if chunk.ends_with('\n') {
|
||||
chunk.pop();
|
||||
|
|
@ -1146,4 +1172,77 @@ mod tests {
|
|||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multibyte_char_with_trailing_backslash() {
|
||||
// Reproduces a panic where the stored `old_text_emitted_len` from a previous
|
||||
// partial lands inside a multi-byte UTF-8 character in the current partial.
|
||||
//
|
||||
// Scenario: The JSON fixer produces a literal backslash when the stream cuts
|
||||
// mid-escape. If the *next* partial replaces that backslash with a multi-byte
|
||||
// character (e.g., em-dash '—'), the stored byte position is no longer valid.
|
||||
let mut parser = StreamingParser::default();
|
||||
|
||||
// First partial: text ends with backslash (held back by safe_emit_end).
|
||||
// "abc" = 3 bytes, backslash held back, so emitted_len = 3.
|
||||
let events = parser.push_edits(&[PartialEdit {
|
||||
old_text: Some("abc\\".into()),
|
||||
new_text: None,
|
||||
}]);
|
||||
assert_eq!(
|
||||
events.as_slice(),
|
||||
&[EditEvent::OldTextChunk {
|
||||
edit_index: 0,
|
||||
chunk: "abc".into(),
|
||||
done: false,
|
||||
}]
|
||||
);
|
||||
|
||||
// Second partial: the backslash is replaced by em-dash '—' (3 bytes: E2 80 94).
|
||||
// "ab—" = 2 + 3 = 5 bytes total, with em-dash at bytes 2..5.
|
||||
// The stored emitted_len (3) is inside the em-dash!
|
||||
// This should NOT panic.
|
||||
let events = parser.push_edits(&[PartialEdit {
|
||||
old_text: Some("ab—".into()),
|
||||
new_text: None,
|
||||
}]);
|
||||
// The parser should handle this gracefully.
|
||||
let _ = events;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_emitted_len_inside_multibyte_char_boundary() {
|
||||
// More direct reproduction: emitted_len points inside a multi-byte character.
|
||||
//
|
||||
// This can happen when:
|
||||
// 1. First partial has text where byte N is a valid boundary
|
||||
// 2. Second partial has *different* text where byte N is inside a multi-byte char
|
||||
let mut parser = StreamingParser::default();
|
||||
|
||||
// First partial: "ab" (2 bytes), backslash held back.
|
||||
// After processing: emitted_len = 2
|
||||
let events = parser.push_edits(&[PartialEdit {
|
||||
old_text: Some("ab\\".into()),
|
||||
new_text: None,
|
||||
}]);
|
||||
assert_eq!(
|
||||
events.as_slice(),
|
||||
&[EditEvent::OldTextChunk {
|
||||
edit_index: 0,
|
||||
chunk: "ab".into(),
|
||||
done: false,
|
||||
}]
|
||||
);
|
||||
|
||||
// Second partial: "a—" where em-dash starts at byte 1 and spans bytes 1-3.
|
||||
// Stored emitted_len = 2, but byte 2 is inside the em-dash!
|
||||
// This should NOT panic.
|
||||
let events = parser.push_edits(&[PartialEdit {
|
||||
old_text: Some("a—".into()),
|
||||
new_text: None,
|
||||
}]);
|
||||
// The parser should handle this gracefully.
|
||||
// We don't care exactly what it emits, just that it doesn't panic.
|
||||
let _ = events;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -361,7 +361,7 @@ impl EditToolTest {
|
|||
abs_path: Path::new("/path/to/root").into(),
|
||||
rules_file: None,
|
||||
}];
|
||||
let project_context = ProjectContext::new(worktrees, Vec::default());
|
||||
let project_context = ProjectContext::new(worktrees);
|
||||
let tool_names = tools
|
||||
.iter()
|
||||
.map(|tool| tool.name.clone().into())
|
||||
|
|
@ -372,6 +372,7 @@ impl EditToolTest {
|
|||
model_name: None,
|
||||
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
template.render(&templates)?
|
||||
|
|
|
|||
|
|
@ -220,7 +220,7 @@ impl TerminalToolTest {
|
|||
abs_path: Path::new("/path/to/root").into(),
|
||||
rules_file: None,
|
||||
}];
|
||||
let project_context = ProjectContext::new(worktrees, Vec::default());
|
||||
let project_context = ProjectContext::new(worktrees);
|
||||
let tool_names = tools
|
||||
.iter()
|
||||
.map(|tool| tool.name.clone().into())
|
||||
|
|
@ -231,6 +231,7 @@ impl TerminalToolTest {
|
|||
model_name: None,
|
||||
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
template.render(&Templates::new())?
|
||||
};
|
||||
|
|
|
|||
|
|
@ -191,7 +191,7 @@ impl WriteToolTest {
|
|||
abs_path: Path::new("/path/to/root").into(),
|
||||
rules_file: None,
|
||||
}];
|
||||
let project_context = ProjectContext::new(worktrees, Vec::default());
|
||||
let project_context = ProjectContext::new(worktrees);
|
||||
let tool_names = tools
|
||||
.iter()
|
||||
.map(|tool| tool.name.clone().into())
|
||||
|
|
@ -202,6 +202,7 @@ impl WriteToolTest {
|
|||
model_name: None,
|
||||
date: chrono::Local::now().format("%Y-%m-%d").to_string(),
|
||||
user_agents_md: None,
|
||||
sandboxing: false,
|
||||
};
|
||||
let templates = Templates::new();
|
||||
template.render(&templates)?
|
||||
|
|
|
|||
|
|
@ -18,11 +18,13 @@ use std::sync::Arc;
|
|||
use util::markdown::MarkdownInlineCode;
|
||||
|
||||
/// Lists files and directories in a given path. Prefer the `grep` or `find_path` tools when searching the codebase.
|
||||
///
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ListDirectoryToolInput {
|
||||
/// The fully-qualified path of the directory to list in the project.
|
||||
///
|
||||
/// This path should never be absolute, and the first component of the path should always be a root directory in a project.
|
||||
/// This path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill directory under `~/.agents/skills`.
|
||||
///
|
||||
/// <example>
|
||||
/// If the project has the following root directories:
|
||||
|
|
@ -41,6 +43,10 @@ pub struct ListDirectoryToolInput {
|
|||
///
|
||||
/// If you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To list a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.
|
||||
/// </example>
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
|
|
@ -234,7 +240,7 @@ impl AgentTool for ListDirectoryTool {
|
|||
|
||||
// Fast path: a global skill resource lives outside any worktree, so
|
||||
// standard project-path resolution would refuse it. If the path
|
||||
// resolves under the global skills tree, list it directly.
|
||||
// expands and resolves under the global skills tree, list it directly.
|
||||
if let Some(skill_path) =
|
||||
resolve_global_skill_path(Path::new(&input.path), fs.as_ref()).await
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
use super::tool_permissions::{
|
||||
authorize_symlink_escapes, canonicalize_worktree_roots, collect_symlink_escapes,
|
||||
sensitive_settings_kind,
|
||||
resolve_creatable_global_skill_descendant_path, resolve_global_skill_descendant_path,
|
||||
resolves_to_global_skills_dir, sensitive_settings_kind,
|
||||
};
|
||||
use crate::{
|
||||
AgentTool, ToolCallEventStream, ToolInput, ToolPermissionDecision,
|
||||
|
|
@ -22,6 +23,7 @@ use util::markdown::MarkdownInlineCode;
|
|||
/// If the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move.
|
||||
///
|
||||
/// This tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.
|
||||
/// The only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct MovePathToolInput {
|
||||
/// The source path of the file or directory to move/rename.
|
||||
|
|
@ -116,6 +118,28 @@ impl AgentTool for MovePathTool {
|
|||
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
|
||||
let canonical_roots = canonicalize_worktree_roots(&project, &fs, cx).await;
|
||||
|
||||
if resolves_to_global_skills_dir(Path::new(&input.source_path), fs.as_ref()).await
|
||||
|| resolves_to_global_skills_dir(
|
||||
Path::new(&input.destination_path),
|
||||
fs.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Err(
|
||||
"Cannot move the global agent skills directory itself. Move a skill directory or file beneath it instead."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let global_source_path =
|
||||
resolve_global_skill_descendant_path(Path::new(&input.source_path), fs.as_ref())
|
||||
.await;
|
||||
let global_destination_path = resolve_creatable_global_skill_descendant_path(
|
||||
Path::new(&input.destination_path),
|
||||
fs.as_ref(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let symlink_escapes: Vec<(&str, std::path::PathBuf)> =
|
||||
project.read_with(cx, |project, cx| {
|
||||
collect_symlink_escapes(
|
||||
|
|
@ -176,6 +200,65 @@ impl AgentTool for MovePathTool {
|
|||
authorize.await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if global_source_path.is_some() || global_destination_path.is_some() {
|
||||
let source_path = if let Some(global_source_path) = global_source_path {
|
||||
global_source_path
|
||||
} else {
|
||||
project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&input.source_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} was not found in the project.", input.source_path)
|
||||
})?;
|
||||
project.entry_for_path(&project_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} was not found in the project.", input.source_path)
|
||||
})?;
|
||||
project.absolute_path(&project_path, cx).ok_or_else(|| {
|
||||
format!("Source path {} could not be resolved.", input.source_path)
|
||||
})
|
||||
})?
|
||||
};
|
||||
|
||||
let destination_path = if let Some(global_destination_path) = global_destination_path
|
||||
{
|
||||
global_destination_path
|
||||
} else {
|
||||
project.read_with(cx, |project, cx| {
|
||||
let project_path = project.find_project_path(&input.destination_path, cx).ok_or_else(|| {
|
||||
format!(
|
||||
"Destination path {} was outside the project.",
|
||||
input.destination_path
|
||||
)
|
||||
})?;
|
||||
project.absolute_path(&project_path, cx).ok_or_else(|| {
|
||||
format!(
|
||||
"Destination path {} could not be resolved.",
|
||||
input.destination_path
|
||||
)
|
||||
})
|
||||
})?
|
||||
};
|
||||
|
||||
futures::select! {
|
||||
result = fs.rename(
|
||||
&source_path,
|
||||
&destination_path,
|
||||
fs::RenameOptions {
|
||||
create_parents: true,
|
||||
..fs::RenameOptions::default()
|
||||
},
|
||||
).fuse() => {
|
||||
result.map_err(|e| format!("Moving {} to {}: {e}", input.source_path, input.destination_path))?;
|
||||
}
|
||||
_ = event_stream.cancelled_by_user().fuse() => {
|
||||
return Err("Move cancelled by user".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(format!(
|
||||
"Moved {} to {}",
|
||||
input.source_path, input.destination_path
|
||||
));
|
||||
}
|
||||
|
||||
let rename_task = project.update(cx, |project, cx| {
|
||||
match project
|
||||
.find_project_path(&input.source_path, cx)
|
||||
|
|
@ -232,6 +315,125 @@ mod tests {
|
|||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_move_path_global_skill_directory_to_project(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root/project"), json!({})).await;
|
||||
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({ "SKILL.md": "content" }))
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(MovePathTool::new(project));
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let destination_path = path!("/root/project/my-skill").to_string();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(MovePathToolInput {
|
||||
source_path: input_path,
|
||||
destination_path,
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should move after approval: {result:?}");
|
||||
assert!(!fs.is_dir(&skill_dir).await);
|
||||
assert_eq!(
|
||||
fs.load(path!("/root/project/my-skill/SKILL.md").as_ref())
|
||||
.await
|
||||
.unwrap(),
|
||||
"content"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_move_path_project_directory_to_global_skill_directory(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/root/project"),
|
||||
json!({ "exported-skill": { "SKILL.md": "content" } }),
|
||||
)
|
||||
.await;
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_dir(&skills_dir).await.unwrap();
|
||||
let project = Project::test(fs.clone(), [path!("/root/project").as_ref()], cx).await;
|
||||
cx.executor().run_until_parked();
|
||||
|
||||
let tool = Arc::new(MovePathTool::new(project));
|
||||
let destination_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("exported-skill")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
tool.run(
|
||||
ToolInput::resolved(MovePathToolInput {
|
||||
source_path: path!("/root/project/exported-skill").to_string(),
|
||||
destination_path,
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let result = task.await;
|
||||
assert!(result.is_ok(), "should move after approval: {result:?}");
|
||||
assert!(
|
||||
!fs.is_dir(path!("/root/project/exported-skill").as_ref())
|
||||
.await
|
||||
);
|
||||
assert_eq!(
|
||||
fs.load(skills_dir.join("exported-skill").join("SKILL.md").as_ref())
|
||||
.await
|
||||
.unwrap(),
|
||||
"content"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_move_path_symlink_escape_source_requests_authorization(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
|
|
@ -18,6 +18,80 @@ fn tool_content_err(e: impl std::fmt::Display) -> LanguageModelToolResultContent
|
|||
LanguageModelToolResultContent::from(e.to_string())
|
||||
}
|
||||
|
||||
/// Resolves the optional `start_line` / `end_line` inputs from the tool schema
|
||||
/// to a concrete 1-indexed, inclusive `(start, end)` line range:
|
||||
///
|
||||
/// - `start` defaults to 1 and is clamped to `>= 1` (the model occasionally passes
|
||||
/// `0` despite instructions to be 1-indexed).
|
||||
/// - `end` defaults to `u32::MAX` and is clamped to `>= start`, so callers always
|
||||
/// read at least one line even when the model passes `end < start`.
|
||||
///
|
||||
/// Callers translate this 1-indexed inclusive range to whichever coordinate
|
||||
/// system their slicing API wants (e.g. 0-indexed exclusive row ranges for
|
||||
/// `Buffer::text_for_range`).
|
||||
fn resolve_line_range(start_line: Option<u32>, end_line: Option<u32>) -> (u32, u32) {
|
||||
let start = start_line.unwrap_or(1).max(1);
|
||||
let end = end_line.unwrap_or(u32::MAX).max(start);
|
||||
(start, end)
|
||||
}
|
||||
|
||||
/// Prefixes each line of `text` with its line number in `cat -n` format:
|
||||
/// the line number is right-aligned in a 6-character field, followed by a
|
||||
/// single tab, followed by the line's original content (including its
|
||||
/// trailing newline if present). Numbering starts at `start_line`.
|
||||
///
|
||||
/// This format matches what the model expects in the edit tool, where the
|
||||
/// line number prefix is `line number + tab` and everything after the tab is
|
||||
/// the actual file content to match.
|
||||
fn format_with_line_numbers(text: &str, start_line: u32) -> String {
|
||||
if text.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut output = String::with_capacity(text.len() + text.len() / 4);
|
||||
write_lines_numbered(&mut output, std::iter::once(text), start_line);
|
||||
output
|
||||
}
|
||||
|
||||
/// Streams `cat -n`-style line-numbered output directly into `output` from an
|
||||
/// iterator of string slices. Chunks do not need to align to line boundaries:
|
||||
/// a single chunk may contain multiple newlines, span multiple lines, or end
|
||||
/// mid-line. This lets callers consume `Buffer::text_for_range`'s `Chunks`
|
||||
/// iterator without materializing the unnumbered text first.
|
||||
fn write_lines_numbered<'a>(
|
||||
output: &mut String,
|
||||
chunks: impl IntoIterator<Item = &'a str>,
|
||||
start_line: u32,
|
||||
) {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
let mut line_number = start_line;
|
||||
let mut at_line_start = true;
|
||||
for chunk in chunks {
|
||||
let mut rest = chunk;
|
||||
while !rest.is_empty() {
|
||||
if at_line_start {
|
||||
// Writes to a `String` are infallible, so the `Result` can be ignored.
|
||||
let _ = write!(output, "{line_number:>6}\t");
|
||||
at_line_start = false;
|
||||
}
|
||||
match rest.find('\n') {
|
||||
Some(nl) => {
|
||||
let (head, tail) = rest.split_at(nl + 1);
|
||||
output.push_str(head);
|
||||
line_number = line_number.saturating_add(1);
|
||||
at_line_start = true;
|
||||
rest = tail;
|
||||
}
|
||||
None => {
|
||||
output.push_str(rest);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a file under the global skills directory directly via the filesystem,
|
||||
/// bypassing project/worktree resolution. Used for skill resources that live
|
||||
/// outside any worktree.
|
||||
|
|
@ -40,26 +114,21 @@ async fn read_global_skill_file(
|
|||
.line(start_line.map(|line| line.saturating_sub(1))),
|
||||
]));
|
||||
|
||||
let result_text = if start_line.is_some() || end_line.is_some() {
|
||||
// Mirror the line-range semantics of the buffer-backed path: 1-indexed,
|
||||
// start clamped to >= 1, end exclusive of the next line, and always
|
||||
// returning at least one line. `split_inclusive` keeps each line's
|
||||
// terminator attached, so CRLF stays CRLF and the trailing newline of
|
||||
// the last returned line is preserved — matching `Buffer::text_for_range`.
|
||||
let start = start_line.unwrap_or(1).max(1);
|
||||
let mut end = end_line.unwrap_or(u32::MAX);
|
||||
if end < start {
|
||||
end = start;
|
||||
}
|
||||
|
||||
let (raw_text, first_line_number) = if start_line.is_some() || end_line.is_some() {
|
||||
// `split_inclusive` keeps each line's terminator attached, so CRLF stays
|
||||
// CRLF and the trailing newline of the last returned line is preserved —
|
||||
// matching `Buffer::text_for_range` in the buffer-backed path.
|
||||
let (start, end) = resolve_line_range(start_line, end_line);
|
||||
let lines: Vec<&str> = content.split_inclusive('\n').collect();
|
||||
let start_idx = (start as usize).saturating_sub(1).min(lines.len());
|
||||
let end_idx = (end as usize).min(lines.len()).max(start_idx);
|
||||
lines[start_idx..end_idx].concat()
|
||||
(lines[start_idx..end_idx].concat(), start)
|
||||
} else {
|
||||
content
|
||||
(content, 1)
|
||||
};
|
||||
|
||||
let result_text = format_with_line_numbers(&raw_text, first_line_number);
|
||||
|
||||
let markdown = MarkdownCodeBlock {
|
||||
tag: requested_path,
|
||||
text: &result_text,
|
||||
|
|
@ -86,11 +155,13 @@ use crate::{AgentTool, ToolCallEventStream, ToolInput, outline};
|
|||
/// Do NOT retry reading the same file without line numbers if you receive an outline.
|
||||
/// - This tool supports reading image files. Supported formats: PNG, JPEG, WebP, GIF, BMP, TIFF.
|
||||
/// Image files are returned as visual content that you can analyze directly.
|
||||
///
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ReadFileToolInput {
|
||||
/// The relative path of the file to read.
|
||||
///
|
||||
/// This path should never be absolute, and the first component of the path should always be a root directory in a project.
|
||||
/// This path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill under `~/.agents/skills`.
|
||||
///
|
||||
/// <example>
|
||||
/// If the project has the following root directories:
|
||||
|
|
@ -101,6 +172,10 @@ pub struct ReadFileToolInput {
|
|||
/// If you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.
|
||||
/// If you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To read a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
|
||||
/// </example>
|
||||
pub path: String,
|
||||
/// Optional line number to start reading on (1-based index)
|
||||
#[serde(default)]
|
||||
|
|
@ -182,8 +257,8 @@ impl AgentTool for ReadFileTool {
|
|||
.map_err(tool_content_err)?;
|
||||
let fs = project.read_with(cx, |project, _cx| project.fs().clone());
|
||||
|
||||
// Fast path: if the model passes an absolute path that resolves
|
||||
// under the global skills directory, read it directly via the
|
||||
// Fast path: if the model passes a path that resolves under the
|
||||
// global skills directory, read it directly via the
|
||||
// filesystem. Global skills live outside any worktree, so the
|
||||
// standard project-path machinery would refuse them.
|
||||
if let Some(skill_path) =
|
||||
|
|
@ -338,32 +413,42 @@ impl AgentTool for ReadFileTool {
|
|||
}
|
||||
|
||||
let mut anchor = None;
|
||||
let mut is_outline_response = false;
|
||||
|
||||
// Check if specific line ranges are provided
|
||||
let result = if input.start_line.is_some() || input.end_line.is_some() {
|
||||
let result = buffer.read_with(cx, |buffer, _cx| {
|
||||
// .max(1) because despite instructions to be 1-indexed, sometimes the model passes 0.
|
||||
let start = input.start_line.unwrap_or(1).max(1);
|
||||
let result_text = buffer.read_with(cx, |buffer, _cx| {
|
||||
let (start, end) = resolve_line_range(input.start_line, input.end_line);
|
||||
let start_row = start - 1;
|
||||
if start_row <= buffer.max_point().row {
|
||||
let column = buffer.line_indent_for_row(start_row).raw_len();
|
||||
anchor = Some(buffer.anchor_before(Point::new(start_row, column)));
|
||||
}
|
||||
|
||||
let mut end_row = input.end_line.unwrap_or(u32::MAX);
|
||||
if end_row <= start_row {
|
||||
end_row = start_row + 1; // read at least one lines
|
||||
}
|
||||
let start = buffer.anchor_before(Point::new(start_row, 0));
|
||||
let end = buffer.anchor_before(Point::new(end_row, 0));
|
||||
buffer.text_for_range(start..end).collect::<String>()
|
||||
// `end` is 1-indexed inclusive; `Point` rows are 0-indexed.
|
||||
// Using `end` directly as the (exclusive) end row is the
|
||||
// standard inclusive→exclusive translation, and since
|
||||
// `resolve_line_range` guarantees `end >= start`, we always
|
||||
// read at least one line.
|
||||
let start_anchor = buffer.anchor_before(Point::new(start_row, 0));
|
||||
let end_anchor = buffer.anchor_before(Point::new(end, 0));
|
||||
// Stream the numbered output directly from the buffer's
|
||||
// chunk iterator so the unnumbered range is never
|
||||
// materialized as its own `String`.
|
||||
let mut output = String::new();
|
||||
write_lines_numbered(
|
||||
&mut output,
|
||||
buffer.text_for_range(start_anchor..end_anchor),
|
||||
start,
|
||||
);
|
||||
output
|
||||
});
|
||||
|
||||
action_log.update(cx, |log, cx| {
|
||||
log.buffer_read(buffer.clone(), cx);
|
||||
});
|
||||
|
||||
Ok(result.into())
|
||||
Ok(result_text.into())
|
||||
} else {
|
||||
// No line ranges specified, so check file size to see if it's too big.
|
||||
let buffer_content = outline::get_buffer_content_or_outline(
|
||||
|
|
@ -377,7 +462,10 @@ impl AgentTool for ReadFileTool {
|
|||
log.buffer_read(buffer.clone(), cx);
|
||||
});
|
||||
|
||||
if buffer_content.is_outline {
|
||||
|
||||
is_outline_response = buffer_content.is_synthetic;
|
||||
|
||||
if buffer_content.is_synthetic {
|
||||
Ok(formatdoc! {"
|
||||
SUCCESS: File outline retrieved. This file is too large to read all at once, so the outline below shows the file's structure with line numbers.
|
||||
|
||||
|
|
@ -391,7 +479,7 @@ impl AgentTool for ReadFileTool {
|
|||
}
|
||||
.into())
|
||||
} else {
|
||||
Ok(buffer_content.text.into())
|
||||
Ok(format_with_line_numbers(&buffer_content.text, 1).into())
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -409,11 +497,12 @@ impl AgentTool for ReadFileTool {
|
|||
}
|
||||
if let Ok(LanguageModelToolResultContent::Text(text)) = &result {
|
||||
let text: &str = text;
|
||||
let markdown = MarkdownCodeBlock {
|
||||
tag: &input.path,
|
||||
text,
|
||||
}
|
||||
.to_string();
|
||||
// For outline responses, omit the path tag so the markdown renderer
|
||||
// does not invoke tree-sitter syntax highlighting against pseudo-code
|
||||
// outline text. The outline is not valid source for the file's language,
|
||||
// so highlighting would be both expensive and incorrect.
|
||||
let tag: &str = if is_outline_response { "" } else { &input.path };
|
||||
let markdown = MarkdownCodeBlock { tag, text }.to_string();
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
|
||||
acp::ToolCallContent::Content(acp::Content::new(markdown)),
|
||||
]));
|
||||
|
|
@ -423,6 +512,27 @@ impl AgentTool for ReadFileTool {
|
|||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn replay(
|
||||
&self,
|
||||
input: Self::Input,
|
||||
output: Self::Output,
|
||||
event_stream: ToolCallEventStream,
|
||||
_cx: &mut App,
|
||||
) -> Result<()> {
|
||||
if let LanguageModelToolResultContent::Text(text) = output {
|
||||
let markdown = MarkdownCodeBlock {
|
||||
tag: &input.path,
|
||||
text: &text,
|
||||
}
|
||||
.to_string();
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![
|
||||
acp::ToolCallContent::Content(acp::Content::new(markdown)),
|
||||
]));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -526,7 +636,10 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "This is a small file content".into());
|
||||
assert_eq!(
|
||||
result.unwrap(),
|
||||
" 1\tThis is a small file content".into()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -610,6 +723,131 @@ mod test {
|
|||
);
|
||||
}
|
||||
|
||||
// The outline returned for a large file is not valid source for the file's
|
||||
// language, so the UI-side markdown wrapping must omit the path tag.
|
||||
// Otherwise the markdown renderer routes the fenced block through
|
||||
// `CodeBlockKind::FencedSrc`, resolves the file's language, and runs
|
||||
// tree-sitter against pseudo-code outline text on every paint.
|
||||
#[gpui::test]
|
||||
async fn test_outline_response_uses_untagged_code_block(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/root"),
|
||||
json!({
|
||||
"large_file.rs": (0..1000).map(|i| format!("struct Test{} {{\n a: u32,\n b: usize,\n}}", i)).collect::<Vec<_>>().join("\n")
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
|
||||
let language_registry = project.read_with(cx, |project, _| project.languages().clone());
|
||||
language_registry.add(language::rust_lang());
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(ReadFileTool::new(project, action_log, true));
|
||||
let (event_stream, mut rx) = ToolCallEventStream::test();
|
||||
|
||||
let result = cx
|
||||
.update(|cx| {
|
||||
let input = ReadFileToolInput {
|
||||
path: "root/large_file.rs".into(),
|
||||
start_line: None,
|
||||
end_line: None,
|
||||
};
|
||||
tool.clone()
|
||||
.run(ToolInput::resolved(input), event_stream, cx)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Sanity-check: the file is large enough to trigger the outline branch.
|
||||
assert!(
|
||||
result
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.starts_with("SUCCESS: File outline retrieved."),
|
||||
"expected outline response, got: {:?}",
|
||||
result.to_str().unwrap()
|
||||
);
|
||||
|
||||
// The first update carries the location; the second carries the
|
||||
// markdown content destined for the tool-call UI.
|
||||
let _location_update = rx.expect_update_fields().await;
|
||||
let content_update = rx.expect_update_fields().await;
|
||||
let content_blocks = content_update.content.expect("expected content update");
|
||||
let acp::ToolCallContent::Content(content) = content_blocks
|
||||
.first()
|
||||
.expect("expected at least one content block")
|
||||
else {
|
||||
panic!("expected ContentBlock, got {:?}", content_blocks.first());
|
||||
};
|
||||
let acp::ContentBlock::Text(text) = &content.content else {
|
||||
panic!("expected text content block, got {:?}", content.content);
|
||||
};
|
||||
|
||||
assert!(
|
||||
text.text.starts_with("```\n"),
|
||||
"outline response must use an untagged fenced code block; got first line: {:?}",
|
||||
text.text.lines().next()
|
||||
);
|
||||
assert!(
|
||||
!text.text.starts_with("```root/"),
|
||||
"outline response must not include the file path as a code block tag"
|
||||
);
|
||||
}
|
||||
|
||||
// The full-file (non-outline) response should still tag the code block
|
||||
// with the file path so the markdown renderer can resolve the file's
|
||||
// language for syntax highlighting.
|
||||
#[gpui::test]
|
||||
async fn test_full_file_response_keeps_path_tag(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
path!("/root"),
|
||||
json!({
|
||||
"small_file.rs": "fn main() {}"
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
|
||||
let action_log = cx.new(|_| ActionLog::new(project.clone()));
|
||||
let tool = Arc::new(ReadFileTool::new(project, action_log, true));
|
||||
let (event_stream, mut rx) = ToolCallEventStream::test();
|
||||
|
||||
cx.update(|cx| {
|
||||
let input = ReadFileToolInput {
|
||||
path: "root/small_file.rs".into(),
|
||||
start_line: None,
|
||||
end_line: None,
|
||||
};
|
||||
tool.clone()
|
||||
.run(ToolInput::resolved(input), event_stream, cx)
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let _location_update = rx.expect_update_fields().await;
|
||||
let content_update = rx.expect_update_fields().await;
|
||||
let content_blocks = content_update.content.expect("expected content update");
|
||||
let acp::ToolCallContent::Content(content) = content_blocks
|
||||
.first()
|
||||
.expect("expected at least one content block")
|
||||
else {
|
||||
panic!("expected ContentBlock, got {:?}", content_blocks.first());
|
||||
};
|
||||
let acp::ContentBlock::Text(text) = &content.content else {
|
||||
panic!("expected text content block, got {:?}", content.content);
|
||||
};
|
||||
|
||||
assert!(
|
||||
text.text.starts_with("```root/small_file.rs\n"),
|
||||
"full-file response must tag the code block with the file path; got first line: {:?}",
|
||||
text.text.lines().next()
|
||||
);
|
||||
}
|
||||
|
||||
// When a worktree is named "foo" and contains a subdirectory also named "foo",
|
||||
// read_file({"path": "foo/test.txt"}) should return the file at the worktree
|
||||
// root (as the tool schema promises), not the one inside the foo/ subdirectory.
|
||||
|
|
@ -648,7 +886,7 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "root content".into());
|
||||
assert_eq!(result.unwrap(), " 1\troot content".into());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -681,7 +919,10 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "Line 2\nLine 3\nLine 4\n".into());
|
||||
assert_eq!(
|
||||
result.unwrap(),
|
||||
" 2\tLine 2\n 3\tLine 3\n 4\tLine 4\n".into()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -715,7 +956,7 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "Line 1\nLine 2\n".into());
|
||||
assert_eq!(result.unwrap(), " 1\tLine 1\n 2\tLine 2\n".into());
|
||||
|
||||
// end_line of 0 should result in at least 1 line
|
||||
let result = cx
|
||||
|
|
@ -732,7 +973,7 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "Line 1\n".into());
|
||||
assert_eq!(result.unwrap(), " 1\tLine 1\n".into());
|
||||
|
||||
// when start_line > end_line, should still return at least 1 line
|
||||
let result = cx
|
||||
|
|
@ -749,7 +990,7 @@ mod test {
|
|||
)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "Line 3\n".into());
|
||||
assert_eq!(result.unwrap(), " 3\tLine 3\n".into());
|
||||
}
|
||||
|
||||
fn error_text(content: LanguageModelToolResultContent) -> String {
|
||||
|
|
@ -983,7 +1224,7 @@ mod test {
|
|||
})
|
||||
.await;
|
||||
assert!(result.is_ok(), "Should be able to read normal files");
|
||||
assert_eq!(result.unwrap(), "Normal file content".into());
|
||||
assert_eq!(result.unwrap(), " 1\tNormal file content".into());
|
||||
|
||||
// Path traversal attempts with .. should fail
|
||||
let result = cx
|
||||
|
|
@ -1153,7 +1394,7 @@ mod test {
|
|||
|
||||
assert_eq!(
|
||||
result,
|
||||
"fn main() { println!(\"Hello from worktree1\"); }".into()
|
||||
" 1\tfn main() { println!(\"Hello from worktree1\"); }".into()
|
||||
);
|
||||
|
||||
// Test reading private file in worktree1 should fail
|
||||
|
|
@ -1219,7 +1460,7 @@ mod test {
|
|||
|
||||
assert_eq!(
|
||||
result,
|
||||
"export function greet() { return 'Hello from worktree2'; }".into()
|
||||
" 1\texport function greet() { return 'Hello from worktree2'; }".into()
|
||||
);
|
||||
|
||||
// Test reading private file in worktree2 should fail
|
||||
|
|
@ -1529,7 +1770,10 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = content else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "# Spec\n\nReference body.");
|
||||
assert_eq!(
|
||||
text.as_ref(),
|
||||
" 1\t# Spec\n 2\t\n 3\tReference body."
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1576,7 +1820,7 @@ mod test {
|
|||
};
|
||||
// Mirrors the buffer-backed path: lines 2-3 inclusive, WITH trailing
|
||||
// newline of the last returned line.
|
||||
assert_eq!(text.as_ref(), "line two\nline three\n");
|
||||
assert_eq!(text.as_ref(), " 2\tline two\n 3\tline three\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1621,7 +1865,7 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "Line 1\nLine 2\n");
|
||||
assert_eq!(text.as_ref(), " 1\tLine 1\n 2\tLine 2\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1666,7 +1910,7 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "Line 1\n");
|
||||
assert_eq!(text.as_ref(), " 1\tLine 1\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1711,7 +1955,7 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "Line 3\n");
|
||||
assert_eq!(text.as_ref(), " 3\tLine 3\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
@ -1756,7 +2000,7 @@ mod test {
|
|||
let LanguageModelToolResultContent::Text(text) = result.unwrap() else {
|
||||
panic!("expected text content");
|
||||
};
|
||||
assert_eq!(text.as_ref(), "line one\r\nline two\r\n");
|
||||
assert_eq!(text.as_ref(), " 1\tline one\r\n 2\tline two\r\n");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ use std::fmt::Write;
|
|||
use std::sync::Arc;
|
||||
|
||||
use agent_client_protocol::schema as acp;
|
||||
use collections::HashSet;
|
||||
use gpui::{App, Entity, SharedString, Task};
|
||||
use project::Project;
|
||||
use schemars::JsonSchema;
|
||||
|
|
@ -95,6 +96,12 @@ impl AgentTool for RenameTool {
|
|||
));
|
||||
}
|
||||
|
||||
let buffers = transaction.0.keys().cloned().collect::<HashSet<_>>();
|
||||
project
|
||||
.update(cx, |project, cx| project.save_buffers(buffers, cx))
|
||||
.await
|
||||
.map_err(|e| format!("Rename succeeded, but failed to save renamed files: {e}"))?;
|
||||
|
||||
let mut output = format!(
|
||||
"Renamed `{}` to `{}` in {} file(s):\n",
|
||||
input.symbol.symbol_name,
|
||||
|
|
|
|||
|
|
@ -46,11 +46,12 @@ fn neutralize_envelope_tags(input: &str) -> String {
|
|||
/// frontmatter), not O(total file size).
|
||||
pub fn render_skill_envelope(skill: &Skill, body: &str) -> String {
|
||||
let source = match &skill.source {
|
||||
agent_skills::SkillSource::BuiltIn => "built-in",
|
||||
agent_skills::SkillSource::Global => "global",
|
||||
agent_skills::SkillSource::ProjectLocal { .. } => "project-local",
|
||||
};
|
||||
let worktree = match &skill.source {
|
||||
agent_skills::SkillSource::Global => None,
|
||||
agent_skills::SkillSource::BuiltIn | agent_skills::SkillSource::Global => None,
|
||||
agent_skills::SkillSource::ProjectLocal {
|
||||
worktree_root_name, ..
|
||||
} => Some(worktree_root_name.clone()),
|
||||
|
|
@ -200,31 +201,33 @@ impl AgentTool for SkillTool {
|
|||
(skill.clone(), path_string)
|
||||
};
|
||||
|
||||
// Read the body on demand. Bodies are not kept in memory
|
||||
// between materializations — see `agent_skills::read_skill_body`.
|
||||
let body = agent_skills::read_skill_body(self.fs.as_ref(), &skill.skill_file_path)
|
||||
.await
|
||||
.map_err(|e| SkillToolOutput::Error {
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
// For built-in skills the body is already in memory (compiled
|
||||
// into the binary). For user skills, read on demand from disk.
|
||||
let body = if let Some(embedded) = skill.embedded_body {
|
||||
embedded.to_string()
|
||||
} else {
|
||||
agent_skills::read_skill_body(self.fs.as_ref(), &skill.skill_file_path)
|
||||
.await
|
||||
.map_err(|e| SkillToolOutput::Error {
|
||||
error: e.to_string(),
|
||||
})?
|
||||
};
|
||||
let rendered = render_skill_envelope(&skill, &body);
|
||||
|
||||
// Activations go through the standard tool-permission flow so
|
||||
// they participate in the same Allow-Once / Always-Allow UX as
|
||||
// every other built-in tool. The auth context value is the
|
||||
// skill's absolute SKILL.md path so that "always allow this
|
||||
// specific skill" is keyed to a specific file: editing the
|
||||
// SKILL.md will change the path's content but not the path,
|
||||
// so for content-change re-trust we'd want a hash too — but
|
||||
// at minimum, two skills with the same name from different
|
||||
// locations get independent trust grants.
|
||||
let authorize = cx.update(|cx| {
|
||||
let context = crate::ToolPermissionContext::new(Self::NAME, vec![skill_file_path]);
|
||||
event_stream.authorize(self.initial_title(Ok(input), cx), context, cx)
|
||||
});
|
||||
authorize.await.map_err(|e| SkillToolOutput::Error {
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
// Built-in skills ship with Zed and are trusted by default,
|
||||
// so they skip the authorization prompt. User-installed skills
|
||||
// go through the standard Allow-Once / Always-Allow UX.
|
||||
let is_builtin = skill.source == agent_skills::SkillSource::BuiltIn;
|
||||
if !is_builtin {
|
||||
let authorize = cx.update(|cx| {
|
||||
let context =
|
||||
crate::ToolPermissionContext::new(Self::NAME, vec![skill_file_path]);
|
||||
event_stream.authorize(self.initial_title(Ok(input), cx), context, cx)
|
||||
});
|
||||
authorize.await.map_err(|e| SkillToolOutput::Error {
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(SkillToolOutput::Found { rendered })
|
||||
})
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ use std::{
|
|||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::sandboxing::sandboxing_enabled;
|
||||
use crate::{AgentTool, ThreadEnvironment, ToolCallEventStream, ToolInput};
|
||||
|
||||
const COMMAND_OUTPUT_LIMIT: u64 = 16 * 1024;
|
||||
|
|
@ -39,7 +40,7 @@ const COMMAND_OUTPUT_LIMIT: u64 = 16 * 1024;
|
|||
/// - Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`).
|
||||
/// - Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`).
|
||||
/// - For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct TerminalToolInput {
|
||||
/// The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user.
|
||||
///
|
||||
|
|
@ -49,6 +50,35 @@ pub struct TerminalToolInput {
|
|||
pub cd: String,
|
||||
/// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.
|
||||
pub timeout_ms: Option<u64>,
|
||||
/// Request network access for this command.
|
||||
///
|
||||
/// Only meaningful when the system prompt's "Terminal sandbox" section
|
||||
/// is present — ignored otherwise. By default sandboxed commands
|
||||
/// cannot make outbound network connections; set this to `true` only
|
||||
/// when the command needs network access. The user will be prompted
|
||||
/// to approve before the command runs.
|
||||
#[serde(default)]
|
||||
pub allow_network: Option<bool>,
|
||||
/// Request unrestricted filesystem-write access for this command.
|
||||
///
|
||||
/// Only meaningful when the system prompt's "Terminal sandbox" section
|
||||
/// is present — ignored otherwise. By default sandboxed commands can
|
||||
/// only write to the project worktree directories and a per-command
|
||||
/// temporary directory; set this to `true` only when the command
|
||||
/// needs to write elsewhere. The user will be prompted to approve
|
||||
/// before the command runs.
|
||||
#[serde(default)]
|
||||
pub allow_fs_write: Option<bool>,
|
||||
/// Request to run this command outside the sandbox entirely.
|
||||
///
|
||||
/// Only meaningful when the system prompt's "Terminal sandbox" section
|
||||
/// is present — ignored otherwise. Prefer `allow_network: true` or
|
||||
/// `allow_fs_write: true` when one of those is enough. Set this to
|
||||
/// `true` ONLY when the command needs behavior that the sandbox can't
|
||||
/// grant on a per-permission basis. The user will be prompted to
|
||||
/// approve before the command runs without sandbox restrictions.
|
||||
#[serde(default)]
|
||||
pub unsandboxed: Option<bool>,
|
||||
}
|
||||
|
||||
pub struct TerminalTool {
|
||||
|
|
@ -96,24 +126,100 @@ impl AgentTool for TerminalTool {
|
|||
cx.spawn(async move |cx| {
|
||||
let input = input.recv().await.map_err(|e| e.to_string())?;
|
||||
|
||||
let (working_dir, authorize) = cx.update(|cx| {
|
||||
let (working_dir, authorize, sandboxing) = cx.update(|cx| {
|
||||
let working_dir =
|
||||
working_dir(&input, &self.project, cx).map_err(|err| err.to_string())?;
|
||||
let context =
|
||||
crate::ToolPermissionContext::new(Self::NAME, vec![input.command.clone()]);
|
||||
let authorize =
|
||||
event_stream.authorize(self.initial_title(Ok(input.clone()), cx), context, cx);
|
||||
Result::<_, String>::Ok((working_dir, authorize))
|
||||
let sandboxing = sandboxing_enabled(cx);
|
||||
Result::<_, String>::Ok((working_dir, authorize, sandboxing))
|
||||
})?;
|
||||
|
||||
authorize.await.map_err(|e| e.to_string())?;
|
||||
|
||||
// Sandbox flags only do anything when sandboxing is on. When
|
||||
// off, we treat them as `None` so the model can't surreptitiously
|
||||
// change runtime behavior by setting flags described as a no-op
|
||||
// in the system prompt.
|
||||
let want_network = sandboxing && input.allow_network == Some(true);
|
||||
let want_fs_write = sandboxing && input.allow_fs_write == Some(true);
|
||||
let want_unsandboxed = sandboxing && input.unsandboxed == Some(true);
|
||||
|
||||
// `unsandboxed: true` bypasses the wrap entirely; per-permission
|
||||
// requests are only meaningful when the command is still being
|
||||
// sandboxed.
|
||||
let escalate = !want_unsandboxed && (want_network || want_fs_write);
|
||||
|
||||
if want_unsandboxed || escalate {
|
||||
let title = sandbox_approval_title(want_network, want_fs_write, want_unsandboxed);
|
||||
let approve = cx.update(|cx| {
|
||||
let context = crate::ToolPermissionContext::new(
|
||||
Self::NAME,
|
||||
vec![input.command.clone()],
|
||||
);
|
||||
// Sandbox escalations always prompt, even if the user
|
||||
// has `always_allow` rules for this command — the
|
||||
// escalation is a stronger trust boundary than the
|
||||
// baseline command approval.
|
||||
event_stream.authorize_always_prompt(title, context, cx)
|
||||
});
|
||||
if let Err(error) = approve.await {
|
||||
return Ok(if want_unsandboxed {
|
||||
format!(
|
||||
"Command cancelled: user denied permission to run outside the sandbox ({error})."
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Command cancelled: user denied the requested sandbox permissions ({error})."
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// The per-thread scratch directory (and the `$TMPDIR`/`TMP`/
|
||||
// `TEMP` environment variables pointing at it) is provisioned by
|
||||
// the thread environment in `create_terminal`, which also adds it
|
||||
// to the sandbox's writable scope. We must not set `$TMPDIR` here:
|
||||
// the environment overrides it with the per-thread directory, so a
|
||||
// per-command directory set here would never be the `$TMPDIR` the
|
||||
// command actually sees and would be left out of the writable
|
||||
// scope, breaking writes into `$TMPDIR`.
|
||||
let extra_env = Vec::new();
|
||||
|
||||
// Build the writable scope from the project's worktrees. The
|
||||
// per-thread temp directory is appended by the thread environment
|
||||
// (which owns it and points `$TMPDIR` at it). Crucially we do
|
||||
// *not* include the resolved `cd` working directory — that's
|
||||
// model-controlled, and using it as the writable scope would
|
||||
// let the model widen its own write permissions outside the
|
||||
// project.
|
||||
let sandbox_wrap = if sandboxing && !want_unsandboxed {
|
||||
let writable_paths: Vec<PathBuf> = cx.update(|cx| {
|
||||
self.project
|
||||
.read(cx)
|
||||
.worktrees(cx)
|
||||
.map(|w| w.read(cx).abs_path().to_path_buf())
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
Some(acp_thread::SandboxWrap {
|
||||
writable_paths,
|
||||
allow_network: want_network,
|
||||
allow_fs_write: want_fs_write,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let terminal = self
|
||||
.environment
|
||||
.create_terminal(
|
||||
input.command.clone(),
|
||||
extra_env,
|
||||
working_dir,
|
||||
Some(COMMAND_OUTPUT_LIMIT),
|
||||
sandbox_wrap,
|
||||
cx,
|
||||
)
|
||||
.await
|
||||
|
|
@ -182,6 +288,29 @@ impl AgentTool for TerminalTool {
|
|||
}
|
||||
}
|
||||
|
||||
/// User-facing title for the sandbox-escalation approval prompt.
|
||||
///
|
||||
/// `want_unsandboxed` wins over the per-permission flags because
|
||||
/// `unsandboxed: true` bypasses the per-permission machinery entirely.
|
||||
fn sandbox_approval_title(
|
||||
want_network: bool,
|
||||
want_fs_write: bool,
|
||||
want_unsandboxed: bool,
|
||||
) -> &'static str {
|
||||
if want_unsandboxed {
|
||||
"Allow this command to run outside the sandbox?"
|
||||
} else {
|
||||
match (want_network, want_fs_write) {
|
||||
(true, true) => "Allow network access and arbitrary filesystem writes?",
|
||||
(true, false) => "Allow network access?",
|
||||
(false, true) => "Allow arbitrary filesystem writes?",
|
||||
// Caller only invokes this when at least one flag is set, so
|
||||
// this fallback is unreachable in practice.
|
||||
(false, false) => "Allow this command to run?",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_content(
|
||||
output: acp::TerminalOutputResponse,
|
||||
command: &str,
|
||||
|
|
@ -310,6 +439,7 @@ mod tests {
|
|||
.to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let title = format_initial_title(Ok(input));
|
||||
|
|
@ -369,6 +499,7 @@ mod tests {
|
|||
command: cmd.to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let title = format_initial_title(Ok(input));
|
||||
|
|
@ -406,6 +537,7 @@ mod tests {
|
|||
command: "echo 'hello world'".to_string(),
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let title = format_initial_title(Ok(input));
|
||||
|
|
@ -435,6 +567,7 @@ mod tests {
|
|||
command: long_command,
|
||||
cd: ".".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let title = format_initial_title(Ok(input));
|
||||
|
|
@ -641,6 +774,7 @@ mod tests {
|
|||
command: "echo $HOME".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -708,6 +842,7 @@ mod tests {
|
|||
command: "echo $HOME".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -769,6 +904,7 @@ mod tests {
|
|||
command: "echo $(rm -rf /)".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -838,6 +974,7 @@ mod tests {
|
|||
command: "PAGER=blah git log --oneline".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -911,6 +1048,7 @@ mod tests {
|
|||
command: "PAGER=blah git log".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1018,6 +1156,7 @@ mod tests {
|
|||
command: command.to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1185,6 +1324,7 @@ mod tests {
|
|||
command: "echo $(whoami)".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1257,6 +1397,7 @@ mod tests {
|
|||
command: "PAGER=other git log".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1323,6 +1464,7 @@ mod tests {
|
|||
command: "A=1 B=2 git log".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1400,6 +1542,7 @@ mod tests {
|
|||
command: "PAGER=\"less -R\" git log".to_string(),
|
||||
cd: "root".to_string(),
|
||||
timeout_ms: None,
|
||||
..Default::default()
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
|
|
@ -1428,4 +1571,72 @@ mod tests {
|
|||
"unexpected terminal result: {result}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_approval_title_unsandboxed_wins() {
|
||||
// `unsandboxed: true` skips the sandbox entirely, so the title should
|
||||
// reflect that even when other flags are also set — they're moot.
|
||||
assert_eq!(
|
||||
sandbox_approval_title(true, true, true),
|
||||
"Allow this command to run outside the sandbox?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(false, false, true),
|
||||
"Allow this command to run outside the sandbox?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_approval_title_per_permission_flags() {
|
||||
assert_eq!(
|
||||
sandbox_approval_title(true, true, false),
|
||||
"Allow network access and arbitrary filesystem writes?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(true, false, false),
|
||||
"Allow network access?"
|
||||
);
|
||||
assert_eq!(
|
||||
sandbox_approval_title(false, true, false),
|
||||
"Allow arbitrary filesystem writes?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_input_schema_includes_sandbox_flags() {
|
||||
// The model only sees these fields when the sandboxing prompt
|
||||
// section is rendered, but they're always present in the schema so
|
||||
// input validation doesn't reject them when sent. Guard against
|
||||
// accidentally renaming or removing them.
|
||||
let schema = serde_json::to_string(&schemars::schema_for!(TerminalToolInput))
|
||||
.expect("input schema should serialize");
|
||||
assert!(
|
||||
schema.contains("allow_network"),
|
||||
"schema should advertise allow_network: {schema}"
|
||||
);
|
||||
assert!(
|
||||
schema.contains("allow_fs_write"),
|
||||
"schema should advertise allow_fs_write: {schema}"
|
||||
);
|
||||
assert!(
|
||||
schema.contains("unsandboxed"),
|
||||
"schema should advertise unsandboxed: {schema}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_flags_default_to_none_when_absent() {
|
||||
// The model is expected to omit the sandbox fields entirely on most
|
||||
// calls. Make sure deserialization doesn't reject the minimal
|
||||
// payload and that the fields default to `None` (which the tool
|
||||
// interprets as "no escalation requested").
|
||||
let input: TerminalToolInput = serde_json::from_value(serde_json::json!({
|
||||
"command": "echo hi",
|
||||
"cd": ".",
|
||||
}))
|
||||
.expect("minimal input should deserialize");
|
||||
assert_eq!(input.allow_network, None);
|
||||
assert_eq!(input.allow_fs_write, None);
|
||||
assert_eq!(input.unsandboxed, None);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,9 +9,9 @@ use fs::Fs;
|
|||
use gpui::{App, Entity, Task, WeakEntity};
|
||||
use project::{Project, ProjectPath};
|
||||
use settings::Settings;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use util::paths::component_matches_ignore_ascii_case;
|
||||
use util::{normalize_path, paths::component_matches_ignore_ascii_case};
|
||||
|
||||
pub enum SensitiveSettingsKind {
|
||||
Local,
|
||||
|
|
@ -116,25 +116,24 @@ fn is_within_any_worktree(canonical_path: &Path, canonical_worktree_roots: &[Pat
|
|||
.any(|root| canonical_path.starts_with(root))
|
||||
}
|
||||
|
||||
/// If `path` is an absolute path under the global skills directory
|
||||
/// (`~/.agents/skills`), return the canonicalized absolute path. Returns
|
||||
/// `None` for any path that resolves outside the global skills tree, for
|
||||
/// relative paths, or if the skills directory itself can't be canonicalized
|
||||
/// (fail closed — better to refuse access than to compare against a
|
||||
/// non-canonical path).
|
||||
/// If `path` names `~/.agents/skills` or one of its descendants, return the
|
||||
/// canonicalized absolute path. Returns `None` for any path that resolves
|
||||
/// outside the global skills tree, for relative paths that don't start with
|
||||
/// `~`, or if the skills directory itself can't be canonicalized (fail closed
|
||||
/// — better to refuse access than to compare against a non-canonical path).
|
||||
///
|
||||
/// This is the gate that lets `read_file` / `list_directory` reach into the
|
||||
/// global skills directory — which lives outside any worktree — without
|
||||
/// also opening up arbitrary external paths.
|
||||
pub async fn resolve_global_skill_path(path: &Path, fs: &dyn Fs) -> Option<PathBuf> {
|
||||
if !path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let normalized_path = resolve_lexical_global_skill_path(path)?;
|
||||
|
||||
// Canonicalize both sides so symlinks and `..` segments can't sneak the
|
||||
// path out of the skills tree (and so different but equivalent path
|
||||
// representations match).
|
||||
let canonical_path = fs.canonicalize(path).await.ok()?;
|
||||
// Canonicalize both sides so symlinks can't sneak the path out of the
|
||||
// skills tree (and so different but equivalent path representations
|
||||
// match). The lexical check above intentionally runs first, so a
|
||||
// symlinked `~/.agents/skills` root can't broaden the allowlist to every
|
||||
// path under the symlink target.
|
||||
let canonical_path = fs.canonicalize(&normalized_path).await.ok()?;
|
||||
let canonical_skills_dir = canonical_global_skills_dir(fs).await?;
|
||||
|
||||
if canonical_path.starts_with(&canonical_skills_dir) {
|
||||
|
|
@ -144,6 +143,112 @@ pub async fn resolve_global_skill_path(path: &Path, fs: &dyn Fs) -> Option<PathB
|
|||
}
|
||||
}
|
||||
|
||||
fn expand_home_prefix(path: &Path) -> Option<PathBuf> {
|
||||
if path.is_absolute() {
|
||||
return Some(path.to_path_buf());
|
||||
}
|
||||
|
||||
let mut components = path.components();
|
||||
let first_component = components.next()?;
|
||||
if !matches!(first_component, Component::Normal(component) if component == "~") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut expanded = paths::home_dir().clone();
|
||||
for component in components {
|
||||
match component {
|
||||
Component::Normal(component) => expanded.push(component),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => expanded.push(".."),
|
||||
Component::Prefix(_) | Component::RootDir => return None,
|
||||
}
|
||||
}
|
||||
Some(expanded)
|
||||
}
|
||||
|
||||
fn expand_and_normalize_absolute_path(path: &Path) -> Option<PathBuf> {
|
||||
let expanded_path = expand_home_prefix(path)?;
|
||||
let normalized_path = normalize_path(&expanded_path);
|
||||
normalized_path.is_absolute().then_some(normalized_path)
|
||||
}
|
||||
|
||||
fn resolve_lexical_global_skill_path(path: &Path) -> Option<PathBuf> {
|
||||
let normalized_path = expand_and_normalize_absolute_path(path)?;
|
||||
let normalized_skills_dir = normalize_path(&agent_skills::global_skills_dir());
|
||||
|
||||
normalized_path
|
||||
.starts_with(&normalized_skills_dir)
|
||||
.then_some(normalized_path)
|
||||
}
|
||||
|
||||
/// If `path` names `~/.agents/skills` or one of its descendants, return a
|
||||
/// canonical absolute path for it. Unlike [`resolve_global_skill_path`], the
|
||||
/// target path may or may not exist on disk yet — the caller decides whether
|
||||
/// to read, write, or create it. Returns `None` for any other path, including
|
||||
/// siblings of the global skills tree or paths that would escape it with `..`
|
||||
/// or symlinks.
|
||||
pub async fn resolve_creatable_global_skill_path(path: &Path, fs: &dyn Fs) -> Option<PathBuf> {
|
||||
let normalized_path = resolve_lexical_global_skill_path(path)?;
|
||||
let canonical_path = canonicalize_with_ancestors(&normalized_path, fs).await?;
|
||||
let canonical_skills_dir = canonical_global_skills_dir(fs).await?;
|
||||
|
||||
if canonical_path.starts_with(&canonical_skills_dir) {
|
||||
Some(canonical_path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn is_strict_descendant(path: &Path, ancestor: &Path) -> bool {
|
||||
path != ancestor && path.starts_with(ancestor)
|
||||
}
|
||||
|
||||
/// Returns whether `path` resolves to the global agent skills directory itself.
|
||||
///
|
||||
/// This is used by destructive tools to reject operations targeting the root
|
||||
/// `~/.agents/skills` directory while still allowing operations on individual
|
||||
/// skills or resources beneath it.
|
||||
pub async fn resolves_to_global_skills_dir(path: &Path, fs: &dyn Fs) -> bool {
|
||||
let Some(normalized_path) = resolve_lexical_global_skill_path(path) else {
|
||||
return false;
|
||||
};
|
||||
let Some(canonical_path) = canonicalize_with_ancestors(&normalized_path, fs).await else {
|
||||
return false;
|
||||
};
|
||||
let Some(canonical_skills_dir) = canonical_global_skills_dir(fs).await else {
|
||||
return false;
|
||||
};
|
||||
|
||||
canonical_path == canonical_skills_dir
|
||||
}
|
||||
|
||||
/// Filters a previously-resolved global skills path so that callers which
|
||||
/// must never act on `~/.agents/skills` itself (move, delete) only see paths
|
||||
/// that point strictly below the skills root.
|
||||
async fn restrict_to_skill_descendant(
|
||||
canonical_path: Option<PathBuf>,
|
||||
fs: &dyn Fs,
|
||||
) -> Option<PathBuf> {
|
||||
let canonical_path = canonical_path?;
|
||||
let canonical_skills_dir = canonical_global_skills_dir(fs).await?;
|
||||
is_strict_descendant(&canonical_path, &canonical_skills_dir).then_some(canonical_path)
|
||||
}
|
||||
|
||||
/// Like [`resolve_global_skill_path`], but only succeeds for paths strictly
|
||||
/// below `~/.agents/skills`, not the skills directory itself.
|
||||
pub async fn resolve_global_skill_descendant_path(path: &Path, fs: &dyn Fs) -> Option<PathBuf> {
|
||||
restrict_to_skill_descendant(resolve_global_skill_path(path, fs).await, fs).await
|
||||
}
|
||||
|
||||
/// Like [`resolve_creatable_global_skill_path`], but only succeeds for paths
|
||||
/// strictly below `~/.agents/skills`, not the skills directory itself.
|
||||
pub async fn resolve_creatable_global_skill_descendant_path(
|
||||
path: &Path,
|
||||
fs: &dyn Fs,
|
||||
) -> Option<PathBuf> {
|
||||
restrict_to_skill_descendant(resolve_creatable_global_skill_path(path, fs).await, fs).await
|
||||
}
|
||||
|
||||
/// Returns the kind of sensitive settings or agent skills location this path targets, if any:
|
||||
/// either inside a `.zed/` local-settings directory, inside `.agents/skills/`, or inside
|
||||
/// the global config dir.
|
||||
|
|
@ -773,6 +878,189 @@ mod tests {
|
|||
roots
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_creatable_global_skill_path_allows_tilde_path(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill");
|
||||
let expected_path = agent_skills::global_skills_dir().join("my-skill");
|
||||
|
||||
let resolved = resolve_creatable_global_skill_path(&input_path, fs.as_ref())
|
||||
.await
|
||||
.expect("global skill path should resolve");
|
||||
|
||||
assert_eq!(resolved, expected_path);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_global_skill_path_allows_tilde_path(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let skill_file = agent_skills::global_skills_dir()
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
fs.insert_tree(
|
||||
skill_file
|
||||
.parent()
|
||||
.expect("skill file should have a parent"),
|
||||
json!({ "SKILL.md": "---\nname: my-skill\ndescription: test\n---" }),
|
||||
)
|
||||
.await;
|
||||
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
let resolved = resolve_global_skill_path(&input_path, fs.as_ref())
|
||||
.await
|
||||
.expect("global skill file should resolve");
|
||||
|
||||
assert_eq!(resolved, skill_file);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_creatable_global_skill_path_rejects_other_home_paths(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let sibling_path = PathBuf::from("~").join(".agents").join("not-skills");
|
||||
let escaped_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("..")
|
||||
.join("not-skills");
|
||||
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&sibling_path, fs.as_ref())
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&escaped_path, fs.as_ref())
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_creatable_global_skill_path_rejects_symlink_escape(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_dir(&skills_dir)
|
||||
.await
|
||||
.expect("global skills directory should be created");
|
||||
fs.create_dir(path!("/external").as_ref())
|
||||
.await
|
||||
.expect("external directory should be created");
|
||||
fs.create_symlink(&skills_dir.join("link"), PathBuf::from(path!("/external")))
|
||||
.await
|
||||
.expect("symlink should be created");
|
||||
|
||||
let escaped_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("link")
|
||||
.join("new-dir");
|
||||
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&escaped_path, fs.as_ref())
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_global_skill_path_resolvers_reject_absolute_paths_when_skills_dir_is_symlink_to_root(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(paths::home_dir(), json!({ ".agents": {} }))
|
||||
.await;
|
||||
fs.insert_tree(path!("/tmp"), json!({ "outside.txt": "outside" }))
|
||||
.await;
|
||||
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_symlink(&skills_dir, PathBuf::from(path!("/")))
|
||||
.await
|
||||
.expect("global skills directory should be symlinked to root");
|
||||
|
||||
let outside_path = PathBuf::from(path!("/tmp/outside.txt"));
|
||||
assert!(
|
||||
resolve_global_skill_path(&outside_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"existing absolute paths outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&outside_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"creatable absolute paths outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
|
||||
let traversed_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("..")
|
||||
.join("outside");
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&traversed_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"paths that normalize outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_global_skill_path_resolvers_reject_absolute_paths_when_skills_dir_is_symlink_to_home(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = FakeFs::new(cx.executor());
|
||||
fs.insert_tree(
|
||||
paths::home_dir(),
|
||||
json!({
|
||||
".agents": {},
|
||||
"outside.txt": "outside",
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let skills_dir = agent_skills::global_skills_dir();
|
||||
fs.create_symlink(&skills_dir, paths::home_dir().clone())
|
||||
.await
|
||||
.expect("global skills directory should be symlinked to home");
|
||||
|
||||
let outside_path = paths::home_dir().join("outside.txt");
|
||||
assert!(
|
||||
resolve_global_skill_path(&outside_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"existing absolute paths outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
assert!(
|
||||
resolve_creatable_global_skill_path(&outside_path, fs.as_ref())
|
||||
.await
|
||||
.is_none(),
|
||||
"creatable absolute paths outside the lexical global skills tree should not resolve",
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_resolve_project_path_safe_for_normal_files(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
|
|
|||
140
crates/agent/src/tools/update_title_tool.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
use crate::{AgentTool, Thread, ToolCallEventStream, ToolInput};
|
||||
use agent_client_protocol::schema as acp;
|
||||
use gpui::{App, SharedString, Task, WeakEntity};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
const MAX_TITLE_LEN: usize = 200;
|
||||
|
||||
/// Updates the current session title.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
|
||||
pub struct UpdateTitleToolInput {
|
||||
/// A concise, human-readable title for the current session.
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
pub struct UpdateTitleTool {
|
||||
thread: WeakEntity<Thread>,
|
||||
}
|
||||
|
||||
impl UpdateTitleTool {
|
||||
pub fn new(thread: WeakEntity<Thread>) -> Self {
|
||||
Self { thread }
|
||||
}
|
||||
|
||||
pub(crate) fn title_for_input(
|
||||
input: Result<UpdateTitleToolInput, serde_json::Value>,
|
||||
) -> SharedString {
|
||||
let Ok(input) = input else {
|
||||
return "Update title".into();
|
||||
};
|
||||
let Ok(title) = normalize_title(&input.title) else {
|
||||
return "Update title".into();
|
||||
};
|
||||
format!("Update title: {title}").into()
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentTool for UpdateTitleTool {
|
||||
type Input = UpdateTitleToolInput;
|
||||
type Output = String;
|
||||
|
||||
const NAME: &'static str = "update_title";
|
||||
|
||||
fn kind() -> acp::ToolKind {
|
||||
acp::ToolKind::Think
|
||||
}
|
||||
|
||||
fn initial_title(
|
||||
&self,
|
||||
input: Result<Self::Input, serde_json::Value>,
|
||||
_cx: &mut App,
|
||||
) -> SharedString {
|
||||
Self::title_for_input(input)
|
||||
}
|
||||
|
||||
fn run(
|
||||
self: Arc<Self>,
|
||||
input: ToolInput<Self::Input>,
|
||||
_event_stream: ToolCallEventStream,
|
||||
cx: &mut App,
|
||||
) -> Task<Result<Self::Output, Self::Output>> {
|
||||
let thread = self.thread.clone();
|
||||
cx.spawn(async move |cx| {
|
||||
let input = input.recv().await.map_err(|error| error.to_string())?;
|
||||
let title = normalize_title(&input.title)?;
|
||||
|
||||
thread
|
||||
.update(cx, |thread, cx| {
|
||||
thread.set_title(title.into(), cx);
|
||||
})
|
||||
.map_err(|error| error.to_string())?;
|
||||
|
||||
Ok("Session title updated".to_string())
|
||||
})
|
||||
}
|
||||
|
||||
fn replay(
|
||||
&self,
|
||||
input: Self::Input,
|
||||
_output: Self::Output,
|
||||
event_stream: ToolCallEventStream,
|
||||
cx: &mut App,
|
||||
) -> anyhow::Result<()> {
|
||||
let title = self.initial_title(Ok(input), cx).to_string();
|
||||
event_stream.update_fields(acp::ToolCallUpdateFields::new().title(title));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_title(title: &str) -> Result<String, String> {
|
||||
let title = title.lines().next().unwrap_or("").trim();
|
||||
if title.is_empty() {
|
||||
return Err("Title cannot be empty".to_string());
|
||||
}
|
||||
Ok(util::truncate_and_trailoff(title, MAX_TITLE_LEN))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use gpui::TestAppContext;
|
||||
|
||||
#[test]
|
||||
fn test_normalize_title() {
|
||||
assert_eq!(
|
||||
normalize_title(" Title from model\nignored").unwrap(),
|
||||
"Title from model"
|
||||
);
|
||||
assert!(normalize_title(" \nignored").is_err());
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_initial_title(cx: &mut TestAppContext) {
|
||||
let tool = UpdateTitleTool::new(WeakEntity::new_invalid());
|
||||
|
||||
let title = cx.update(|cx| {
|
||||
tool.initial_title(
|
||||
Ok(UpdateTitleToolInput {
|
||||
title: "Investigate title updates".to_string(),
|
||||
}),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
assert_eq!(
|
||||
title,
|
||||
SharedString::from("Update title: Investigate title updates")
|
||||
);
|
||||
|
||||
let title = cx.update(|cx| {
|
||||
tool.initial_title(
|
||||
Ok(UpdateTitleToolInput {
|
||||
title: " ".to_string(),
|
||||
}),
|
||||
cx,
|
||||
)
|
||||
});
|
||||
assert_eq!(title, SharedString::from("Update title"));
|
||||
}
|
||||
}
|
||||
|
|
@ -22,11 +22,13 @@ const DEFAULT_UI_TEXT: &str = "Writing file";
|
|||
/// To make granular edits to an existing file, prefer the `edit_file` tool instead.
|
||||
///
|
||||
/// Before using this tool, verify the directory path is correct (only applicable when creating new files). Use the `list_directory` tool to verify the parent directory exists and is the correct location
|
||||
///
|
||||
/// The only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct WriteFileToolInput {
|
||||
/// The full path of the file to create or overwrite in the project.
|
||||
///
|
||||
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories.
|
||||
/// WARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.
|
||||
///
|
||||
/// The following examples assume we have two root directories in the project:
|
||||
/// - /a/b/backend
|
||||
|
|
@ -41,6 +43,10 @@ pub struct WriteFileToolInput {
|
|||
/// <example>
|
||||
/// `frontend/db.js`
|
||||
/// </example>
|
||||
///
|
||||
/// <example>
|
||||
/// To create or overwrite a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.
|
||||
/// </example>
|
||||
pub path: PathBuf,
|
||||
|
||||
/// The entire content for the file.
|
||||
|
|
@ -237,6 +243,7 @@ impl AgentTool for WriteFileTool {
|
|||
run_session(
|
||||
self.process_streaming_writes(&mut input, &event_stream, cx)
|
||||
.await,
|
||||
&event_stream,
|
||||
cx,
|
||||
)
|
||||
.await
|
||||
|
|
@ -272,7 +279,7 @@ mod tests {
|
|||
use prompt_store::ProjectContext;
|
||||
use serde_json::json;
|
||||
use settings::{Settings, SettingsStore};
|
||||
use std::sync::Arc;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
use util::path;
|
||||
use util::rel_path::{RelPath, rel_path};
|
||||
|
||||
|
|
@ -327,6 +334,62 @@ mod tests {
|
|||
assert_eq!(*old_text, "old content");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_write_global_skill_file(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
|
||||
let fs = project::FakeFs::new(cx.executor());
|
||||
fs.insert_tree(path!("/root"), json!({})).await;
|
||||
let skill_dir = agent_skills::global_skills_dir().join("my-skill");
|
||||
fs.insert_tree(&skill_dir, json!({})).await;
|
||||
let (write_tool, _project, _action_log, fs, _thread) =
|
||||
setup_test_with_fs(cx, fs, &[path!("/root").as_ref()]).await;
|
||||
|
||||
let input_path = PathBuf::from("~")
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
let skill_file = agent_skills::global_skills_dir()
|
||||
.join("my-skill")
|
||||
.join("SKILL.md");
|
||||
|
||||
let (event_stream, mut event_rx) = ToolCallEventStream::test();
|
||||
let task = cx.update(|cx| {
|
||||
write_tool.clone().run(
|
||||
ToolInput::resolved(WriteFileToolInput {
|
||||
path: input_path,
|
||||
content: "# My Skill\n".into(),
|
||||
}),
|
||||
event_stream,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
event_rx.expect_update_fields().await;
|
||||
let auth = event_rx.expect_authorization().await;
|
||||
let title = auth.tool_call.fields.title.as_deref().unwrap_or("");
|
||||
assert!(
|
||||
title.contains("agent skills"),
|
||||
"Authorization title should mention agent skills, got: {title}",
|
||||
);
|
||||
auth.response
|
||||
.send(acp_thread::SelectedPermissionOutcome::new(
|
||||
acp::PermissionOptionId::new("allow"),
|
||||
acp::PermissionOptionKind::AllowOnce,
|
||||
))
|
||||
.expect("authorization response should send");
|
||||
|
||||
let EditSessionOutput::Success { new_text, .. } = task.await.unwrap() else {
|
||||
panic!("expected success");
|
||||
};
|
||||
assert_eq!(new_text, "# My Skill\n");
|
||||
assert_eq!(
|
||||
fs.load(&skill_file).await.unwrap().replace("\r\n", "\n"),
|
||||
"# My Skill\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_streaming_path_completeness_heuristic(cx: &mut TestAppContext) {
|
||||
let (write_tool, _project, _action_log, _fs, _thread) =
|
||||
|
|
@ -998,7 +1061,8 @@ mod tests {
|
|||
|
||||
cx.run_until_parked();
|
||||
|
||||
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
|
||||
let changed =
|
||||
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
|
||||
assert!(
|
||||
!changed.is_empty(),
|
||||
"action_log.changed_buffers() should be non-empty after streaming write, \
|
||||
|
|
@ -1070,7 +1134,8 @@ mod tests {
|
|||
);
|
||||
|
||||
// Reject all edits — this should delete the newly created file
|
||||
let changed = action_log.read_with(cx, |log, cx| log.changed_buffers(cx));
|
||||
let changed =
|
||||
action_log.read_with(cx, |log, cx| log.changed_buffers(cx).collect::<Vec<_>>());
|
||||
assert!(
|
||||
!changed.is_empty(),
|
||||
"action_log should track the created file as changed"
|
||||
|
|
|
|||
|
|
@ -88,22 +88,18 @@ impl AgentServer for CustomAgentServer {
|
|||
let config_id = config_id.to_string();
|
||||
let value_id = value_id.to_string();
|
||||
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
match settings {
|
||||
settings::CustomAgentServerSettings::Custom {
|
||||
favorite_config_option_values,
|
||||
..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Extension {
|
||||
favorite_config_option_values,
|
||||
..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Registry {
|
||||
favorite_config_option_values,
|
||||
..
|
||||
|
|
@ -129,16 +125,15 @@ impl AgentServer for CustomAgentServer {
|
|||
|
||||
fn set_default_mode(&self, mode_id: Option<acp::SessionModeId>, fs: Arc<dyn Fs>, cx: &mut App) {
|
||||
let agent_id = self.agent_id();
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
match settings {
|
||||
settings::CustomAgentServerSettings::Custom { default_mode, .. }
|
||||
| settings::CustomAgentServerSettings::Extension { default_mode, .. }
|
||||
| settings::CustomAgentServerSettings::Registry { default_mode, .. } => {
|
||||
*default_mode = mode_id.map(|m| m.to_string());
|
||||
}
|
||||
|
|
@ -161,16 +156,15 @@ impl AgentServer for CustomAgentServer {
|
|||
|
||||
fn set_default_model(&self, model_id: Option<acp::ModelId>, fs: Arc<dyn Fs>, cx: &mut App) {
|
||||
let agent_id = self.agent_id();
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
match settings {
|
||||
settings::CustomAgentServerSettings::Custom { default_model, .. }
|
||||
| settings::CustomAgentServerSettings::Extension { default_model, .. }
|
||||
| settings::CustomAgentServerSettings::Registry { default_model, .. } => {
|
||||
*default_model = model_id.map(|m| m.to_string());
|
||||
}
|
||||
|
|
@ -205,20 +199,17 @@ impl AgentServer for CustomAgentServer {
|
|||
cx: &App,
|
||||
) {
|
||||
let agent_id = self.agent_id();
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
let favorite_models = match settings {
|
||||
settings::CustomAgentServerSettings::Custom {
|
||||
favorite_models, ..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Extension {
|
||||
favorite_models, ..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Registry {
|
||||
favorite_models, ..
|
||||
} => favorite_models,
|
||||
|
|
@ -258,22 +249,18 @@ impl AgentServer for CustomAgentServer {
|
|||
let agent_id = self.agent_id();
|
||||
let config_id = config_id.to_string();
|
||||
let value_id = value_id.map(|s| s.to_string());
|
||||
update_settings_file(fs, cx, move |settings, cx| {
|
||||
update_settings_file(fs, cx, move |settings, _cx| {
|
||||
let settings = settings
|
||||
.agent_servers
|
||||
.get_or_insert_default()
|
||||
.entry(agent_id.0.to_string())
|
||||
.or_insert_with(|| default_settings_for_agent(agent_id, cx));
|
||||
.or_insert_with(default_settings_for_agent);
|
||||
|
||||
match settings {
|
||||
settings::CustomAgentServerSettings::Custom {
|
||||
default_config_options,
|
||||
..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Extension {
|
||||
default_config_options,
|
||||
..
|
||||
}
|
||||
| settings::CustomAgentServerSettings::Registry {
|
||||
default_config_options,
|
||||
..
|
||||
|
|
@ -307,10 +294,6 @@ impl AgentServer for CustomAgentServer {
|
|||
default_config_options,
|
||||
..
|
||||
}
|
||||
| project::agent_server_store::CustomAgentServerSettings::Extension {
|
||||
default_config_options,
|
||||
..
|
||||
}
|
||||
| project::agent_server_store::CustomAgentServerSettings::Registry {
|
||||
default_config_options,
|
||||
..
|
||||
|
|
@ -422,28 +405,14 @@ fn is_registry_agent(agent_id: impl Into<AgentId>, cx: &App) -> bool {
|
|||
is_in_registry || is_settings_registry
|
||||
}
|
||||
|
||||
fn default_settings_for_agent(
|
||||
agent_id: impl Into<AgentId>,
|
||||
cx: &App,
|
||||
) -> settings::CustomAgentServerSettings {
|
||||
if is_registry_agent(agent_id, cx) {
|
||||
settings::CustomAgentServerSettings::Registry {
|
||||
default_model: None,
|
||||
default_mode: None,
|
||||
env: Default::default(),
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: Default::default(),
|
||||
favorite_config_option_values: Default::default(),
|
||||
}
|
||||
} else {
|
||||
settings::CustomAgentServerSettings::Extension {
|
||||
default_model: None,
|
||||
default_mode: None,
|
||||
env: Default::default(),
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: Default::default(),
|
||||
favorite_config_option_values: Default::default(),
|
||||
}
|
||||
fn default_settings_for_agent() -> settings::CustomAgentServerSettings {
|
||||
settings::CustomAgentServerSettings::Registry {
|
||||
default_model: None,
|
||||
default_mode: None,
|
||||
env: Default::default(),
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: Default::default(),
|
||||
favorite_config_option_values: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -547,53 +516,4 @@ mod tests {
|
|||
assert!(is_registry_agent("agent-from-settings", cx));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_agent_with_extension_settings_type_is_not_registry(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
set_agent_server_settings(
|
||||
cx,
|
||||
vec![(
|
||||
"my-extension-agent",
|
||||
settings::CustomAgentServerSettings::Extension {
|
||||
env: HashMap::default(),
|
||||
default_mode: None,
|
||||
default_model: None,
|
||||
favorite_models: Vec::new(),
|
||||
default_config_options: HashMap::default(),
|
||||
favorite_config_option_values: HashMap::default(),
|
||||
},
|
||||
)],
|
||||
);
|
||||
cx.update(|cx| {
|
||||
assert!(!is_registry_agent("my-extension-agent", cx));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_default_settings_for_extension_agent(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
cx.update(|cx| {
|
||||
assert!(matches!(
|
||||
default_settings_for_agent("some-extension-agent", cx),
|
||||
settings::CustomAgentServerSettings::Extension { .. }
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_default_settings_for_agent_in_registry(cx: &mut TestAppContext) {
|
||||
init_test(cx);
|
||||
init_registry_with_agents(cx, &["new-registry-agent"]);
|
||||
cx.update(|cx| {
|
||||
assert!(matches!(
|
||||
default_settings_for_agent("new-registry-agent", cx),
|
||||
settings::CustomAgentServerSettings::Registry { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
default_settings_for_agent("not-in-registry", cx),
|
||||
settings::CustomAgentServerSettings::Extension { .. }
|
||||
));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ futures.workspace = true
|
|||
gpui.workspace = true
|
||||
language_model.workspace = true
|
||||
log.workspace = true
|
||||
paths.workspace = true
|
||||
project.workspace = true
|
||||
regex.workspace = true
|
||||
schemars.workspace = true
|
||||
|
|
@ -31,7 +32,6 @@ util.workspace = true
|
|||
[dev-dependencies]
|
||||
fs.workspace = true
|
||||
gpui = { workspace = true, features = ["test-support"] }
|
||||
paths.workspace = true
|
||||
|
||||
serde_json_lenient.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
mod agent_profile;
|
||||
mod user_agents_md;
|
||||
|
||||
use std::path::{Component, Path};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
|
@ -20,6 +21,7 @@ use settings::{
|
|||
};
|
||||
|
||||
pub use crate::agent_profile::*;
|
||||
pub use crate::user_agents_md::{UserAgentsMd, UserAgentsMdState, init as init_user_agents_md};
|
||||
|
||||
pub const SUMMARIZE_THREAD_PROMPT: &str = include_str!("prompts/summarize_thread_prompt.txt");
|
||||
pub const SUMMARIZE_THREAD_DETAILED_PROMPT: &str =
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ path = "agent_skills.rs"
|
|||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
const_format.workspace = true
|
||||
fs.workspace = true
|
||||
futures.workspace = true
|
||||
|
|
@ -20,6 +21,7 @@ gpui.workspace = true
|
|||
paths.workspace = true
|
||||
serde.workspace = true
|
||||
serde_yaml_ng.workspace = true
|
||||
url.workspace = true
|
||||
util.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
use anyhow::{Context as _, Result};
|
||||
use const_format::concatcp;
|
||||
use const_format::{concatcp, formatcp};
|
||||
use fs::Fs;
|
||||
use futures::StreamExt;
|
||||
use gpui::{Global, SharedString};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use url::Url;
|
||||
use util::paths::component_matches_ignore_ascii_case;
|
||||
|
||||
/// First segment of the skills directory path: `.agents`.
|
||||
|
|
@ -64,11 +65,19 @@ pub struct Skill {
|
|||
/// `skill` tool refuses to load it. The user can still invoke it as a
|
||||
/// slash command.
|
||||
pub disable_model_invocation: bool,
|
||||
/// For built-in skills whose content is compiled into the binary,
|
||||
/// this holds the full SKILL.md body so the skill tool can serve it
|
||||
/// without a filesystem read.
|
||||
pub embedded_body: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Indicates where a skill was loaded from.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SkillSource {
|
||||
/// Compiled into the Zed binary. These are always available and have
|
||||
/// the lowest override priority (global and project-local skills can
|
||||
/// shadow them).
|
||||
BuiltIn,
|
||||
/// From ~/.agents/skills/
|
||||
Global,
|
||||
/// From {project}/.agents/skills/
|
||||
|
|
@ -79,6 +88,23 @@ pub enum SkillSource {
|
|||
}
|
||||
|
||||
impl SkillSource {
|
||||
/// Precedence for resolving same-named skills. Higher values shadow
|
||||
/// lower ones: `ProjectLocal` > `Global` > `BuiltIn`. Two sources
|
||||
/// returning equal precedence (e.g. two project-local skills from
|
||||
/// different worktrees) leave the winner up to the caller, which by
|
||||
/// convention keeps the first one in iteration order.
|
||||
///
|
||||
/// Adding a new `SkillSource` variant should be a one-line change
|
||||
/// here — every consumer routes through this method so the hierarchy
|
||||
/// stays in sync.
|
||||
pub fn precedence(&self) -> u8 {
|
||||
match self {
|
||||
Self::BuiltIn => 0,
|
||||
Self::Global => 1,
|
||||
Self::ProjectLocal { .. } => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// Scope prefix used in the `/<prefix>:<name>` slash-command
|
||||
/// syntax that the autocomplete popup inserts. Global skills use
|
||||
/// an empty prefix (so the inserted text is `/:<name>`), and
|
||||
|
|
@ -91,9 +117,21 @@ impl SkillSource {
|
|||
/// invoked as `/:<name>`, and the worktree's skill is invoked as
|
||||
/// `/global:<name>`. The two grammars never collide on the
|
||||
/// inserted text.
|
||||
/// Human-readable label for this source, used in the UI to
|
||||
/// distinguish skills from different origins.
|
||||
pub fn display_label(&self) -> &str {
|
||||
match self {
|
||||
Self::BuiltIn => "built-in",
|
||||
Self::Global => "global",
|
||||
Self::ProjectLocal {
|
||||
worktree_root_name, ..
|
||||
} => worktree_root_name.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scope_prefix(&self) -> &str {
|
||||
match self {
|
||||
Self::Global => "",
|
||||
Self::BuiltIn | Self::Global => "",
|
||||
Self::ProjectLocal {
|
||||
worktree_root_name, ..
|
||||
} => worktree_root_name.as_ref(),
|
||||
|
|
@ -112,7 +150,7 @@ impl SkillSource {
|
|||
/// strictness only affects users typing by memory.
|
||||
pub fn matches_scope(&self, scope: &str) -> bool {
|
||||
match self {
|
||||
Self::Global => scope.is_empty(),
|
||||
Self::BuiltIn | Self::Global => scope.is_empty(),
|
||||
Self::ProjectLocal {
|
||||
worktree_root_name, ..
|
||||
} => !scope.is_empty() && worktree_root_name.as_ref() == scope,
|
||||
|
|
@ -120,6 +158,23 @@ impl SkillSource {
|
|||
}
|
||||
}
|
||||
|
||||
/// App-wide index of loaded skills, published by NativeAgent and read
|
||||
/// by any UI that needs to display the skill list (e.g. Settings UI).
|
||||
#[derive(Default)]
|
||||
pub struct SkillIndex {
|
||||
pub global_skills: Vec<Skill>,
|
||||
pub project_skills: Vec<ProjectSkillGroup>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ProjectSkillGroup {
|
||||
pub worktree_id: SkillScopeId,
|
||||
pub worktree_root_name: SharedString,
|
||||
pub skills: Vec<Skill>,
|
||||
}
|
||||
|
||||
impl Global for SkillIndex {}
|
||||
|
||||
/// Just the frontmatter, used for parsing
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SkillMetadata {
|
||||
|
|
@ -187,17 +242,7 @@ pub fn parse_skill_frontmatter(
|
|||
content: &str,
|
||||
source: SkillSource,
|
||||
) -> Result<Skill> {
|
||||
if content.len() > MAX_SKILL_FILE_SIZE {
|
||||
anyhow::bail!(
|
||||
"SKILL.md file exceeds maximum size of {}KB",
|
||||
MAX_SKILL_FILE_SIZE / 1024
|
||||
);
|
||||
}
|
||||
|
||||
let (metadata, _body) = extract_frontmatter(content)?;
|
||||
|
||||
validate_name(&metadata.name)?;
|
||||
validate_description(&metadata.description)?;
|
||||
let (metadata, _body) = parse_skill_file_content(content)?;
|
||||
|
||||
let directory_path = skill_file_path
|
||||
.parent()
|
||||
|
|
@ -211,9 +256,33 @@ pub fn parse_skill_frontmatter(
|
|||
directory_path,
|
||||
skill_file_path: skill_file_path.to_path_buf(),
|
||||
disable_model_invocation: metadata.disable_model_invocation,
|
||||
embedded_body: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Extract the YAML frontmatter and body from a SKILL.md file without
|
||||
/// validating the metadata fields.
|
||||
pub fn extract_skill_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
|
||||
if content.len() > MAX_SKILL_FILE_SIZE {
|
||||
anyhow::bail!(
|
||||
"SKILL.md file exceeds maximum size of {}KB",
|
||||
MAX_SKILL_FILE_SIZE / 1024
|
||||
);
|
||||
}
|
||||
|
||||
extract_frontmatter(content)
|
||||
}
|
||||
|
||||
/// Parse and validate the YAML frontmatter and body from a SKILL.md file.
|
||||
pub fn parse_skill_file_content(content: &str) -> Result<(SkillMetadata, &str)> {
|
||||
let (metadata, body) = extract_skill_frontmatter(content)?;
|
||||
|
||||
validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
|
||||
validate_description(&metadata.description).map_err(anyhow::Error::msg)?;
|
||||
|
||||
Ok((metadata, body))
|
||||
}
|
||||
|
||||
fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
|
||||
let content = content.trim_start();
|
||||
|
||||
|
|
@ -290,6 +359,14 @@ fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {
|
|||
/// by [`validate_name`].
|
||||
pub const MAX_SKILL_NAME_LEN: usize = 64;
|
||||
|
||||
/// Maximum length (in bytes) for a valid skill description. Mirrors the
|
||||
/// upper bound enforced by [`validate_description`].
|
||||
///
|
||||
/// Byte-based rather than char-based because that's what `.len()` returns
|
||||
/// and what every caller currently measures; the UI also surfaces this
|
||||
/// limit as a byte count so the editor's counter matches the validator.
|
||||
pub const MAX_SKILL_DESCRIPTION_LEN: usize = 1024;
|
||||
|
||||
/// Convert an arbitrary human-readable string into a valid skill name, or
|
||||
/// return `None` if no valid name can be produced (e.g. the input contains
|
||||
/// no ASCII alphanumeric characters at all).
|
||||
|
|
@ -354,34 +431,54 @@ pub fn slugify_skill_name(input: &str) -> Option<String> {
|
|||
if slug.is_empty() { None } else { Some(slug) }
|
||||
}
|
||||
|
||||
fn validate_name(name: &str) -> Result<()> {
|
||||
/// Validate a skill name against the rules enforced by both the loader
|
||||
/// and the create-skill UI.
|
||||
///
|
||||
/// Rules:
|
||||
/// * non-empty
|
||||
/// * at most [`MAX_SKILL_NAME_LEN`] bytes
|
||||
/// * ASCII lowercase letters, digits, and hyphens only
|
||||
/// * must not start or end with a hyphen — [`slugify_skill_name`]
|
||||
/// already guarantees this for its output, so requiring it in the
|
||||
/// validator keeps hand-written `SKILL.md` files consistent with
|
||||
/// slugifier output
|
||||
///
|
||||
/// Error messages are returned as `&'static str` (interpolated at
|
||||
/// compile time via `formatcp!`) so that UI surfaces can store them in
|
||||
/// `Option<&'static str>` fields without allocating, and loader callers
|
||||
/// can convert them to `anyhow::Error` via `anyhow::Error::msg`.
|
||||
pub fn validate_name(name: &str) -> Result<(), &'static str> {
|
||||
if name.is_empty() {
|
||||
anyhow::bail!("Skill name cannot be empty");
|
||||
return Err("Skill name cannot be empty");
|
||||
}
|
||||
|
||||
if name.len() > MAX_SKILL_NAME_LEN {
|
||||
anyhow::bail!("Skill name must be at most {MAX_SKILL_NAME_LEN} characters");
|
||||
return Err(formatcp!(
|
||||
"Skill name must be at most {MAX_SKILL_NAME_LEN} characters"
|
||||
));
|
||||
}
|
||||
if name.starts_with('-') || name.ends_with('-') {
|
||||
return Err("Skill name must not start or end with a hyphen");
|
||||
}
|
||||
|
||||
if !name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||
{
|
||||
anyhow::bail!("Skill name must contain only lowercase letters, numbers, and hyphens");
|
||||
return Err("Skill name must contain only lowercase letters, numbers, and hyphens");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_description(description: &str) -> Result<()> {
|
||||
if description.is_empty() {
|
||||
anyhow::bail!("Skill description cannot be empty");
|
||||
/// Validate a skill description against the rules enforced by both the
|
||||
/// loader and the create-skill UI.
|
||||
pub fn validate_description(description: &str) -> Result<(), &'static str> {
|
||||
if description.trim().is_empty() {
|
||||
return Err("Skill description cannot be empty");
|
||||
}
|
||||
|
||||
if description.len() > 1024 {
|
||||
anyhow::bail!("Skill description must be at most 1024 characters");
|
||||
if description.len() > MAX_SKILL_DESCRIPTION_LEN {
|
||||
return Err(formatcp!(
|
||||
"Skill description must be at most {MAX_SKILL_DESCRIPTION_LEN} bytes"
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -460,53 +557,15 @@ async fn find_skill_files(fs: &Arc<dyn Fs>, directory: &Path) -> Vec<PathBuf> {
|
|||
.await
|
||||
}
|
||||
|
||||
/// Returns the byte index ONE PAST the end of the closing frontmatter
|
||||
/// delimiter line in `bytes`, or `None` if no closing delimiter has been
|
||||
/// seen yet. Used by the chunked reader to know when it has enough
|
||||
/// bytes to stop pulling from disk.
|
||||
/// Read `skill_file_path` from disk and parse its frontmatter. The
|
||||
/// SKILL.md body is parsed away by `parse_skill_frontmatter` and not
|
||||
/// surfaced here; it's re-read on demand via `read_skill_body` when a
|
||||
/// skill is actually being loaded for the model.
|
||||
///
|
||||
/// Scans for the first `\n---` line followed by `\n`, `\r\n`, or EOF
|
||||
/// (excluding the opening line itself, which sits at byte 0 and is
|
||||
/// naturally skipped because we only consider lines following a `\n`).
|
||||
/// This may overshoot in pathological cases (e.g. `---` inside a quoted
|
||||
/// YAML string), but `parse_skill_frontmatter`'s candidate-and-validate
|
||||
/// logic still produces a correct result or a YAML parse error.
|
||||
fn closing_delimiter_end(bytes: &[u8]) -> Option<usize> {
|
||||
for (i, &b) in bytes.iter().enumerate() {
|
||||
if b != b'\n' {
|
||||
continue;
|
||||
}
|
||||
let line_start = i + 1;
|
||||
if line_start + 3 > bytes.len() {
|
||||
continue;
|
||||
}
|
||||
if &bytes[line_start..line_start + 3] != b"---" {
|
||||
continue;
|
||||
}
|
||||
let after_dashes = line_start + 3;
|
||||
if after_dashes == bytes.len() {
|
||||
return Some(after_dashes);
|
||||
}
|
||||
if bytes[after_dashes] == b'\n' {
|
||||
return Some(after_dashes + 1);
|
||||
}
|
||||
if after_dashes + 1 < bytes.len()
|
||||
&& bytes[after_dashes] == b'\r'
|
||||
&& bytes[after_dashes + 1] == b'\n'
|
||||
{
|
||||
return Some(after_dashes + 2);
|
||||
}
|
||||
// Line is `---trailing` or `----`; keep scanning.
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Read just enough of `skill_file_path` from disk to parse its
|
||||
/// frontmatter. The SKILL.md body is NOT loaded — that's deferred to
|
||||
/// `read_skill_body`, called only when a skill is actually being
|
||||
/// materialized for the model. Reading in 4KB chunks keeps the peak
|
||||
/// memory cost of loading N skills proportional to total frontmatter
|
||||
/// size, not total file size.
|
||||
/// We load the whole file in one go rather than streaming up to the
|
||||
/// closing `---`. `MAX_SKILL_FILE_SIZE` is 100KB and the metadata check
|
||||
/// below caps the worst case at that, so the peak transient cost is
|
||||
/// trivially small (≤ `MAX_SKILL_FILE_SIZE` × `SKILL_IO_CONCURRENCY`).
|
||||
pub async fn load_skill_frontmatter(
|
||||
fs: Arc<dyn Fs>,
|
||||
skill_file_path: PathBuf,
|
||||
|
|
@ -514,10 +573,15 @@ pub async fn load_skill_frontmatter(
|
|||
) -> Result<Skill, SkillLoadError> {
|
||||
// Short-circuit on oversized files before reading any of their
|
||||
// contents, so a stray multi-GB file named `SKILL.md` can't OOM the
|
||||
// app. We only act on a positive signal that the file is too large;
|
||||
// if metadata fails or is unavailable, we fall through to the read
|
||||
// loop, which is itself capped at `MAX_SKILL_FILE_SIZE`.
|
||||
if let Ok(Some(metadata)) = fs.metadata(&skill_file_path).await
|
||||
// app. If metadata is unavailable, refuse to read.
|
||||
let metadata = fs
|
||||
.metadata(&skill_file_path)
|
||||
.await
|
||||
.map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: format!("Failed to read SKILL.md metadata: {}", e),
|
||||
})?;
|
||||
if let Some(metadata) = metadata
|
||||
&& metadata.len > MAX_SKILL_FILE_SIZE as u64
|
||||
{
|
||||
return Err(SkillLoadError {
|
||||
|
|
@ -529,51 +593,15 @@ pub async fn load_skill_frontmatter(
|
|||
});
|
||||
}
|
||||
|
||||
let mut reader = fs
|
||||
.open_sync(&skill_file_path)
|
||||
let content = fs
|
||||
.load(&skill_file_path)
|
||||
.await
|
||||
.map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: format!("Failed to open file: {}", e),
|
||||
message: format!("Failed to read file: {}", e),
|
||||
})?;
|
||||
|
||||
// The chunked read is intentionally synchronous: `Fs::open_sync`
|
||||
// returns a synchronous `Read` (RealFs uses `std::fs::File`), and
|
||||
// production callers already wrap `load_skills_from_directory` in
|
||||
// `cx.background_spawn`, so any blocking happens on the background
|
||||
// executor — not on the foreground thread. Routing through
|
||||
// `smol::unblock` instead would schedule the work on smol's blocking
|
||||
// pool, whose wakeups don't drive GPUI's test scheduler and therefore
|
||||
// panic with "Parking forbidden" under `TestAppContext`.
|
||||
let read_result: Result<Vec<u8>, io::Error> = (|| {
|
||||
let mut accumulated: Vec<u8> = Vec::new();
|
||||
let mut chunk = [0u8; 4096];
|
||||
loop {
|
||||
let n = reader.read(&mut chunk)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
accumulated.extend_from_slice(&chunk[..n]);
|
||||
if closing_delimiter_end(&accumulated).is_some() {
|
||||
break;
|
||||
}
|
||||
if accumulated.len() > MAX_SKILL_FILE_SIZE {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(accumulated)
|
||||
})();
|
||||
let accumulated = read_result.map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: format!("Failed to read file: {}", e),
|
||||
})?;
|
||||
|
||||
let content = std::str::from_utf8(&accumulated).map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: format!("SKILL.md is not valid UTF-8: {}", e),
|
||||
})?;
|
||||
|
||||
parse_skill_frontmatter(&skill_file_path, content, source).map_err(|e| SkillLoadError {
|
||||
parse_skill_frontmatter(&skill_file_path, &content, source).map_err(|e| SkillLoadError {
|
||||
path: skill_file_path.clone(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
|
|
@ -600,6 +628,53 @@ pub async fn read_skill_body(
|
|||
Ok(body.trim().to_string())
|
||||
}
|
||||
|
||||
/// Content of the built-in `create-skill` SKILL.md, embedded at compile time.
|
||||
const CREATE_SKILL_CONTENT: &str = include_str!("builtin/create-skill/SKILL.md");
|
||||
|
||||
/// Returns the set of skills that are compiled into the Zed binary.
|
||||
pub fn builtin_skills() -> Vec<Skill> {
|
||||
let mut skills = Vec::new();
|
||||
if let Ok(skill) = parse_builtin_skill("create-skill", CREATE_SKILL_CONTENT) {
|
||||
skills.push(skill);
|
||||
}
|
||||
skills
|
||||
}
|
||||
|
||||
/// Parse a built-in skill from its embedded SKILL.md content. The skill
|
||||
/// gets a synthetic `<built-in>` path since it doesn't live on disk.
|
||||
fn parse_builtin_skill(name: &str, content: &'static str) -> Result<Skill> {
|
||||
let (metadata, body) = extract_frontmatter(content)?;
|
||||
validate_name(&metadata.name).map_err(anyhow::Error::msg)?;
|
||||
validate_description(&metadata.description).map_err(anyhow::Error::msg)?;
|
||||
|
||||
let synthetic_dir = PathBuf::from(format!("<built-in>/{}", name));
|
||||
let synthetic_path = synthetic_dir.join(SKILL_FILE_NAME);
|
||||
|
||||
Ok(Skill {
|
||||
name: metadata.name,
|
||||
description: metadata.description,
|
||||
source: SkillSource::BuiltIn,
|
||||
directory_path: synthetic_dir,
|
||||
skill_file_path: synthetic_path,
|
||||
disable_model_invocation: metadata.disable_model_invocation,
|
||||
embedded_body: Some(body.trim()),
|
||||
})
|
||||
}
|
||||
|
||||
/// All built-in skills as `(name, raw_content)` pairs. Used by
|
||||
/// `builtin_skill_content` to serve the full SKILL.md without disk I/O.
|
||||
const BUILTIN_SKILL_ENTRIES: &[(&str, &str)] = &[("create-skill", CREATE_SKILL_CONTENT)];
|
||||
|
||||
/// Look up the full embedded content of a built-in skill by its
|
||||
/// synthetic file path. Returns `None` if the path doesn't match any
|
||||
/// built-in skill.
|
||||
pub fn builtin_skill_content(skill_file_path: &Path) -> Option<&'static str> {
|
||||
BUILTIN_SKILL_ENTRIES.iter().find_map(|(name, content)| {
|
||||
let expected = PathBuf::from(format!("<built-in>/{}", name)).join(SKILL_FILE_NAME);
|
||||
(expected == skill_file_path).then_some(*content)
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the global skills directory: `~/.agents/skills`.
|
||||
///
|
||||
/// Other agents (e.g. Claude Code) already write skill files into this
|
||||
|
|
@ -657,12 +732,92 @@ pub fn is_agents_skills_path(path: &Path) -> bool {
|
|||
false
|
||||
}
|
||||
|
||||
/// The `zed://` scheme used by share links.
|
||||
const SKILL_SHARE_LINK_SCHEME: &str = "zed";
|
||||
/// The host (the part after `zed://`) that identifies a skill share link.
|
||||
const SKILL_SHARE_LINK_HOST: &str = "skill";
|
||||
/// The query parameter that carries the embedded `SKILL.md` payload.
|
||||
const SKILL_SHARE_LINK_DATA_PARAM: &str = "data";
|
||||
|
||||
/// The `zed://` deep-link prefix for a shared skill. Opening a link with this
|
||||
/// prefix prompts the recipient to review and install the embedded skill.
|
||||
pub const SKILL_SHARE_LINK_PREFIX: &str =
|
||||
concatcp!(SKILL_SHARE_LINK_SCHEME, "://", SKILL_SHARE_LINK_HOST);
|
||||
|
||||
/// Build a shareable `zed://skill?data=…` link that fully embeds the given
|
||||
/// `SKILL.md` file contents.
|
||||
///
|
||||
/// The contents are base64url-encoded (no padding) so the link is
|
||||
/// self-contained and URL-safe: the recipient doesn't need the skill to be
|
||||
/// hosted anywhere. Recover the contents with [`decode_skill_share_link`].
|
||||
pub fn encode_skill_share_link(skill_file_content: &str) -> String {
|
||||
use base64::Engine as _;
|
||||
let data =
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(skill_file_content.as_bytes());
|
||||
let mut url = Url::parse(SKILL_SHARE_LINK_PREFIX).expect("skill share link prefix is valid");
|
||||
url.query_pairs_mut()
|
||||
.append_pair(SKILL_SHARE_LINK_DATA_PARAM, &data);
|
||||
url.into()
|
||||
}
|
||||
|
||||
/// Recover the `SKILL.md` contents embedded in a `zed://skill?data=…` link
|
||||
/// produced by [`encode_skill_share_link`].
|
||||
pub fn decode_skill_share_link(link: &str) -> Result<String> {
|
||||
use base64::Engine as _;
|
||||
let url = Url::parse(link).context("skill share link is not a valid URL")?;
|
||||
anyhow::ensure!(
|
||||
url.scheme() == SKILL_SHARE_LINK_SCHEME && url.host_str() == Some(SKILL_SHARE_LINK_HOST),
|
||||
"not a skill share link"
|
||||
);
|
||||
let data = url
|
||||
.query_pairs()
|
||||
.find_map(|(key, value)| (key == SKILL_SHARE_LINK_DATA_PARAM).then_some(value))
|
||||
.context("skill share link is missing the `data` parameter")?;
|
||||
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(data.as_bytes())
|
||||
.context("skill share link `data` is not valid base64")?;
|
||||
anyhow::ensure!(
|
||||
bytes.len() <= MAX_SKILL_FILE_SIZE,
|
||||
"shared skill exceeds the maximum size of {MAX_SKILL_FILE_SIZE} bytes"
|
||||
);
|
||||
let content = String::from_utf8(bytes).context("skill share link `data` is not valid UTF-8")?;
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use fs::FakeFs;
|
||||
use gpui::TestAppContext;
|
||||
|
||||
#[test]
|
||||
fn test_skill_source_precedence_is_total_and_ordered() {
|
||||
// Pin the hierarchy: project-local > global > built-in. Every
|
||||
// override and conflict-resolution site routes through this,
|
||||
// so the rest of the codebase relies on it being correct.
|
||||
let built_in = SkillSource::BuiltIn.precedence();
|
||||
let global = SkillSource::Global.precedence();
|
||||
let project = SkillSource::ProjectLocal {
|
||||
worktree_id: SkillScopeId(1),
|
||||
worktree_root_name: "my-project".into(),
|
||||
}
|
||||
.precedence();
|
||||
|
||||
assert!(built_in < global, "global must shadow built-in");
|
||||
assert!(global < project, "project-local must shadow global");
|
||||
|
||||
// Two project-local skills from different worktrees tie. The
|
||||
// "first wins" convention is enforced by the callers, but the
|
||||
// precedence itself must be equal so neither silently shadows
|
||||
// the other.
|
||||
let other_project = SkillSource::ProjectLocal {
|
||||
worktree_id: SkillScopeId(2),
|
||||
worktree_root_name: "other-project".into(),
|
||||
}
|
||||
.precedence();
|
||||
assert_eq!(project, other_project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_valid_skill() {
|
||||
let content = r#"---
|
||||
|
|
@ -690,6 +845,26 @@ Do the thing.
|
|||
assert!(!skill.disable_model_invocation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_skill_file_content_returns_body() {
|
||||
let content = r#"---
|
||||
name: my-skill
|
||||
description: A test skill for testing purposes
|
||||
---
|
||||
|
||||
# My Skill
|
||||
|
||||
Do the thing.
|
||||
"#;
|
||||
|
||||
let (metadata, body) = parse_skill_file_content(content)
|
||||
.expect("valid skill content should parse successfully");
|
||||
|
||||
assert_eq!(metadata.name, "my-skill");
|
||||
assert_eq!(metadata.description, "A test skill for testing purposes");
|
||||
assert_eq!(body.trim(), "# My Skill\n\nDo the thing.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_disable_model_invocation_true() {
|
||||
let content = r#"---
|
||||
|
|
@ -873,12 +1048,8 @@ Content.
|
|||
SkillSource::Global,
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("at most 64 characters")
|
||||
);
|
||||
let expected = format!("at most {MAX_SKILL_NAME_LEN} characters");
|
||||
assert!(result.unwrap_err().to_string().contains(&expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1154,12 +1325,8 @@ Content.
|
|||
SkillSource::Global,
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("at most 1024 characters")
|
||||
);
|
||||
let expected = format!("at most {MAX_SKILL_DESCRIPTION_LEN} bytes");
|
||||
assert!(result.unwrap_err().to_string().contains(&expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1532,6 +1699,7 @@ description: A skill with no body content
|
|||
directory_path: PathBuf::from("/skills/test-skill"),
|
||||
skill_file_path: PathBuf::from("/skills/test-skill/SKILL.md"),
|
||||
disable_model_invocation: false,
|
||||
embedded_body: None,
|
||||
};
|
||||
|
||||
let summary = SkillSummary::from(&skill);
|
||||
|
|
@ -1759,4 +1927,110 @@ description: A skill with no body content
|
|||
"project/.AGENTS/SKILLS/foo"
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_accepts_valid_names() {
|
||||
assert!(validate_name("draft-pr").is_ok());
|
||||
assert!(validate_name("a").is_ok());
|
||||
assert!(validate_name("skill1").is_ok());
|
||||
assert!(validate_name(&"a".repeat(MAX_SKILL_NAME_LEN)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_rejects_empty() {
|
||||
assert!(validate_name("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_rejects_uppercase() {
|
||||
assert!(validate_name("Draft-PR").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_rejects_leading_and_trailing_hyphens() {
|
||||
assert!(validate_name("-draft").is_err());
|
||||
assert!(validate_name("draft-").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_rejects_invalid_chars() {
|
||||
assert!(validate_name("draft_pr").is_err());
|
||||
assert!(validate_name("draft pr").is_err());
|
||||
assert!(validate_name("draft.pr").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_rejects_too_long() {
|
||||
assert!(validate_name(&"a".repeat(MAX_SKILL_NAME_LEN + 1)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_description_accepts_valid() {
|
||||
assert!(validate_description("A useful skill").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_description_rejects_empty_and_whitespace_only() {
|
||||
assert!(validate_description("").is_err());
|
||||
assert!(validate_description(" ").is_err());
|
||||
assert!(validate_description("\t\n ").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_description_rejects_too_long() {
|
||||
assert!(validate_description(&"a".repeat(MAX_SKILL_DESCRIPTION_LEN + 1)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_description_length_is_measured_in_bytes() {
|
||||
// "é" is 2 bytes in UTF-8. A string of MAX/2 + 1 "é" characters has
|
||||
// only ~MAX/2 + 1 chars but exceeds MAX bytes, so it must be
|
||||
// rejected by a byte-based validator (and accepted by a char-based
|
||||
// one). This regression-tests the byte semantics that the loader
|
||||
// and UI both rely on.
|
||||
let chars = MAX_SKILL_DESCRIPTION_LEN / 2 + 1;
|
||||
let description = "é".repeat(chars);
|
||||
assert!(description.chars().count() <= MAX_SKILL_DESCRIPTION_LEN);
|
||||
assert!(description.len() > MAX_SKILL_DESCRIPTION_LEN);
|
||||
assert!(validate_description(&description).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slugify_output_always_passes_validate_name() {
|
||||
for input in [
|
||||
"foo",
|
||||
"Foo Bar",
|
||||
"rock & roll",
|
||||
"---weird---",
|
||||
"a".repeat(200).as_str(),
|
||||
] {
|
||||
if let Some(slug) = slugify_skill_name(input) {
|
||||
assert!(
|
||||
validate_name(&slug).is_ok(),
|
||||
"slug {slug:?} from {input:?} failed validate_name"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_share_link_round_trips() {
|
||||
let content =
|
||||
"---\nname: my-skill\ndescription: Does a thing.\n---\n\n## Steps\n\nDo the thing.\n";
|
||||
let link = encode_skill_share_link(content);
|
||||
let data = link
|
||||
.strip_prefix("zed://skill?data=")
|
||||
.expect("link should start with the skill share prefix");
|
||||
// base64url (no-pad) output must not require percent-encoding.
|
||||
assert!(!data.contains('+') && !data.contains('/') && !data.contains('='));
|
||||
assert_eq!(decode_skill_share_link(&link).unwrap(), content);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_skill_share_link_rejects_non_skill_links() {
|
||||
assert!(decode_skill_share_link("zed://settings/agent.skills").is_err());
|
||||
assert!(decode_skill_share_link("zed://skill").is_err());
|
||||
assert!(decode_skill_share_link("zed://skill?other=1").is_err());
|
||||
assert!(decode_skill_share_link("zed://skill?data=!!!notbase64").is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
95
crates/agent_skills/builtin/create-skill/SKILL.md
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
---
|
||||
name: create-skill
|
||||
description: Helps you create new agent skills for Zed. Use this to create a skill, ask about SKILLs.md, or package reusable agent instructions.
|
||||
---
|
||||
|
||||
# Creating a Zed Agent Skill
|
||||
|
||||
Use this skill when the user wants to create, edit, or understand agent skills in Zed.
|
||||
|
||||
## What is a Skill?
|
||||
|
||||
A skill is a reusable set of instructions that an agent can load on demand. Each skill lives in its own directory and is defined by a `SKILL.md` file with YAML frontmatter.
|
||||
|
||||
## Where Skills Live
|
||||
|
||||
Skills can be placed in two locations:
|
||||
|
||||
| Scope | Path | When to use |
|
||||
|-------|------|-------------|
|
||||
| Global | `~/.agents/skills/<skill-name>/SKILL.md` | Personal skills, available in all projects |
|
||||
| Project-local | `<project>/.agents/skills/<skill-name>/SKILL.md` | Project-specific skills, shared with collaborators through version control |
|
||||
|
||||
Prefer project-local when the skill is specific to a repository. Prefer global when the skill is a personal workflow the user wants everywhere.
|
||||
|
||||
## SKILL.md Format
|
||||
|
||||
Every `SKILL.md` must start with YAML frontmatter between `---` delimiters:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: my-skill-name
|
||||
description: A clear, specific description of what this skill does and when to use it.
|
||||
---
|
||||
|
||||
# Skill Title
|
||||
|
||||
Instructions for the agent go here. Write them as if you're telling the agent
|
||||
what to do when this skill is activated.
|
||||
```
|
||||
|
||||
### Required Frontmatter Fields
|
||||
|
||||
- **`name`** (required): Must be 1–64 characters, lowercase alphanumeric with single-hyphen separators. Must match the containing directory name exactly. Regex: `^[a-z0-9]+(-[a-z0-9]+)*$`
|
||||
- **`description`** (required): Must be 1–1024 characters. This is what the agent sees when deciding whether to use the skill — make it specific and actionable.
|
||||
|
||||
### Optional Frontmatter Fields
|
||||
|
||||
- **`disable-model-invocation`**: When set to `true`, the skill is hidden from the agent's automatic catalog. The user can still invoke it manually via the `/` slash command menu. Useful for skills that should only run when explicitly requested.
|
||||
|
||||
## Naming Rules
|
||||
|
||||
The skill name must:
|
||||
- Be lowercase letters and numbers only, with single hyphens as separators
|
||||
- Not start or end with `-`
|
||||
- Not contain consecutive `--`
|
||||
- Match the directory name that contains the `SKILL.md`
|
||||
|
||||
Good: `git-release`, `pr-review`, `rust-patterns`
|
||||
Bad: `Git-Release`, `pr--review`, `-my-skill`, `my_skill`
|
||||
|
||||
## Writing Good Skill Instructions
|
||||
|
||||
The body of the SKILL.md (after the frontmatter) contains the instructions the agent will follow. Guidelines:
|
||||
|
||||
1. **Be direct**: Write instructions as if talking to the agent. "Do X", "Check Y", "Ask the user about Z".
|
||||
2. **Be specific**: Include concrete file paths, commands, formats, and patterns.
|
||||
3. **Include when-to-use guidance**: Help the agent understand the right context for this skill.
|
||||
4. **Reference supporting files**: Skills can include additional files in their directory. Reference them with relative paths (e.g., `templates/component.tsx`). The agent can read these files when the skill is activated.
|
||||
5. **Keep descriptions actionable**: The `description` field is the agent's primary signal for whether to load this skill. "Helps with code" is too vague. "Generate React components following the project's design system patterns" is specific.
|
||||
|
||||
## Supporting Files
|
||||
|
||||
A skill directory can contain additional files beyond `SKILL.md`:
|
||||
|
||||
```
|
||||
~/.agents/skills/react-component/
|
||||
├── SKILL.md
|
||||
├── templates/
|
||||
│ ├── component.tsx
|
||||
│ └── test.tsx
|
||||
└── examples/
|
||||
└── button.tsx
|
||||
```
|
||||
|
||||
Reference these in the skill body. The agent can read them using the file path shown in the `<directory>` tag of the skill envelope.
|
||||
|
||||
## Step-by-Step: Creating a Skill
|
||||
|
||||
1. Decide on scope (global vs project-local) based on the user's needs.
|
||||
2. Choose a descriptive, hyphenated name.
|
||||
3. Create the directory structure. The `create_directory` tool normally only creates directories inside the current project, but it has a special allow case for global skills under `~/.agents/skills`.
|
||||
4. Write the `SKILL.md` with frontmatter and instructions. The `write_file` and `edit_file` tools also have a special allow case for creating or modifying files under `~/.agents/skills`.
|
||||
5. Optionally add supporting files (templates, examples, references).
|
||||
|
||||
After creating the skill, it will be automatically discovered by Zed's agent on the next conversation (no restart needed for global skills if the `~/.agents/skills/` directory already exists).
|
||||
|
|
@ -30,10 +30,10 @@ acp_thread.workspace = true
|
|||
action_log.workspace = true
|
||||
agent-client-protocol.workspace = true
|
||||
agent.workspace = true
|
||||
agent_skills.workspace = true
|
||||
async-channel.workspace = true
|
||||
agent_servers.workspace = true
|
||||
agent_settings.workspace = true
|
||||
agent_skills.workspace = true
|
||||
ai_onboarding.workspace = true
|
||||
anyhow.workspace = true
|
||||
heapless.workspace = true
|
||||
|
|
@ -69,6 +69,7 @@ language.workspace = true
|
|||
language_model.workspace = true
|
||||
language_models.workspace = true
|
||||
log.workspace = true
|
||||
lru.workspace = true
|
||||
lsp.workspace = true
|
||||
markdown.workspace = true
|
||||
menu.workspace = true
|
||||
|
|
@ -88,7 +89,7 @@ release_channel.workspace = true
|
|||
remote.workspace = true
|
||||
remote_connection.workspace = true
|
||||
rope.workspace = true
|
||||
rules_library.workspace = true
|
||||
skill_creator.workspace = true
|
||||
schemars.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
|
@ -145,3 +146,4 @@ tempfile.workspace = true
|
|||
vim.workspace = true
|
||||
tree-sitter-md.workspace = true
|
||||
unindent.workspace = true
|
||||
terminal = { workspace = true, features = ["test-support"] }
|
||||
|
|
|
|||
|
|
@ -664,8 +664,14 @@ impl AgentConfiguration {
|
|||
None
|
||||
};
|
||||
let auth_required = matches!(server_status, ContextServerStatus::AuthRequired);
|
||||
let client_secret_required = matches!(
|
||||
server_status,
|
||||
ContextServerStatus::ClientSecretRequired { .. }
|
||||
);
|
||||
let authenticating = matches!(server_status, ContextServerStatus::Authenticating);
|
||||
let context_server_store = self.context_server_store.clone();
|
||||
let workspace = self.workspace.clone();
|
||||
let language_registry = self.language_registry.clone();
|
||||
|
||||
let tool_count = self
|
||||
.context_server_registry
|
||||
|
|
@ -685,6 +691,9 @@ impl AgentConfiguration {
|
|||
ContextServerStatus::Error(_) => AiSettingItemStatus::Error,
|
||||
ContextServerStatus::Stopped => AiSettingItemStatus::Stopped,
|
||||
ContextServerStatus::AuthRequired => AiSettingItemStatus::AuthRequired,
|
||||
ContextServerStatus::ClientSecretRequired { .. } => {
|
||||
AiSettingItemStatus::ClientSecretRequired
|
||||
}
|
||||
ContextServerStatus::Authenticating => AiSettingItemStatus::Authenticating,
|
||||
};
|
||||
|
||||
|
|
@ -886,7 +895,7 @@ impl AgentConfiguration {
|
|||
),
|
||||
)
|
||||
.child(
|
||||
Button::new("error-logout-server", "Authenticate")
|
||||
Button::new("authenticate-server", "Authenticate")
|
||||
.style(ButtonStyle::Outlined)
|
||||
.label_size(LabelSize::Small)
|
||||
.on_click({
|
||||
|
|
@ -900,6 +909,46 @@ impl AgentConfiguration {
|
|||
)
|
||||
.into_any_element(),
|
||||
)
|
||||
} else if client_secret_required {
|
||||
Some(
|
||||
feedback_base_container()
|
||||
.child(
|
||||
h_flex()
|
||||
.pr_4()
|
||||
.min_w_0()
|
||||
.w_full()
|
||||
.gap_2()
|
||||
.child(
|
||||
Icon::new(IconName::Info)
|
||||
.size(IconSize::XSmall)
|
||||
.color(Color::Muted),
|
||||
)
|
||||
.child(
|
||||
Label::new("Enter a client secret to connect this server")
|
||||
.color(Color::Muted)
|
||||
.size(LabelSize::Small),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
Button::new("enter-client-secret", "Enter Client Secret")
|
||||
.style(ButtonStyle::Outlined)
|
||||
.label_size(LabelSize::Small)
|
||||
.on_click({
|
||||
let context_server_id = context_server_id.clone();
|
||||
move |_event, window, cx| {
|
||||
ConfigureContextServerModal::show_modal_for_existing_server(
|
||||
context_server_id.clone(),
|
||||
language_registry.clone(),
|
||||
workspace.clone(),
|
||||
window,
|
||||
cx,
|
||||
)
|
||||
.detach();
|
||||
}
|
||||
}),
|
||||
)
|
||||
.into_any_element(),
|
||||
)
|
||||
} else if authenticating {
|
||||
Some(
|
||||
h_flex()
|
||||
|
|
@ -1125,7 +1174,6 @@ impl AgentConfiguration {
|
|||
};
|
||||
|
||||
let source_kind = match source {
|
||||
ExternalAgentSource::Extension => AiSettingItemSource::Extension,
|
||||
ExternalAgentSource::Registry => AiSettingItemSource::Registry,
|
||||
ExternalAgentSource::Custom => AiSettingItemSource::Custom,
|
||||
};
|
||||
|
|
@ -1169,26 +1217,6 @@ impl AgentConfiguration {
|
|||
});
|
||||
|
||||
let uninstall_button = match source {
|
||||
ExternalAgentSource::Extension => Some(
|
||||
IconButton::new(
|
||||
SharedString::from(format!("uninstall-{}", id)),
|
||||
IconName::Trash,
|
||||
)
|
||||
.icon_color(Color::Muted)
|
||||
.icon_size(IconSize::Small)
|
||||
.tooltip(Tooltip::text("Uninstall Agent Extension"))
|
||||
.on_click(cx.listener(move |this, _, _window, cx| {
|
||||
let agent_name = agent_server_name.clone();
|
||||
|
||||
if let Some(ext_id) = this.agent_server_store.update(cx, |store, _cx| {
|
||||
store.get_extension_id_for_agent(&agent_name)
|
||||
}) {
|
||||
ExtensionStore::global(cx)
|
||||
.update(cx, |store, cx| store.uninstall_extension(ext_id, cx))
|
||||
.detach_and_log_err(cx);
|
||||
}
|
||||
})),
|
||||
),
|
||||
ExternalAgentSource::Registry => {
|
||||
let fs = self.fs.clone();
|
||||
Some(
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ use project::{
|
|||
ContextServerStatus, ContextServerStore, ServerStatusChangedEvent,
|
||||
registry::ContextServerDescriptorRegistry,
|
||||
},
|
||||
project_settings::{ContextServerSettings, ProjectSettings},
|
||||
project_settings::{ContextServerSettings, OAuthClientSettings, ProjectSettings},
|
||||
worktree_store::WorktreeStore,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
|
@ -43,7 +43,9 @@ enum ConfigurationTarget {
|
|||
id: ContextServerId,
|
||||
url: String,
|
||||
headers: HashMap<String, String>,
|
||||
oauth: Option<OAuthClientSettings>,
|
||||
},
|
||||
|
||||
Extension {
|
||||
id: ContextServerId,
|
||||
repository_url: Option<SharedString>,
|
||||
|
|
@ -121,15 +123,17 @@ impl ConfigurationSource {
|
|||
id,
|
||||
url,
|
||||
headers: auth,
|
||||
oauth,
|
||||
} => ConfigurationSource::Existing {
|
||||
editor: create_editor(
|
||||
context_server_http_input(Some((id, url, auth))),
|
||||
context_server_http_input(Some((id, url, auth, oauth))),
|
||||
jsonc_language,
|
||||
window,
|
||||
cx,
|
||||
),
|
||||
is_http: true,
|
||||
},
|
||||
|
||||
ConfigurationTarget::Extension {
|
||||
id,
|
||||
repository_url,
|
||||
|
|
@ -168,7 +172,7 @@ impl ConfigurationSource {
|
|||
ConfigurationSource::New { editor, is_http }
|
||||
| ConfigurationSource::Existing { editor, is_http } => {
|
||||
if *is_http {
|
||||
parse_http_input(&editor.read(cx).text(cx)).map(|(id, url, auth)| {
|
||||
parse_http_input(&editor.read(cx).text(cx)).map(|(id, url, auth, oauth)| {
|
||||
(
|
||||
id,
|
||||
ContextServerSettings::Http {
|
||||
|
|
@ -176,6 +180,7 @@ impl ConfigurationSource {
|
|||
url,
|
||||
headers: auth,
|
||||
timeout: None,
|
||||
oauth,
|
||||
},
|
||||
)
|
||||
})
|
||||
|
|
@ -256,11 +261,16 @@ fn context_server_input(existing: Option<(ContextServerId, ContextServerCommand)
|
|||
}
|
||||
|
||||
fn context_server_http_input(
|
||||
existing: Option<(ContextServerId, String, HashMap<String, String>)>,
|
||||
existing: Option<(
|
||||
ContextServerId,
|
||||
String,
|
||||
HashMap<String, String>,
|
||||
Option<OAuthClientSettings>,
|
||||
)>,
|
||||
) -> String {
|
||||
let (name, url, headers) = match existing {
|
||||
Some((id, url, headers)) => {
|
||||
let header = if headers.is_empty() {
|
||||
let (name, url, headers, oauth) = match existing {
|
||||
Some((id, url, headers, oauth)) => {
|
||||
let headers = if headers.is_empty() {
|
||||
r#"// "Authorization": "Bearer <token>"#.to_string()
|
||||
} else {
|
||||
let json = serde_json::to_string_pretty(&headers).unwrap();
|
||||
|
|
@ -274,15 +284,48 @@ fn context_server_http_input(
|
|||
.map(|line| format!(" {}", line))
|
||||
.collect::<String>()
|
||||
};
|
||||
(id.0.to_string(), url, header)
|
||||
(id.0.to_string(), url, headers, oauth)
|
||||
}
|
||||
None => (
|
||||
"some-remote-server".to_string(),
|
||||
"https://example.com/mcp".to_string(),
|
||||
r#"// "Authorization": "Bearer <token>"#.to_string(),
|
||||
None,
|
||||
),
|
||||
};
|
||||
|
||||
let oauth = oauth.map_or_else(
|
||||
|| {
|
||||
r#"
|
||||
/// Uncomment to use a pre-registered OAuth client. You can include the client secret here as well, otherwise it will be prompted interactively and saved in the system keychain.
|
||||
// "oauth": {
|
||||
// "client_id": "your-client-id",
|
||||
// },"#
|
||||
.to_string()
|
||||
},
|
||||
|
||||
|oauth| {
|
||||
let mut lines = vec![
|
||||
String::from("\n \"oauth\": {"),
|
||||
|
||||
format!(" \"client_id\": {},", serde_json::to_string(&oauth.client_id).unwrap()),
|
||||
];
|
||||
if let Some(client_secret) = oauth.client_secret {
|
||||
lines.push(format!(
|
||||
" \"client_secret\": {}",
|
||||
serde_json::to_string(&client_secret).unwrap()
|
||||
));
|
||||
} else {
|
||||
lines.push(String::from(
|
||||
" /// Optional client secret for confidential clients\n // \"client_secret\": \"your-client-secret\"",
|
||||
));
|
||||
}
|
||||
lines.push(String::from(" },"));
|
||||
|
||||
lines.join("\n")
|
||||
},
|
||||
);
|
||||
|
||||
format!(
|
||||
r#"{{
|
||||
/// Configure an MCP server that you connect to over HTTP
|
||||
|
|
@ -290,7 +333,7 @@ fn context_server_http_input(
|
|||
/// The name of your remote MCP server
|
||||
"{name}": {{
|
||||
/// The URL of the remote MCP server
|
||||
"url": "{url}",
|
||||
"url": "{url}",{oauth}
|
||||
"headers": {{
|
||||
/// Any headers to send along
|
||||
{headers}
|
||||
|
|
@ -300,12 +343,21 @@ fn context_server_http_input(
|
|||
)
|
||||
}
|
||||
|
||||
fn parse_http_input(text: &str) -> Result<(ContextServerId, String, HashMap<String, String>)> {
|
||||
fn parse_http_input(
|
||||
text: &str,
|
||||
) -> Result<(
|
||||
ContextServerId,
|
||||
String,
|
||||
HashMap<String, String>,
|
||||
Option<OAuthClientSettings>,
|
||||
)> {
|
||||
#[derive(Deserialize)]
|
||||
struct Temp {
|
||||
url: String,
|
||||
#[serde(default)]
|
||||
headers: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
oauth: Option<OAuthClientSettings>,
|
||||
}
|
||||
let value: HashMap<String, Temp> = serde_json_lenient::from_str(text)?;
|
||||
if value.len() != 1 {
|
||||
|
|
@ -314,7 +366,12 @@ fn parse_http_input(text: &str) -> Result<(ContextServerId, String, HashMap<Stri
|
|||
|
||||
let (key, value) = value.into_iter().next().unwrap();
|
||||
|
||||
Ok((ContextServerId(key.into()), value.url, value.headers))
|
||||
Ok((
|
||||
ContextServerId(key.into()),
|
||||
value.url,
|
||||
value.headers,
|
||||
value.oauth,
|
||||
))
|
||||
}
|
||||
|
||||
fn resolve_context_server_extension(
|
||||
|
|
@ -349,8 +406,16 @@ fn resolve_context_server_extension(
|
|||
enum State {
|
||||
Idle,
|
||||
Waiting,
|
||||
AuthRequired { server_id: ContextServerId },
|
||||
Authenticating { _server_id: ContextServerId },
|
||||
AuthRequired {
|
||||
server_id: ContextServerId,
|
||||
},
|
||||
ClientSecretRequired {
|
||||
server_id: ContextServerId,
|
||||
error: Option<SharedString>,
|
||||
},
|
||||
Authenticating {
|
||||
server_id: ContextServerId,
|
||||
},
|
||||
Error(SharedString),
|
||||
}
|
||||
|
||||
|
|
@ -361,10 +426,47 @@ pub struct ConfigureContextServerModal {
|
|||
state: State,
|
||||
original_server_id: Option<ContextServerId>,
|
||||
scroll_handle: ScrollHandle,
|
||||
secret_editor: Entity<Editor>,
|
||||
_auth_subscription: Option<Subscription>,
|
||||
}
|
||||
|
||||
impl ConfigureContextServerModal {
|
||||
fn initial_state(
|
||||
context_server_store: &Entity<ContextServerStore>,
|
||||
target: &ConfigurationTarget,
|
||||
cx: &App,
|
||||
) -> State {
|
||||
let Some(server_id) = (match target {
|
||||
ConfigurationTarget::Existing { id, .. }
|
||||
| ConfigurationTarget::ExistingHttp { id, .. }
|
||||
| ConfigurationTarget::Extension { id, .. } => Some(id),
|
||||
ConfigurationTarget::New => None,
|
||||
}) else {
|
||||
return State::Idle;
|
||||
};
|
||||
|
||||
match context_server_store.read(cx).status_for_server(server_id) {
|
||||
Some(ContextServerStatus::AuthRequired) => State::AuthRequired {
|
||||
server_id: server_id.clone(),
|
||||
},
|
||||
Some(ContextServerStatus::ClientSecretRequired { error }) => {
|
||||
State::ClientSecretRequired {
|
||||
server_id: server_id.clone(),
|
||||
error: error.map(SharedString::from),
|
||||
}
|
||||
}
|
||||
Some(ContextServerStatus::Authenticating) => State::Authenticating {
|
||||
server_id: server_id.clone(),
|
||||
},
|
||||
Some(ContextServerStatus::Error(error)) => State::Error(error.into()),
|
||||
|
||||
Some(ContextServerStatus::Starting)
|
||||
| Some(ContextServerStatus::Running)
|
||||
| Some(ContextServerStatus::Stopped)
|
||||
| None => State::Idle,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(
|
||||
workspace: &mut Workspace,
|
||||
language_registry: Arc<LanguageRegistry>,
|
||||
|
|
@ -426,12 +528,14 @@ impl ConfigureContextServerModal {
|
|||
url,
|
||||
headers,
|
||||
timeout: _,
|
||||
..
|
||||
oauth,
|
||||
} => Some(ConfigurationTarget::ExistingHttp {
|
||||
id: server_id,
|
||||
url,
|
||||
headers,
|
||||
oauth,
|
||||
}),
|
||||
|
||||
ContextServerSettings::Extension { .. } => {
|
||||
match workspace
|
||||
.update(cx, |workspace, cx| {
|
||||
|
|
@ -468,9 +572,10 @@ impl ConfigureContextServerModal {
|
|||
let workspace_handle = cx.weak_entity();
|
||||
let context_server_store = workspace.project().read(cx).context_server_store();
|
||||
workspace.toggle_modal(window, cx, |window, cx| Self {
|
||||
context_server_store,
|
||||
context_server_store: context_server_store.clone(),
|
||||
workspace: workspace_handle,
|
||||
state: State::Idle,
|
||||
state: Self::initial_state(&context_server_store, &target, cx),
|
||||
|
||||
original_server_id: match &target {
|
||||
ConfigurationTarget::Existing { id, .. } => Some(id.clone()),
|
||||
ConfigurationTarget::ExistingHttp { id, .. } => Some(id.clone()),
|
||||
|
|
@ -485,6 +590,16 @@ impl ConfigureContextServerModal {
|
|||
cx,
|
||||
),
|
||||
scroll_handle: ScrollHandle::new(),
|
||||
secret_editor: cx.new(|cx| {
|
||||
let mut editor = Editor::single_line(window, cx);
|
||||
editor.set_placeholder_text(
|
||||
"Enter client secret (leave empty for public clients)",
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
editor.set_masked(true, cx);
|
||||
editor
|
||||
}),
|
||||
_auth_subscription: None,
|
||||
})
|
||||
})
|
||||
|
|
@ -497,13 +612,12 @@ impl ConfigureContextServerModal {
|
|||
}
|
||||
|
||||
fn confirm(&mut self, _: &menu::Confirm, cx: &mut Context<Self>) {
|
||||
if matches!(
|
||||
self.state,
|
||||
State::Waiting | State::AuthRequired { .. } | State::Authenticating { .. }
|
||||
) {
|
||||
if matches!(self.state, State::Waiting | State::Authenticating { .. }) {
|
||||
return;
|
||||
}
|
||||
|
||||
self._auth_subscription = None;
|
||||
|
||||
self.state = State::Idle;
|
||||
let Some(workspace) = self.workspace.upgrade() else {
|
||||
return;
|
||||
|
|
@ -519,7 +633,7 @@ impl ConfigureContextServerModal {
|
|||
|
||||
self.state = State::Waiting;
|
||||
|
||||
let existing_server = self.context_server_store.read(cx).get_running_server(&id);
|
||||
let existing_server = self.context_server_store.read(cx).get_server(&id);
|
||||
if existing_server.is_some() {
|
||||
self.context_server_store.update(cx, |store, cx| {
|
||||
store.stop_server(&id, cx).log_err();
|
||||
|
|
@ -542,6 +656,13 @@ impl ConfigureContextServerModal {
|
|||
this.state = State::AuthRequired { server_id: id };
|
||||
cx.notify();
|
||||
}
|
||||
Ok(ContextServerStatus::ClientSecretRequired { error }) => {
|
||||
this.state = State::ClientSecretRequired {
|
||||
server_id: id,
|
||||
error: error.map(SharedString::from),
|
||||
};
|
||||
cx.notify();
|
||||
}
|
||||
Err(err) => {
|
||||
this.set_error(err, cx);
|
||||
}
|
||||
|
|
@ -581,13 +702,33 @@ impl ConfigureContextServerModal {
|
|||
cx.emit(DismissEvent);
|
||||
}
|
||||
|
||||
fn cancel_authentication(&mut self, server_id: &ContextServerId, cx: &mut Context<Self>) {
|
||||
self._auth_subscription = None;
|
||||
self.context_server_store.update(cx, |store, cx| {
|
||||
store.stop_server(server_id, cx).log_err();
|
||||
});
|
||||
self.state = State::Idle;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
fn authenticate(&mut self, server_id: ContextServerId, cx: &mut Context<Self>) {
|
||||
self.context_server_store.update(cx, |store, cx| {
|
||||
store.authenticate_server(&server_id, cx).log_err();
|
||||
});
|
||||
self.await_auth_outcome(server_id, cx);
|
||||
}
|
||||
|
||||
fn submit_client_secret(&mut self, server_id: ContextServerId, cx: &mut Context<Self>) {
|
||||
let secret = self.secret_editor.read(cx).text(cx);
|
||||
self.context_server_store.update(cx, |store, cx| {
|
||||
store.submit_client_secret(&server_id, secret, cx).log_err();
|
||||
});
|
||||
self.await_auth_outcome(server_id, cx);
|
||||
}
|
||||
|
||||
fn await_auth_outcome(&mut self, server_id: ContextServerId, cx: &mut Context<Self>) {
|
||||
self.state = State::Authenticating {
|
||||
_server_id: server_id.clone(),
|
||||
server_id: server_id.clone(),
|
||||
};
|
||||
|
||||
self._auth_subscription = Some(cx.subscribe(
|
||||
|
|
@ -610,6 +751,14 @@ impl ConfigureContextServerModal {
|
|||
};
|
||||
cx.notify();
|
||||
}
|
||||
ContextServerStatus::ClientSecretRequired { error } => {
|
||||
this._auth_subscription = None;
|
||||
this.state = State::ClientSecretRequired {
|
||||
server_id: event.server_id.clone(),
|
||||
error: error.clone().map(SharedString::from),
|
||||
};
|
||||
cx.notify();
|
||||
}
|
||||
ContextServerStatus::Error(error) => {
|
||||
this._auth_subscription = None;
|
||||
this.set_error(error.clone(), cx);
|
||||
|
|
@ -814,10 +963,7 @@ impl ConfigureContextServerModal {
|
|||
|
||||
fn render_modal_footer(&self, cx: &mut Context<Self>) -> ModalFooter {
|
||||
let focus_handle = self.focus_handle(cx);
|
||||
let is_busy = matches!(
|
||||
self.state,
|
||||
State::Waiting | State::AuthRequired { .. } | State::Authenticating { .. }
|
||||
);
|
||||
let is_busy = matches!(self.state, State::Waiting | State::Authenticating { .. });
|
||||
|
||||
ModalFooter::new()
|
||||
.start_slot::<Button>(
|
||||
|
|
@ -944,6 +1090,112 @@ impl ConfigureContextServerModal {
|
|||
)
|
||||
}
|
||||
|
||||
fn render_client_secret_required(
|
||||
&self,
|
||||
server_id: &ContextServerId,
|
||||
error: Option<SharedString>,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Div {
|
||||
let settings = ThemeSettings::get_global(cx);
|
||||
let text_style = TextStyle {
|
||||
color: cx.theme().colors().text,
|
||||
font_family: settings.buffer_font.family.clone(),
|
||||
font_fallbacks: settings.buffer_font.fallbacks.clone(),
|
||||
font_size: settings.buffer_font_size(cx).into(),
|
||||
font_weight: settings.buffer_font.weight,
|
||||
line_height: relative(settings.buffer_line_height.value()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
v_flex()
|
||||
.w_full()
|
||||
.gap_2()
|
||||
.when_some(error, |this, error| {
|
||||
this.child(Self::render_modal_error(error))
|
||||
})
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1p5()
|
||||
.child(
|
||||
Icon::new(IconName::Info)
|
||||
.size(IconSize::Small)
|
||||
.color(Color::Muted),
|
||||
)
|
||||
.child(
|
||||
Label::new(
|
||||
"Enter your OAuth client secret, or leave empty for public clients",
|
||||
)
|
||||
.size(LabelSize::Small)
|
||||
.color(Color::Muted),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
h_flex()
|
||||
.w_full()
|
||||
.gap_2()
|
||||
.capture_action({
|
||||
let server_id = server_id.clone();
|
||||
cx.listener(move |this, _: &editor::actions::Newline, _window, cx| {
|
||||
this.submit_client_secret(server_id.clone(), cx);
|
||||
})
|
||||
})
|
||||
.child(div().flex_1().child(EditorElement::new(
|
||||
&self.secret_editor,
|
||||
EditorStyle {
|
||||
background: cx.theme().colors().editor_background,
|
||||
local_player: cx.theme().players().local(),
|
||||
text: text_style,
|
||||
syntax: cx.theme().syntax().clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)))
|
||||
.child(
|
||||
Button::new("submit-client-secret", "Submit")
|
||||
.style(ButtonStyle::Outlined)
|
||||
.label_size(LabelSize::Small)
|
||||
.on_click({
|
||||
let server_id = server_id.clone();
|
||||
cx.listener(move |this, _event, _window, cx| {
|
||||
this.submit_client_secret(server_id.clone(), cx);
|
||||
})
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_authenticating(&self, server_id: &ContextServerId, cx: &mut Context<Self>) -> Div {
|
||||
h_flex()
|
||||
.h_8()
|
||||
.gap_2()
|
||||
.justify_center()
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1p5()
|
||||
.child(
|
||||
Icon::new(IconName::LoadCircle)
|
||||
.size(IconSize::XSmall)
|
||||
.color(Color::Muted)
|
||||
.with_rotate_animation(3),
|
||||
)
|
||||
.child(
|
||||
Label::new("Authenticating…")
|
||||
.size(LabelSize::Small)
|
||||
.color(Color::Muted),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
Button::new("cancel-authentication", "Cancel")
|
||||
.style(ButtonStyle::Outlined)
|
||||
.label_size(LabelSize::Small)
|
||||
.on_click({
|
||||
let server_id = server_id.clone();
|
||||
cx.listener(move |this, _event, _window, cx| {
|
||||
this.cancel_authentication(&server_id, cx);
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_modal_error(error: SharedString) -> Div {
|
||||
h_flex()
|
||||
.h_8()
|
||||
|
|
@ -1003,8 +1255,15 @@ impl Render for ConfigureContextServerModal {
|
|||
State::AuthRequired { server_id } => {
|
||||
self.render_auth_required(&server_id.clone(), cx)
|
||||
}
|
||||
State::Authenticating { .. } => {
|
||||
self.render_loading("Authenticating…")
|
||||
State::ClientSecretRequired { server_id, error } => {
|
||||
self.render_client_secret_required(
|
||||
&server_id.clone(),
|
||||
error.clone(),
|
||||
cx,
|
||||
)
|
||||
}
|
||||
State::Authenticating { server_id } => {
|
||||
self.render_authenticating(&server_id.clone(), cx)
|
||||
}
|
||||
State::Error(error) => {
|
||||
Self::render_modal_error(error.clone())
|
||||
|
|
@ -1040,7 +1299,9 @@ fn wait_for_context_server(
|
|||
}
|
||||
|
||||
match status {
|
||||
ContextServerStatus::Running | ContextServerStatus::AuthRequired => {
|
||||
ContextServerStatus::Running
|
||||
| ContextServerStatus::AuthRequired
|
||||
| ContextServerStatus::ClientSecretRequired { .. } => {
|
||||
if let Some(tx) = tx.lock().take() {
|
||||
let _ = tx.send(Ok(status.clone()));
|
||||
}
|
||||
|
|
@ -1104,3 +1365,52 @@ pub(crate) fn default_markdown_style(window: &Window, cx: &App) -> MarkdownStyle
|
|||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_http_input_reads_oauth_settings() {
|
||||
let (id, url, headers, oauth) = parse_http_input(
|
||||
r#"{
|
||||
"figma": {
|
||||
"url": "https://mcp.figma.com/mcp",
|
||||
"oauth": {
|
||||
"client_id": "client-id",
|
||||
"client_secret": "client-secret"
|
||||
},
|
||||
"headers": {
|
||||
"X-Test": "test"
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(id, ContextServerId("figma".into()));
|
||||
assert_eq!(url, "https://mcp.figma.com/mcp");
|
||||
assert_eq!(headers.get("X-Test"), Some(&String::from("test")));
|
||||
let oauth = oauth.expect("oauth should be present");
|
||||
assert_eq!(oauth.client_id, "client-id");
|
||||
assert_eq!(oauth.client_secret.as_deref(), Some("client-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_server_http_input_preserves_existing_oauth_settings() {
|
||||
let text = context_server_http_input(Some((
|
||||
ContextServerId("figma".into()),
|
||||
String::from("https://mcp.figma.com/mcp"),
|
||||
HashMap::default(),
|
||||
Some(OAuthClientSettings {
|
||||
client_id: String::from("client-id"),
|
||||
client_secret: Some(String::from("client-secret")),
|
||||
}),
|
||||
)));
|
||||
|
||||
let (_, _, _, oauth) = parse_http_input(&text).unwrap();
|
||||
let oauth = oauth.expect("oauth should be present");
|
||||
assert_eq!(oauth.client_id, "client-id");
|
||||
assert_eq!(oauth.client_secret.as_deref(), Some("client-secret"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -138,7 +138,7 @@ impl AgentDiffPane {
|
|||
.changed_buffers(cx);
|
||||
|
||||
// Sort edited files alphabetically for consistency with Git diff view
|
||||
let mut sorted_buffers: Vec<_> = changed_buffers.iter().collect();
|
||||
let mut sorted_buffers: Vec<_> = changed_buffers.collect();
|
||||
sorted_buffers.sort_by(|(buffer_a, _), (buffer_b, _)| {
|
||||
let path_a = buffer_a.read(cx).file().map(|f| f.path().clone());
|
||||
let path_b = buffer_b.read(cx).file().map(|f| f.path().clone());
|
||||
|
|
@ -566,6 +566,10 @@ impl Item for AgentDiffPane {
|
|||
.for_each_project_item(cx, f)
|
||||
}
|
||||
|
||||
fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
|
||||
self.editor.read(cx).active_project_path(cx)
|
||||
}
|
||||
|
||||
fn set_nav_history(
|
||||
&mut self,
|
||||
nav_history: ItemNavHistory,
|
||||
|
|
@ -1531,7 +1535,7 @@ impl AgentDiff {
|
|||
};
|
||||
|
||||
let action_log = thread.read(cx).action_log();
|
||||
let changed_buffers = action_log.read(cx).changed_buffers(cx);
|
||||
let changed_buffers = action_log.read(cx).changed_buffers(cx).collect::<Vec<_>>();
|
||||
|
||||
let mut unaffected = self.reviewing_editors.clone();
|
||||
|
||||
|
|
@ -1765,12 +1769,13 @@ impl AgentDiff {
|
|||
{
|
||||
let changed_buffers = thread.read(cx).action_log().read(cx).changed_buffers(cx);
|
||||
|
||||
let mut keys = changed_buffers.keys();
|
||||
keys.find(|k| *k == &curr_buffer);
|
||||
let mut keys = changed_buffers.map(|(buffer, _)| buffer);
|
||||
keys.find(|k| *k == curr_buffer);
|
||||
let next_project_path = keys
|
||||
.next()
|
||||
.filter(|k| *k != &curr_buffer)
|
||||
.filter(|k| *k != curr_buffer)
|
||||
.and_then(|after| after.read(cx).project_path(cx));
|
||||
drop(keys);
|
||||
|
||||
if let Some(path) = next_project_path {
|
||||
let task = workspace.open_path(path, None, true, window, cx);
|
||||
|
|
@ -2253,7 +2258,7 @@ mod tests {
|
|||
});
|
||||
|
||||
let editor2_path = editor2
|
||||
.read_with(cx, |editor, cx| editor.project_path(cx))
|
||||
.read_with(cx, |editor, cx| editor.active_project_path(cx))
|
||||
.unwrap();
|
||||
assert_eq!(editor2_path, buffer_path2);
|
||||
|
||||
|
|
|
|||
|
|
@ -34,7 +34,6 @@ enum RegistryInstallStatus {
|
|||
NotInstalled,
|
||||
InstalledRegistry,
|
||||
InstalledCustom,
|
||||
InstalledExtension,
|
||||
}
|
||||
|
||||
#[derive(IntoElement)]
|
||||
|
|
@ -155,9 +154,6 @@ impl AgentRegistryPage {
|
|||
RegistryInstallStatus::InstalledRegistry
|
||||
}
|
||||
CustomAgentServerSettings::Custom { .. } => RegistryInstallStatus::InstalledCustom,
|
||||
CustomAgentServerSettings::Extension { .. } => {
|
||||
RegistryInstallStatus::InstalledExtension
|
||||
}
|
||||
};
|
||||
self.installed_statuses.insert(id.clone(), status);
|
||||
}
|
||||
|
|
@ -560,9 +556,6 @@ impl AgentRegistryPage {
|
|||
RegistryInstallStatus::InstalledCustom => Button::new(button_id, "Installed")
|
||||
.style(ButtonStyle::OutlinedGhost)
|
||||
.disabled(true),
|
||||
RegistryInstallStatus::InstalledExtension => Button::new(button_id, "Installed")
|
||||
.style(ButtonStyle::OutlinedGhost)
|
||||
.disabled(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ mod model_selector_popover;
|
|||
mod profile_selector;
|
||||
mod terminal_codegen;
|
||||
mod terminal_inline_assistant;
|
||||
pub mod terminal_thread_metadata_store;
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub mod test_support;
|
||||
mod thread_import;
|
||||
|
|
@ -42,10 +43,12 @@ use ::ui::IconName;
|
|||
use agent_client_protocol::schema as acp;
|
||||
use agent_settings::{AgentProfileId, AgentSettings};
|
||||
use command_palette_hooks::CommandPaletteFilter;
|
||||
use feature_flags::{FeatureFlagAppExt as _, SkillsFeatureFlag};
|
||||
use editor::{Editor, SelectionEffects, scroll::Autoscroll};
|
||||
use feature_flags::FeatureFlagAppExt as _;
|
||||
use fs::Fs;
|
||||
use gpui::{
|
||||
Action, App, Context, Entity, ImageSource, Resource, SharedString, SharedUri, Window, actions,
|
||||
Action, App, Context, Entity, ImageSource, Resource, SharedString, SharedUri, TaskExt, Window,
|
||||
actions,
|
||||
};
|
||||
use language::{
|
||||
LanguageRegistry,
|
||||
|
|
@ -55,7 +58,8 @@ use language_model::{
|
|||
ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
|
||||
};
|
||||
use project::{AgentId, DisableAiSettings};
|
||||
use prompt_store::{PromptBuilder, rules_to_skills_migration};
|
||||
use prompt_store::{self, PromptBuilder, rules_to_skills_migration};
|
||||
use rope::Point;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use settings::{LanguageModelSelection, Settings as _, SettingsStore, SidebarSide};
|
||||
|
|
@ -111,6 +115,42 @@ pub(crate) fn resolve_agent_image(
|
|||
None
|
||||
}
|
||||
|
||||
pub(crate) fn open_abs_path_at_point(
|
||||
workspace: &mut Workspace,
|
||||
abs_path: PathBuf,
|
||||
point: Point,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Workspace>,
|
||||
) -> bool {
|
||||
let project = workspace.project();
|
||||
let Some(path) = project.update(cx, |project, cx| project.find_project_path(abs_path, cx))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let item = workspace.open_path(path, None, true, window, cx);
|
||||
window
|
||||
.spawn(cx, async move |cx| {
|
||||
let Some(editor) = item.await?.downcast::<Editor>() else {
|
||||
return Ok(());
|
||||
};
|
||||
let range = point..point;
|
||||
editor
|
||||
.update_in(cx, |editor, window, cx| {
|
||||
editor.change_selections(
|
||||
SelectionEffects::scroll(Autoscroll::center()),
|
||||
window,
|
||||
cx,
|
||||
|selections| selections.select_ranges([range]),
|
||||
);
|
||||
})
|
||||
.ok();
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
true
|
||||
}
|
||||
|
||||
pub const DEFAULT_THREAD_TITLE: &str = "New Agent Thread";
|
||||
const PARALLEL_AGENT_LAYOUT_BACKFILL_KEY: &str = "parallel_agent_layout_backfilled";
|
||||
|
||||
|
|
@ -159,6 +199,8 @@ actions!(
|
|||
ArchiveSelectedThread,
|
||||
/// Removes the currently selected thread.
|
||||
RemoveSelectedThread,
|
||||
/// Renames the currently selected thread.
|
||||
RenameSelectedThread,
|
||||
/// Starts a chat conversation with follow-up enabled.
|
||||
ChatWithFollow,
|
||||
/// Cycles to the next inline assist suggestion.
|
||||
|
|
@ -203,6 +245,8 @@ actions!(
|
|||
ResetTrialUpsell,
|
||||
/// Resets the trial end upsell notification.
|
||||
ResetTrialEndUpsell,
|
||||
/// Re-enables the fast mode warning for every provider and model.
|
||||
ResetFastModeWarnings,
|
||||
/// Opens the "Add Context" menu in the message editor.
|
||||
OpenAddContextMenu,
|
||||
/// Interrupts the current generation and sends the message immediately.
|
||||
|
|
@ -243,6 +287,8 @@ actions!(
|
|||
ScrollOutputToNextMessage,
|
||||
/// Import agent threads from other Zed release channels (e.g. Preview, Nightly).
|
||||
ImportThreadsFromOtherChannels,
|
||||
/// Starts a new terminal thread.
|
||||
NewTerminalThread,
|
||||
]
|
||||
);
|
||||
|
||||
|
|
@ -504,7 +550,8 @@ pub fn init(
|
|||
cx: &mut App,
|
||||
) {
|
||||
agent::ThreadStore::init_global(cx);
|
||||
rules_library::init(cx);
|
||||
prompt_store::init(cx);
|
||||
skill_creator::init(cx);
|
||||
if !is_eval {
|
||||
// Initializing the language model from the user settings messes with the eval, so we only initialize them when
|
||||
// we're not running inside of the eval.
|
||||
|
|
@ -513,6 +560,7 @@ pub fn init(
|
|||
agent_panel::init(cx);
|
||||
context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
|
||||
thread_metadata_store::init(cx);
|
||||
terminal_thread_metadata_store::init(cx);
|
||||
|
||||
inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
|
||||
terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
|
||||
|
|
@ -552,32 +600,6 @@ pub fn init(
|
|||
);
|
||||
})
|
||||
.detach();
|
||||
cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
|
||||
workspace.register_action(
|
||||
|workspace: &mut Workspace,
|
||||
_: &zed_actions::agent::OpenRulesToSkillsMigrationInfo,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Workspace>| {
|
||||
// The banner is the only intended entry point and is
|
||||
// gated on the skills flag, but dispatch from the
|
||||
// command palette or a keybind is still possible — only
|
||||
// open the explainer if the flag is enabled so it never
|
||||
// surfaces outside its intended audience.
|
||||
//
|
||||
// Race note: `has_flag` returns false before server
|
||||
// flags are received, so a dispatch during that brief
|
||||
// window is a no-op even for users who genuinely have
|
||||
// the flag. The banner itself has the same race — it
|
||||
// stays hidden until flags arrive — so a user who can
|
||||
// see the banner has, by definition, already passed it.
|
||||
if cx.has_flag::<SkillsFeatureFlag>() {
|
||||
crate::ui::RulesToSkillsModal::toggle(workspace, window, cx);
|
||||
}
|
||||
},
|
||||
);
|
||||
})
|
||||
.detach();
|
||||
|
||||
cx.observe_new(ManageProfilesModal::register).detach();
|
||||
cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
|
||||
workspace.register_action(
|
||||
|
|
@ -606,10 +628,16 @@ pub fn init(
|
|||
})
|
||||
.detach();
|
||||
|
||||
// Once the `skills` feature flag has resolved, kick off the one-time
|
||||
// migration of non-Default Rules to global Skills. Idempotent and
|
||||
// self-gated on the flag, so it's safe to call on every flag-ready
|
||||
// notification (and a no-op for users without the flag).
|
||||
// Kick off the one-time migration of non-Default Rules to global
|
||||
// Skills, deferred until server feature flags arrive.
|
||||
//
|
||||
// The migration itself is idempotent and no longer gated on a flag,
|
||||
// but the deferral via `on_flags_ready` still matters: the migration
|
||||
// writes to the on-disk `GlobalKeyValueStore`, which dispatches work
|
||||
// on the `sqlezWorker` background thread. In `gpui::test` contexts,
|
||||
// server flags are never received, so this callback never fires —
|
||||
// which keeps that sqlite worker activity from racing with the
|
||||
// `TestScheduler` and tripping its non-determinism panic.
|
||||
{
|
||||
let fs = fs.clone();
|
||||
cx.on_flags_ready(move |_, cx| {
|
||||
|
|
@ -651,12 +679,6 @@ fn update_command_palette_filter(cx: &mut App) {
|
|||
.edit_predictions
|
||||
.provider;
|
||||
|
||||
// The Skills feature flag is loaded asynchronously, so this value may
|
||||
// be `false` before flags resolve. `update_command_palette_filter`
|
||||
// gets re-run from `cx.on_flags_ready` (see `init`), which means the
|
||||
// filter is reapplied with the correct value once flags arrive.
|
||||
let skills_enabled = cx.has_flag::<SkillsFeatureFlag>();
|
||||
|
||||
CommandPaletteFilter::update_global(cx, |filter, _| {
|
||||
use editor::actions::{
|
||||
AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
|
||||
|
|
@ -666,7 +688,6 @@ fn update_command_palette_filter(cx: &mut App) {
|
|||
TypeId::of::<AcceptEditPrediction>(),
|
||||
TypeId::of::<AcceptNextWordEditPrediction>(),
|
||||
TypeId::of::<AcceptNextLineEditPrediction>(),
|
||||
TypeId::of::<AcceptEditPrediction>(),
|
||||
TypeId::of::<ShowEditPrediction>(),
|
||||
TypeId::of::<NextEditPrediction>(),
|
||||
TypeId::of::<PreviousEditPrediction>(),
|
||||
|
|
@ -674,6 +695,10 @@ fn update_command_palette_filter(cx: &mut App) {
|
|||
];
|
||||
|
||||
let open_rules_library_action = [TypeId::of::<zed_actions::assistant::OpenRulesLibrary>()];
|
||||
let skill_creator_actions = [
|
||||
TypeId::of::<zed_actions::assistant::OpenSkillCreator>(),
|
||||
TypeId::of::<zed_actions::assistant::CreateSkillFromUrl>(),
|
||||
];
|
||||
|
||||
if disable_ai {
|
||||
filter.hide_namespace("agent");
|
||||
|
|
@ -724,15 +749,17 @@ fn update_command_palette_filter(cx: &mut App) {
|
|||
filter.show_namespace("multi_workspace");
|
||||
}
|
||||
|
||||
// Hide `assistant: open rules library` when Skills are enabled —
|
||||
// Rules are surfaced through the Skills UI in that case. Applied
|
||||
// after the disable-ai / agent-enabled branches so it overrides
|
||||
// the `show_namespace("assistant")` call above without affecting
|
||||
// the rest of that namespace's actions.
|
||||
if !disable_ai && skills_enabled {
|
||||
// Hide `assistant: open rules library` — Rules are surfaced
|
||||
// through the Skills UI now. Applied after the disable-ai /
|
||||
// agent-enabled branches so it overrides the
|
||||
// `show_namespace("assistant")` call above without affecting the
|
||||
// rest of that namespace's actions.
|
||||
if !disable_ai {
|
||||
filter.hide_action_types(&open_rules_library_action);
|
||||
filter.show_action_types(skill_creator_actions.iter());
|
||||
} else {
|
||||
filter.show_action_types(open_rules_library_action.iter());
|
||||
filter.hide_action_types(&skill_creator_actions);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -870,6 +897,26 @@ mod tests {
|
|||
!filter.is_hidden(&NewThread),
|
||||
"NewThread should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&NewTerminalThread),
|
||||
"NewTerminalThread should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&zed_actions::assistant::OpenSkillCreator),
|
||||
"OpenSkillCreator should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&zed_actions::assistant::CreateSkillFromUrl),
|
||||
"CreateSkillFromUrl should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&zed_actions::assistant::OpenGlobalAgentsMdRules),
|
||||
"OpenGlobalAgentsMdRules should be visible by default"
|
||||
);
|
||||
assert!(
|
||||
!filter.is_hidden(&zed_actions::assistant::OpenProjectAgentsMdRules),
|
||||
"OpenProjectAgentsMdRules should be visible by default"
|
||||
);
|
||||
});
|
||||
|
||||
// Disable agent
|
||||
|
|
@ -889,6 +936,18 @@ mod tests {
|
|||
filter.is_hidden(&NewThread),
|
||||
"NewThread should be hidden when agent is disabled"
|
||||
);
|
||||
assert!(
|
||||
filter.is_hidden(&NewTerminalThread),
|
||||
"NewTerminalThread should be hidden when agent is disabled"
|
||||
);
|
||||
assert!(
|
||||
filter.is_hidden(&zed_actions::assistant::OpenGlobalAgentsMdRules),
|
||||
"OpenGlobalAgentsMdRules should be hidden when agent is disabled"
|
||||
);
|
||||
assert!(
|
||||
filter.is_hidden(&zed_actions::assistant::OpenProjectAgentsMdRules),
|
||||
"OpenProjectAgentsMdRules should be hidden when agent is disabled"
|
||||
);
|
||||
});
|
||||
|
||||
// Test EditPredictionProvider
|
||||
|
|
|
|||
|
|
@ -12,7 +12,9 @@ use futures::{
|
|||
stream::BoxStream,
|
||||
};
|
||||
use gpui::{App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Subscription, Task};
|
||||
use language::{Buffer, IndentKind, LanguageName, Point, TransactionId, line_diff};
|
||||
use language::{
|
||||
Buffer, BufferEditSource, IndentKind, LanguageName, Point, TransactionId, line_diff,
|
||||
};
|
||||
use language_model::{
|
||||
CompletionIntent, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
|
||||
LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
|
||||
|
|
@ -978,7 +980,7 @@ impl CodegenAlternative {
|
|||
buffer.finalize_last_transaction(cx);
|
||||
buffer.start_transaction(cx);
|
||||
buffer.edit(edits, None, cx);
|
||||
buffer.end_transaction(cx)
|
||||
buffer.end_transaction_with_source(BufferEditSource::Agent, cx)
|
||||
});
|
||||
|
||||
if let Some(transaction) = transaction {
|
||||
|
|
|
|||