From 5faba6885aa9193ac9079f8a7ae82349ee0c7e99 Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:24:31 +0000 Subject: [PATCH 01/27] Docs: remote HTTP and WebSocket API contract --- docs/README.md | 1 + docs/remote.md | 203 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 204 insertions(+) create mode 100644 docs/remote.md diff --git a/docs/README.md b/docs/README.md index d5de5530..086e80a7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,7 @@ New here? Read [getting started](getting-started.md) first. | [Sessions and checkpoints](sessions-and-checkpoints.md) | Resuming and forking sessions, exporting and sharing, bug reports, compaction, `/rewind` | | [Migrating from another harness](migrating.md) | `azazel migrate` and `/migrate`: models, keys, skills, commands, MCP servers, settings, conversations and memory from pi, omp, jcode, Claude Code and Codex CLI | | [Background sessions, schedules and remote work](background-and-remote.md) | `azazel bg`, `ps`, `logs`, `attach`, `kill`; `azazel schedule` and triggers; working on another machine with `--ssh` | +| [Remote](remote.md) | Following and steering a session from a browser or a phone: pairing links, access levels, the HTTP and WebSocket API | ## Working as a team diff --git a/docs/remote.md b/docs/remote.md new file mode 100644 index 00000000..9ac77114 --- /dev/null +++ b/docs/remote.md @@ -0,0 +1,203 @@ +# Remote: follow and steer a session from a browser + +Remote opens a session of azazel in a web page, on this machine or on a phone. It shows what the session does as +it happens and, when you allow it, lets you answer approvals and questions, steer the run and stop it. + +## The model: master and child + +The azazel process is the **master**. It owns the session, the agents, the tools, the credentials and the +permissions, and it keeps running with or without a browser. The browser is a thin **child**: it sends commands and +draws the frames it gets back. Nothing of the session lives in the page; close the tab and the session goes on, open +another and it catches up from the session's own log. + +The page speaks the [RPC protocol](rpc.md) unchanged: one JSON object per WebSocket text message, in both +directions. This page describes what is around that: how a browser gets in, which commands each kind of access may +send, and the routes the server answers. + +## The HTTP and WebSocket API + +This section is the contract between the server (`crates/azazel-remote`) and the web page (`web/`). Everything the +page does goes through the routes below. + +### Conventions + +- The server listens on `127.0.0.1:7420` by default. The port is fixed because an installed page belongs to its + origin, port included. When it is taken, the server tries 7421 to 7429 and reports the one it took. +- Request and response bodies are JSON (`Content-Type: application/json`) unless a route says otherwise. +- An error is a status code with the body `{"error": ""}`. +- `POST` requests need the header `X-Azazel: 1`. A plain HTML form cannot send it, which closes the door on + cross-site posts. +- **Authentication.** Every `/api/` route except `POST /api/pair` needs a signed-in device: the cookie + `azazel_device` (what a browser has after pairing) or the header `Authorization: Bearer ` (scripts + and tests). Without one the answer is `401`. +- **Host check.** The `Host` header must name the server: `127.0.0.1:`, `localhost:`, `[::1]:`, a + LAN address of this machine, or the host of `remote.public_url`. Anything else gets `421`. This stops DNS + rebinding. +- **Origin check.** A request that has an `Origin` header must carry one of the allowed origins (the same + addresses as above, with the scheme the server uses, and `remote.public_url`); otherwise `403`. A request + signed in by cookie must have an `Origin`; a request with a Bearer token may leave it out. +- Answers on `/api/` carry `Cache-Control: no-store`. Every answer carries `X-Content-Type-Options: nosniff`, + `Referrer-Policy: no-referrer`, and a `Content-Security-Policy` of `default-src 'self'; connect-src 'self'; + img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'`. A page must therefore + have no inline scripts. +- Limits: a request body is at most 64 KiB; a WebSocket message at most 12 MiB. + +### Routes + +| Route | Needs | What it does | +|---|---|---| +| `GET /` and any other path that is not `/api/…` | nothing | The web page. A path that is not a built file answers with `index.html`, so the page can route by itself. Gzip is used when the browser accepts it. | +| `POST /api/pair` | the pairing secret | Turns a pairing secret into a signed-in device. | +| `GET /api/me` | a device | Who this device is and what it may do. | +| `GET /api/sessions` | a device | The sessions this server can reach. | +| `POST /api/links` | a device | Makes a new pairing link. | +| `POST /api/logout` | a device | Signs this device out. | +| `GET /api/ws/{id}` | a device | Upgrades to a WebSocket on one session. | + +An unknown route under `/api/` is `404`, a wrong method `405`. + +#### `POST /api/pair` + +Request: `{"secret": "", "bearer": false}`. `bearer` is optional. + +Answer `200`: `{"access": "view" | "control", "expires": "", "allow_bypass": false}`, with a +`Set-Cookie: azazel_device=; HttpOnly; SameSite=Strict; Path=/; Max-Age=` (and `Secure` when the +page is served over https). With `"bearer": true` the answer also has `"token"`, and no cookie is set: this is for +programs, which send the token as `Authorization: Bearer`. + +The secret works once. The answers: `401` for a secret that is unknown, used or expired, `429` once too many +attempts failed (see [limits](#limits)). + +#### `GET /api/me` + +Answer `200`: + +```json +{ + "access": "control", + "expires": "2026-11-16T09:30:00Z", + "allow_bypass": false, + "protocol": 1, + "version": "0.11.0" +} +``` + +`allow_bypass` tells the page whether it may offer the `bypass` mode. The page uses `access` to hide what the +server would refuse anyway. + +#### `GET /api/sessions` + +Answer `200`: `{"sessions": [ … ]}`, newest first. Each session: + +| Member | Meaning | +|---|---| +| `id` | What goes into `/api/ws/{id}`. | +| `name` | The session's name, or `null`. | +| `kind` | `background` for a background session (`terminal` is for the session of a terminal UI that shares itself). | +| `state` | `working`, `waiting for you`, `idle` or `interrupted`. | +| `cwd` | The project directory. | +| `cost_usd` | The cost so far, or `null`. | +| `mode` | The permission mode, or `null`. | +| `started` | RFC 3339. | + +The page asks again when it needs a fresh list; there is no push. + +#### `POST /api/links` + +Request: `{"access": "view" | "control"}`. A device with view access can make only view links (`403` otherwise). + +Answer `200`: `{"url": "/#pair=", "access": "view", "expires": ""}`. The link works once +and for `remote.link_minutes`. The page shows it as text and as a QR code. + +#### `POST /api/logout` + +Signs this device out and clears the cookie. Answer `204`. Its WebSockets close with `4401`. + +### The WebSocket + +`GET /api/ws/{id}` with the usual upgrade headers (`Upgrade: websocket`, `Sec-WebSocket-Version: 13`, a key). It +needs a device. A failed check before the upgrade is the plain HTTP answer (`401`, `403`, `421`, `429`); a failure +after it is a close code. + +Once upgraded: + +1. The server sends the session's `hello` frame as the first message. +2. The client sends `attach` (see [rpc.md](rpc.md#background-sessions)); until then the session + refuses everything else. The answer, the snapshot and the replay of what the client missed arrive as ordinary + frames. +3. After that the socket carries commands in one direction and frames (responses, events, requests) in the + other, as the RPC protocol defines them. + +Each message is one JSON object in a text message. A binary message closes the socket with `1003`. A command the +device's access does not allow is not forwarded: the server sends a `response` with the command's `id` and +`"success": false` and an `error`. A message that is not a command gets the same, with `"id": null`. A client that +sends more than 20 commands a second (a burst of 40 is fine) gets the same error for the surplus. + +A frame carries `"at"`, the position in the session's log. A client that was cut off attaches again with +`"since": ` and gets only what it missed. + +**Close codes** + +| Code | Meaning | What the page does | +|---|---|---| +| `1000` | The session ended. | Shows the session as ended; goes back to the list. | +| `1003` | A binary message was sent. | A bug of the client. | +| `1009` | A message was longer than 12 MiB. | Tells the user to send less. | +| `4401` | Not signed in, or the device was revoked, signed out or has expired. | Shows the pairing screen. Does not retry. | +| `4404` | No session has this id (it may have ended). | Goes back to the list. | +| `4408` | The client fell behind: 4096 frames were waiting to be sent. | Reconnects at once and attaches with `since`. | +| `4409` | Too many connections: 4 per device, 16 in all. | Waits, then retries with backoff. | + +### Pairing + +1. Whoever runs the server asks for a link (the command prints one at start, and `l` for control or `v` for view + makes another). It is `/#pair=`: 32 random bytes in base64url, valid once and for + `remote.link_minutes` (15). The secret is in the fragment so that it never reaches a server log, a proxy or a + `Referer`. +2. The person opens the link. The page reads the secret from `location.hash`, removes it with + `history.replaceState`, and sends it to `POST /api/pair`. +3. The server answers with the device cookie. The device stays signed in for `remote.device_hours` (24). The + server keeps only a hash of the token, in memory: ending the server signs every device out. +4. From then on the cookie authorises `GET /api/…` and the WebSocket. A device with control access can make more + links with `POST /api/links`. + +Ten failed pairing attempts in a row void every open link; a new one has to be made. + +### Limits + +| What | Limit | +|---|---| +| Failed pairings | 5 a minute per address, 20 a minute in all; after 10 in a row every link is void | +| WebSockets | 4 per device, 16 in all | +| Commands | 20 a second per connection, burst 40 | +| Message size | 12 MiB | +| Outbound queue | 4096 frames, then the socket is closed with `4408` | + +### What each access level may send + +The server checks every command before it reaches the session; this is the policy. The commands are those of +[rpc.md](rpc.md). + +| Access | Commands it may send | +|---|---| +| **view** | `attach`, `get_state`, `get_messages`, `get_agent_messages`, `get_tree`, `get_usage`, `list_models`, `list_roles`, `list_commands`. Frames arrive as for any client; a view client shows requests as "waiting for an answer" and cannot answer them. | +| **control** | Everything, except the commands in the next table. | + +A control device may not send: + +| Command | Why | +|---|---| +| `shell` | Running commands on this machine from a phone is not offered. | +| `export` with a `path` | It would write a file on this machine. | +| `resume_session` with a `path` | It would read a file on this machine. | +| `set_role` with `save` other than `session` | It would change the config files. | +| `save_preset` | It would change the config files. | +| `set_mode` to `bypass` | Refused unless `remote.allow_bypass` is set. | +| `run_command` of anything outside `cost`, `context`, `session`, `tools`, `todo`, `rules`, `doctor`, `skill:` and the commands extensions mark as safe | `trust`, `add-dir`, `hooks` and `forget-approvals` change what agents may do. | + +The server has no route that reads or writes files, so a browser cannot read `auth.json`, credentials or +configuration, cannot sign in or out of a provider and cannot change what is trusted. The server never approves +anything on its own. + +When several clients are attached, the first answer to an approval or a question wins: the others get +`request_closed`, and a second answer is refused. From cd174a1ae4b1591ac066b0a4f709f96a82769085 Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:37:16 +0000 Subject: [PATCH 02/27] RPC: resume with since/at/cursor/gap, paged get_messages, get_agent_messages --- CHANGELOG.md | 5 ++ crates/azazel-cli/src/detach.rs | 1 + crates/azazel-cli/src/host.rs | 48 ++++++++++- crates/azazel-cli/src/rpc.rs | 7 +- crates/azazel-cli/src/rpc/session.rs | 77 ++++++++++++++--- crates/azazel-cli/src/schedule/fire.rs | 1 + crates/azazel-cli/src/schedule/inbox.rs | 1 + crates/azazel-cli/src/tui/remote.rs | 1 + crates/azazel-cli/tests/it/background.rs | 100 +++++++++++++++++++++- crates/azazel-cli/tests/it/rpc_session.rs | 88 +++++++++++++++++++ crates/azazel-protocol/src/lib.rs | 29 ++++++- docs/rpc.md | 21 ++++- docs/rpc.schema.json | 67 ++++++++++++++- 13 files changed, 423 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8fc66fd..9b4fabbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ GitHub are its section here. ## [Unreleased] +### Added + +- RPC: a client of a background session can resume after a dropped connection. Every logged frame carries `at`, `attach` takes `since` (the `at` of the last frame it saw) and replays exactly the frames after it, and the answer has `cursor` and `gap` (true when `since` is unknown, so the client reloads with `get_messages`). +- RPC: `get_messages` takes `before` and `limit` to load the history in pages, and the new `get_agent_messages` reads the transcript of a sub-agent the same way. + ## [0.10.5] - 2026-11-15 ### Added diff --git a/crates/azazel-cli/src/detach.rs b/crates/azazel-cli/src/detach.rs index 2f4f338c..1aa9db43 100644 --- a/crates/azazel-cli/src/detach.rs +++ b/crates/azazel-cli/src/detach.rs @@ -812,6 +812,7 @@ pub async fn line_client(client: Client) -> u8 { .send(Command::Attach { pid: Some(std::process::id()), replay: Replay::Missed, + since: None, }) .await; let attached: Attached = match attached.map(serde_json::from_value) { diff --git a/crates/azazel-cli/src/host.rs b/crates/azazel-cli/src/host.rs index 842dbda1..64c85aa9 100644 --- a/crates/azazel-cli/src/host.rs +++ b/crates/azazel-cli/src/host.rs @@ -446,6 +446,7 @@ impl Host { text: text.to_string(), agent: None, }; + let frame = serde_json::to_value(&frame).map(|frame| self.stamped(frame)); if !self.live.busy { self.input_at.get_or_insert(self.log_len); } @@ -453,12 +454,19 @@ impl Host { kind: kind.to_string(), text: text.to_string(), }); - if let Ok(line) = serde_json::to_string(&frame) { + if let Ok(line) = frame.map(|frame| frame.to_string()) { self.log(&line); self.to_clients(&line, from); } } + /// Gives a frame that is about to be logged its `at`: the byte offset of its line in the + /// log, which is where a client resumes from after a dropped connection. + fn stamped(&self, mut frame: Value) -> Value { + frame["at"] = json!(self.log_len); + frame + } + /// The request `request_id` no longer waits: the clients that still show it are told, /// `except` the one that answered. fn closed(&self, request_id: &str, except: Option) { @@ -551,6 +559,8 @@ impl Host { // An answer in the making belongs to the client that asked. "btw_delta" => self.to_asker(frame), _ => { + // The line that is logged, sent and kept for a pending request carries its `at`. + let line = self.stamped(frame.clone()).to_string(); if of_lead && kind == "agent_start" { self.run_start = Some(self.input_at.take().unwrap_or(self.log_len)); } @@ -759,7 +769,9 @@ impl Host { } let (id, command) = Request::parse(line); let command = match command { - Ok(Command::Attach { pid, replay }) => return self.attach(conn, id, pid, replay), + Ok(Command::Attach { pid, replay, since }) => { + return self.attach(conn, id, pid, replay, since); + } Ok(Command::Stop { now }) => { self.stopping = true; if now { @@ -815,11 +827,14 @@ impl Host { } } - fn attach(&mut self, conn: u64, id: Value, pid: Option, replay: Replay) { + fn attach(&mut self, conn: u64, id: Value, pid: Option, replay: Replay, since: Option) { let alone = self.attached.is_empty(); self.attached.insert(conn, pid); self.settle(); self.drop_closed(); + // The frame a client resumes after must still be in the log, where `since` says. + let resumed = since.filter(|at| self.logged_at(*at)); + let gap = since.is_some() && resumed.is_none(); let attached = Attached { host: self.entry.id.clone(), pid: self.entry.pid, @@ -827,13 +842,18 @@ impl Host { session_file: self.entry.session_file.display().to_string(), clients: self.attached.len() as u32, snapshot: self.snapshot(), + cursor: self.log_len, + gap, }; self.respond( conn, id, serde_json::to_value(attached).map_err(|e| e.to_string()), ); + // A `since` the log does not know is a client that missed something. + let replay = if gap { Replay::Missed } else { replay }; let from = match replay { + _ if resumed.is_some() => resumed.unwrap_or_default(), Replay::Missed if alone => self.seen, // Somebody was here all along: what this client lacks is the run in progress. Replay::Missed => self.run_start.unwrap_or(self.log_len), @@ -841,6 +861,10 @@ impl Host { Replay::None => self.log_len, }; for line in self.logged(from) { + // The frame `since` names is the one the client has seen. + if resumed.is_some_and(|at| at_of(&line) == Some(at)) { + continue; + } // Requests are sent below, and only those that still wait. let is_request = serde_json::from_str::(&line).is_ok_and(|frame| { frame["type"] == "approval_request" || (frame["type"] == "ui_request" && asks(&frame)) @@ -850,10 +874,23 @@ impl Host { } } for pending in &self.pending { + // A request the client saw before it dropped is still on its screen. + if resumed.is_some_and(|at| at_of(&pending.line).is_some_and(|sent| sent <= at)) { + continue; + } self.to(conn, pending.line.clone()); } } + /// Whether the log holds a frame whose line starts at byte `at`. + fn logged_at(&self, at: u64) -> bool { + at < self.log_len + && self + .logged(at) + .first() + .is_some_and(|line| at_of(line) == Some(at)) + } + /// The lines of the log from byte `from` on. fn logged(&self, from: u64) -> Vec { let read = || -> std::io::Result { @@ -874,6 +911,11 @@ impl Host { } } +/// The `at` a logged frame carries. +fn at_of(line: &str) -> Option { + serde_json::from_str::(line).ok()?["at"].as_u64() +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] diff --git a/crates/azazel-cli/src/rpc.rs b/crates/azazel-cli/src/rpc.rs index 829797c7..3c7c2c2a 100644 --- a/crates/azazel-cli/src/rpc.rs +++ b/crates/azazel-cli/src/rpc.rs @@ -616,7 +616,12 @@ impl Session { } Command::ForkSession { entry_id } => self.fork_session(entry_id).await.map(Some), Command::ListSessions { query } => self.list_sessions(query.as_deref()).map(Some), - Command::GetMessages { leaf } => self.messages(leaf.as_deref()).map(Some), + Command::GetMessages { leaf, before, limit } => { + self.messages(leaf.as_deref(), before.as_deref(), limit).map(Some) + } + Command::GetAgentMessages { agent, before, limit } => { + self.agent_messages(&agent, before.as_deref(), limit).map(Some) + } Command::GetTree => data(self.tree()).map(Some), Command::SetLeaf { entry_id, before } => self.set_leaf(&entry_id, before).await.map(Some), Command::SetLabel { entry_id, label } => { diff --git a/crates/azazel-cli/src/rpc/session.rs b/crates/azazel-cli/src/rpc/session.rs index 46ab31db..58af1fc1 100644 --- a/crates/azazel-cli/src/rpc/session.rs +++ b/crates/azazel-cli/src/rpc/session.rs @@ -72,6 +72,38 @@ fn session_row(summary: SessionSummary, matches: Vec) -> SessionRow { } /// The name an entry's kind has in the session file. +/// The messages among `entries` (a branch, oldest first) as rows: all of them, or the last +/// `limit`, or the last `limit` before the entry `before`. +fn message_page( + entries: Vec, + before: Option<&str>, + limit: Option, +) -> Result, String> { + let mut rows: Vec = entries + .into_iter() + .filter_map(|entry| match entry.kind { + EntryKind::Message { message } => Some(MessageRow { + entry_id: entry.id, + timestamp: entry.timestamp, + message: serde_json::to_value(message).ok()?, + }), + _ => None, + }) + .collect(); + if let Some(before) = before { + let at = rows + .iter() + .position(|row| row.entry_id == before) + .ok_or_else(|| format!("no message `{before}` on this branch"))?; + rows.truncate(at); + } + if let Some(limit) = limit { + let skip = rows.len().saturating_sub(limit as usize); + rows.drain(..skip); + } + Ok(rows) +} + fn kind_name(kind: &EntryKind) -> &'static str { match kind { EntryKind::Message { .. } => "message", @@ -404,26 +436,43 @@ impl Session { data(rows) } - pub(super) fn messages(&self, leaf: Option<&str>) -> Result { + pub(super) fn messages( + &self, + leaf: Option<&str>, + before: Option<&str>, + limit: Option, + ) -> Result { let session = &self.active.session; if let Some(leaf) = leaf && session.entry(leaf).is_none() { return Err(format!("no entry `{leaf}` in this session")); } - let rows: Vec = session - .branch(leaf) - .into_iter() - .filter_map(|entry| match entry.kind { - EntryKind::Message { message } => Some(MessageRow { - entry_id: entry.id, - timestamp: entry.timestamp, - message: serde_json::to_value(message).ok()?, - }), - _ => None, - }) - .collect(); - data(rows) + data(message_page(session.branch(leaf), before, limit)?) + } + + /// The transcript of sub-agent `agent`, a page of it like [`Self::messages`]. + pub(super) fn agent_messages( + &self, + agent: &str, + before: Option<&str>, + limit: Option, + ) -> Result { + let team = self + .team + .as_ref() + .ok_or("there are no sub-agents in this session")?; + let path = team + .transcript_path(agent) + .ok_or_else(|| format!("no agent `{agent}` in this session"))?; + // An agent that has not written anything yet has no transcript file. + let entries = if path.exists() { + SessionStore::branch_of(&path) + .map_err(|e| format!("could not read the transcript of `{agent}`: {e}"))? + } else { + Vec::new() + }; + data(message_page(entries, before, limit)?) } pub(super) fn tree(&self) -> Vec { diff --git a/crates/azazel-cli/src/schedule/fire.rs b/crates/azazel-cli/src/schedule/fire.rs index e6e19947..a579cb6e 100644 --- a/crates/azazel-cli/src/schedule/fire.rs +++ b/crates/azazel-cli/src/schedule/fire.rs @@ -162,6 +162,7 @@ async fn send(entry: &running::Entry, prompt: &str) -> Result { .send(Command::Attach { pid: None, replay: Replay::None, + since: None, }) .await .map_err(|e| e.to_string())?; diff --git a/crates/azazel-cli/src/schedule/inbox.rs b/crates/azazel-cli/src/schedule/inbox.rs index 0d646993..c12947cb 100644 --- a/crates/azazel-cli/src/schedule/inbox.rs +++ b/crates/azazel-cli/src/schedule/inbox.rs @@ -794,6 +794,7 @@ async fn work( .send(Command::Attach { pid: None, replay: Replay::None, + since: None, }) .await .map_err(|e| e.to_string())?; diff --git a/crates/azazel-cli/src/tui/remote.rs b/crates/azazel-cli/src/tui/remote.rs index a4b18de3..2068c720 100644 --- a/crates/azazel-cli/src/tui/remote.rs +++ b/crates/azazel-cli/src/tui/remote.rs @@ -746,6 +746,7 @@ impl Remote { pid: Some(std::process::id()), // The UI shows where the session stands from the session itself. replay: Replay::None, + since: None, }, ) .await?; diff --git a/crates/azazel-cli/tests/it/background.rs b/crates/azazel-cli/tests/it/background.rs index 94503c96..e65523e4 100644 --- a/crates/azazel-cli/tests/it/background.rs +++ b/crates/azazel-cli/tests/it/background.rs @@ -713,6 +713,12 @@ struct Bridge { impl Bridge { /// Connects and attaches; returns the bridge and the data of `attach`. fn attach(sandbox: &Sandbox, id: &str, replay: &str) -> (Bridge, Value) { + Bridge::attach_with(sandbox, id, json!({ "replay": replay })) + } + + /// Connects and attaches with the members `extra` adds to the command; returns the + /// bridge and the data of `attach`. + fn attach_with(sandbox: &Sandbox, id: &str, extra: Value) -> (Bridge, Value) { let mut process = sandbox .azazel(&["rpc", "--attach", id]) .stdin(Stdio::piped()) @@ -726,7 +732,11 @@ impl Bridge { process, }; assert_eq!(bridge.next()["type"], "hello"); - bridge.send(json!({ "id": "attach", "type": "attach", "replay": replay })); + let mut attach = json!({ "id": "attach", "type": "attach" }); + for (key, value) in extra.as_object().unwrap() { + attach[key] = value.clone(); + } + bridge.send(attach); let attached = bridge.until(|frame| frame["id"] == "attach").pop().unwrap(); assert_eq!(attached["success"], true, "{attached}"); (bridge, attached["data"].clone()) @@ -886,6 +896,94 @@ fn two_clients_of_one_session_see_the_same_and_either_answers_an_approval() { assert_eq!(sandbox.ok(&["kill", &id]).trim(), format!("stopped {id}")); } +/// The `at` of every frame that has one. +fn cursors(frames: &[Value]) -> Vec { + frames.iter().filter_map(|frame| frame["at"].as_u64()).collect() +} + +/// A background session whose run waits for an approval, and the script that finishes it. +fn session_waiting_for_approval() -> (Sandbox, String) { + let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/scripts/write_read.json"); + let script: Value = serde_json::from_str(&std::fs::read_to_string(script).unwrap()).unwrap(); + let sandbox = Sandbox::new(&script); + let id = sandbox.bg(&[], "create hello"); + sandbox.wait_for_state(&id, "waiting for you"); + (sandbox, id) +} + +#[test] +fn a_client_that_dropped_is_sent_the_frames_after_its_last_one_and_no_other() { + let (sandbox, id) = session_waiting_for_approval(); + let (mut stays, attached) = Bridge::attach(&sandbox, &id, "all"); + let (drops, _) = Bridge::attach(&sandbox, &id, "all"); + let begin = attached["cursor"].as_u64().unwrap(); + let seen = drops.until(|frame| frame["type"] == "approval_request"); + let request = seen.last().unwrap().clone(); + stays.until(|frame| frame["type"] == "approval_request"); + // Every frame of the log says where it is; the order is the log's. + let first = cursors(&seen); + assert!( + first.len() > 2 && first.windows(2).all(|pair| pair[0] < pair[1]), + "{seen:?}" + ); + assert!(first.iter().all(|at| *at < begin), "{first:?} before {begin}"); + let last_seen = *first.last().unwrap(); + drops.detach(); + + // The run goes on while it is away. + let request_id = request["request_id"].as_str().unwrap(); + stays + .send(json!({ "id": 1, "type": "approval_response", "request_id": request_id, "decision": "allow" })); + let live = stays.until(|frame| frame["type"] == "idle"); + let missed: Vec = live + .iter() + .filter(|frame| frame["at"].is_u64()) + .cloned() + .collect(); + assert!(missed.len() > 2, "{live:?}"); + + let (back, resumed) = Bridge::attach_with(&sandbox, &id, json!({ "replay": "none", "since": last_seen })); + assert_eq!(resumed["gap"], Value::Null, "{resumed}"); + assert!(resumed["cursor"].as_u64().unwrap() > *cursors(&missed).last().unwrap()); + let replayed = back.until(|frame| frame["type"] == "idle"); + // Exactly what came after `last_seen`: nothing before it, nothing twice, nothing missing. + assert_eq!(cursors(&replayed), cursors(&missed), "{replayed:?}"); + assert_eq!(events(&replayed), events(&missed)); + assert!( + replayed.iter().all(|frame| frame["type"] != "approval_request"), + "the request was answered: {replayed:?}" + ); + back.detach(); + stays.detach(); + sandbox.wait_for_state(&id, "idle"); +} + +#[test] +fn a_since_the_log_does_not_hold_is_a_gap() { + let (sandbox, id) = session_waiting_for_approval(); + let (first, attached) = Bridge::attach(&sandbox, &id, "all"); + let cursor = attached["cursor"].as_u64().unwrap(); + first.detach(); + // Past the end of the log, and in the middle of a line. + for since in [cursor + 1000, 1] { + let (bridge, attached) = Bridge::attach_with(&sandbox, &id, json!({ "since": since })); + assert_eq!(attached["gap"], true, "since {since}: {attached}"); + assert_eq!(attached["cursor"], cursor, "{attached}"); + // The client is still told what waits for an answer. + bridge.until(|frame| frame["type"] == "approval_request"); + bridge.detach(); + } + // Resuming at a frame the log holds is no gap. + let (bridge, _) = Bridge::attach(&sandbox, &id, "all"); + let last = cursors(&bridge.until(|frame| frame["type"] == "approval_request")); + bridge.detach(); + let (bridge, attached) = Bridge::attach_with(&sandbox, &id, json!({ "since": last[last.len() - 2] })); + assert_eq!(attached["gap"], Value::Null, "{attached}"); + bridge.until(|frame| frame["type"] == "approval_request"); + bridge.detach(); + assert_eq!(sandbox.ok(&["kill", &id]).trim(), format!("stopped {id}")); +} + #[test] fn a_named_bg_sent_again_starts_no_second_session() { let sandbox = Sandbox::new(&json!({ "lead": [{ "reply": { "text": "Done." } }] })); diff --git a/crates/azazel-cli/tests/it/rpc_session.rs b/crates/azazel-cli/tests/it/rpc_session.rs index ef74516d..924eebb7 100644 --- a/crates/azazel-cli/tests/it/rpc_session.rs +++ b/crates/azazel-cli/tests/it/rpc_session.rs @@ -334,6 +334,94 @@ fn the_tree_is_read_moved_in_and_the_last_prompt_sent_again() { assert_eq!(client.finish(), Some(0)); } +#[test] +fn messages_are_read_in_pages_from_the_end_of_the_branch() { + let mut client = Client::start(&replies(&["one", "two", "three"]), &[]); + for prompt in ["a", "b", "c"] { + client.prompt(prompt); + } + let rows = client.ok(json!({ "type": "get_messages" })); + let ids: Vec = rows + .as_array() + .unwrap() + .iter() + .map(|row| row["entry_id"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(ids.len(), 6); + let texts = |rows: &Value| -> Vec { + rows.as_array() + .unwrap() + .iter() + .map(|row| row["message"]["content"][0]["text"].as_str().unwrap().to_string()) + .collect() + }; + + // The last page, oldest first; then the one before it, found through its first row. + let last = client.ok(json!({ "type": "get_messages", "limit": 2 })); + assert_eq!(texts(&last), ["c", "three"]); + let before = last[0]["entry_id"].as_str().unwrap(); + let middle = client.ok(json!({ "type": "get_messages", "before": before, "limit": 2 })); + assert_eq!(texts(&middle), ["b", "two"]); + // A page that reaches past the start is what is left. + let first = client.ok(json!({ "type": "get_messages", "before": middle[0]["entry_id"], "limit": 5 })); + assert_eq!(texts(&first), ["a", "one"]); + // Without a limit, `before` gives everything up to it. + let upto = client.ok(json!({ "type": "get_messages", "before": ids[3] })); + assert_eq!(texts(&upto), ["a", "one", "b"]); + assert_eq!( + client.error(json!({ "type": "get_messages", "before": "nope" })), + "no message `nope` on this branch" + ); + assert_eq!(client.finish(), Some(0)); +} + +#[test] +fn the_messages_of_a_sub_agent_are_read_from_its_transcript() { + let script: Value = + serde_json::from_str(&std::fs::read_to_string(fixture("mention.json")).unwrap()).unwrap(); + let mut client = Client::start(&script, &["--set", "roles.smol=[\"mock/scout\"]"]); + assert_eq!( + client.error(json!({ "type": "get_agent_messages", "agent": "scout-1" })), + "no agent `scout-1` in this session" + ); + client.ok(json!({ "type": "agent_mention", "name": "scout", "text": "where is the retry policy?" })); + client.until(|line| line["type"] == "idle" && line["agent"] == "lead"); + + let rows = client.ok(json!({ "type": "get_agent_messages", "agent": "scout-1" })); + let said: Vec<(&str, &str)> = rows + .as_array() + .unwrap() + .iter() + .map(|row| { + ( + row["message"]["role"].as_str().unwrap(), + row["message"]["content"][0]["text"].as_str().unwrap(), + ) + }) + .collect(); + assert_eq!( + said, + [ + ("user", "where is the retry policy?"), + ("assistant", "The retry policy is in src/retry.rs.") + ] + ); + let last = client.ok(json!({ "type": "get_agent_messages", "agent": "scout-1", "limit": 1 })); + assert_eq!(last.as_array().unwrap().len(), 1); + assert_eq!(last[0]["message"]["role"], "assistant"); + let first = client.ok(json!({ + "type": "get_agent_messages", "agent": "scout-1", "before": last[0]["entry_id"], "limit": 1 + })); + assert_eq!(first[0]["message"]["role"], "user"); + assert_eq!(client.finish(), Some(0)); +} + +fn fixture(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/fixtures/scripts") + .join(name) +} + /// The texts of the messages of `request` a user wrote, in order. fn user_texts(request: &Value) -> Vec { request["messages"] diff --git a/crates/azazel-protocol/src/lib.rs b/crates/azazel-protocol/src/lib.rs index b2f20b5f..ba9336a3 100644 --- a/crates/azazel-protocol/src/lib.rs +++ b/crates/azazel-protocol/src/lib.rs @@ -182,10 +182,25 @@ pub enum Command { query: Option, }, /// The messages from the start of the session to `leaf` (the current leaf when left out). - /// Answers with a list of [`MessageRow`]. + /// With `limit`, only the last `limit` of them, or with `before` (an entry id of the + /// branch) the last `limit` messages before that entry, so that a client can load the + /// history in pages. Answers with a list of [`MessageRow`], oldest first. GetMessages { #[serde(default, skip_serializing_if = "Option::is_none")] leaf: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + before: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + limit: Option, + }, + /// The messages of a sub-agent's transcript, paged like `get_messages`. Answers with a + /// list of [`MessageRow`], oldest first. + GetAgentMessages { + agent: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + before: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + limit: Option, }, /// Every entry of the session file. Answers with a list of [`TreeRow`]. GetTree, @@ -301,6 +316,11 @@ pub enum Command { pid: Option, #[serde(default)] replay: Replay, + /// Resumes after a frame: the `at` of the last frame the client saw. The frames + /// logged after it follow the response, and nothing before. When the log has no frame + /// with that `at`, `gap` is set in the answer and `replay` applies instead. + #[serde(default, skip_serializing_if = "Option::is_none")] + since: Option, }, /// Background sessions only, attached or not: ends the session once the lead has finished /// what it is doing; with `now` the lead is stopped first. The connection closes when the @@ -1137,6 +1157,13 @@ pub struct Attached { /// Where the session stands at this moment. #[serde(default)] pub snapshot: Snapshot, + /// The `at` the next frame will have: where live frames begin. + #[serde(default)] + pub cursor: u64, + /// True when `since` named a frame the log does not hold; the client resynchronises with + /// `get_messages`. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub gap: bool, } /// A background session at the moment a client attaches: what a client needs to show the work diff --git a/docs/rpc.md b/docs/rpc.md index 33e0fb77..481e7f7f 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -74,7 +74,8 @@ The session commands report the saved sessions and the open one, change which se | `resume_session` | `session_id` or `path` | Opens a saved session by its id (a unique prefix is enough) or by its file | The state | | `fork_session` | `entry_id?` | Continues in a copy of the open session, cut at `entry_id` when it is given | The state | | `list_sessions` | `query?` | The saved sessions of this project, most recently used first; with `query`, those whose messages contain it | A list of `{"id", "path", "name", "created", "updated", "first_prompt", "messages", "prompts", "pinned", "usage", "matches?"}` | -| `get_messages` | `leaf?` | The messages from the start of the session to `leaf` (the current leaf when left out) | A list of `{"entry_id", "timestamp", "message"}` | +| `get_messages` | `leaf?`, `before?`, `limit?` | The messages from the start of the session to `leaf` (the current leaf when left out). With `limit`, only the last `limit` of them; with `before` (the `entry_id` of a message on the branch), the last `limit` messages before that one, so a client can load the history in pages. An unknown `before` is an error | A list of `{"entry_id", "timestamp", "message"}`, oldest first | +| `get_agent_messages` | `agent`, `before?`, `limit?` | The messages of the transcript of sub-agent `agent`, paged like `get_messages`. An agent that has written nothing yet has none | A list of `{"entry_id", "timestamp", "message"}`, oldest first | | `get_tree` | | Every entry of the session file | A list of `{"id", "parent_id", "timestamp", "kind", "role?", "text?", "target_id?", "current"}`; `current` marks the branch that ends at the current leaf, and the journal entries of its runs (`run_started`, ...), which hang from it | | `set_leaf` | `entry_id`, `before?` | Continues the conversation from another entry of the tree; with `before`, from the entry before it, which is how a prompt is gone back to. When that leaves a branch the agent worked on, a [summary of it](sessions-and-checkpoints.md#branch-summaries) is added to the conversation a moment later and announced with a `notify` request | The state | | `set_label` | `entry_id`, `label` | Labels an entry of the tree; an empty label takes the label away | `null` | @@ -302,7 +303,7 @@ output to it. Two commands exist only there: | `type` | Members | Does | Response `data` | |---|---|---|---| -| `attach` | `pid?`, `replay?` | The first command on a connection: makes it a client of the session, beside any that are attached already. `replay` is `missed` (the default), `all` or `none`; those frames follow the response, then the requests that still wait for an answer, then everything the session does from then on | `{"host", "pid", "session_id", "session_file", "clients", "snapshot"}` | +| `attach` | `pid?`, `replay?`, `since?` | The first command on a connection: makes it a client of the session, beside any that are attached already. `replay` is `missed` (the default), `all` or `none`; those frames follow the response, then the requests that still wait for an answer, then everything the session does from then on. With `since`, the `at` of the last frame the client saw, the frames logged after that one follow instead, and `replay` is not used (see [resuming](#resuming-after-a-dropped-connection)) | `{"host", "pid", "session_id", "session_file", "clients", "snapshot", "cursor", "gap?"}` | | `stop` | `now?` | Ends the session once the lead has finished what it is doing; with `now` the lead is stopped first. Any connection may send it, attached or not. The connection closes when the session has ended | `null` | Until `attach` has been answered, every other command is refused. @@ -318,6 +319,17 @@ appended to `~/.azazel/run/.log`. another client is attached already, nobody was away: the frames of the run in progress are replayed, from the input that started it. +### Resuming after a dropped connection + +Every frame a background session logs carries `"at"`: the byte offset of its line in the log, which grows with +each frame. A client keeps the `at` of the last frame it read. When its connection drops, it connects again and +sends `attach` with `since` set to that value; it is replayed the frames logged after that one, exactly once each, +and the requests that still wait for an answer (those it saw before are not sent again). The response's `cursor` +is the `at` the next frame will have, where live frames begin. When the log has no frame with that `at` (a +different session, or an `at` that was never one), `gap` is `true`: the client cannot trust what it shows, so it +resynchronises with `get_messages`, and the frames of the run in progress are replayed as with `missed`. Frames +that are not logged (responses, `btw_delta`, `request_closed`) have no `at`. + `snapshot` in the response to `attach` says where the session stands at that moment, for a client that draws the session's state rather than replaying frames: @@ -332,6 +344,11 @@ session's state rather than replaying frames: `clients` counts the clients attached, the new one included. +| Member | Meaning | +|---|---| +| `cursor` | The `at` of the next frame: where live frames begin | +| `gap` | Present and `true` when `since` named no frame of the log | + ## Example Lines sent by the client are marked `>`, lines from azazel `<`. Long members are shortened with `…` and most `stream` lines are left out. diff --git a/docs/rpc.schema.json b/docs/rpc.schema.json index 9982a895..0f9059c8 100644 --- a/docs/rpc.schema.json +++ b/docs/rpc.schema.json @@ -383,12 +383,57 @@ "string", "null" ] + }, + "before": { + "type": [ + "string", + "null" + ] + }, + "limit": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 } }, "required": [ "type" ], - "description": "The messages from the start of the session to `leaf` (the current leaf when left out).\nAnswers with a list of [`MessageRow`]." + "description": "The messages from the start of the session to `leaf` (the current leaf when left out).\nWith `limit`, only the last `limit` of them, or with `before` (an entry id of the\nbranch) the last `limit` messages before that entry, so that a client can load the\nhistory in pages. Answers with a list of [`MessageRow`], oldest first." + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "get_agent_messages" + }, + "agent": { + "type": "string" + }, + "before": { + "type": [ + "string", + "null" + ] + }, + "limit": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + } + }, + "required": [ + "type", + "agent" + ], + "description": "The messages of a sub-agent's transcript, paged like `get_messages`. Answers with a\nlist of [`MessageRow`], oldest first." }, { "type": "object", @@ -828,6 +873,15 @@ "replay": { "$ref": "#/$defs/Replay", "default": "missed" + }, + "since": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0, + "description": "Resumes after a frame: the `at` of the last frame the client saw. The frames\nlogged after it follow the response, and nothing before. When the log has no frame\nwith that `at`, `gap` is set in the answer and `replay` applies instead." } }, "required": [ @@ -2972,6 +3026,17 @@ "queue": [], "pending": [] } + }, + "cursor": { + "type": "integer", + "format": "uint64", + "minimum": 0, + "description": "The `at` the next frame will have: where live frames begin.", + "default": 0 + }, + "gap": { + "type": "boolean", + "description": "True when `since` named a frame the log does not hold; the client resynchronises with\n`get_messages`." } }, "required": [ From 18654f0cbe4da572ccdf997b130751c25e2a0a58 Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:39:42 +0000 Subject: [PATCH 03/27] Config: the [remote] table --- crates/azazel-core/src/config.rs | 26 ++++++++++++++++++++++++-- crates/azazel-core/src/settings.rs | 8 ++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/azazel-core/src/config.rs b/crates/azazel-core/src/config.rs index 020e8db5..76962b73 100644 --- a/crates/azazel-core/src/config.rs +++ b/crates/azazel-core/src/config.rs @@ -317,6 +317,23 @@ config_table!(WebConfig { /// Search through the model provider's own search tool when the lead's model has one. provider_search: bool = true, }); +config_table!(RemoteConfig { + /// The port `azazel remote` listens on. It is fixed because an installed page belongs to its + /// origin, port included; 0 lets the system choose. + port: u16 = 7420, + /// The address of your own tunnel or reverse proxy in front of the server + /// (`https://remote.example.com`): the origin of the pairing links, and an origin the server + /// accepts. `azazel remote --tunnel` sets it for the run. + public_url: String = String::new(), + /// Minutes a pairing link works. + link_minutes: u64 = 15, + /// Hours a paired device stays signed in. + device_hours: u64 = 24, + /// Hide secrets in the messages and tool results sent to a browser. + redact: bool = true, + /// Let a browser with control access switch to the `bypass` mode. + allow_bypass: bool = false, +}); config_table!(GuardsConfig { /// Send the lead back once when it stops on changed code and ran no build or test since. done_check: bool = true, @@ -774,6 +791,7 @@ pub struct Config { /// Absent means lexical search only. pub embeddings: Option, pub web: WebConfig, + pub remote: RemoteConfig, pub mcp: McpConfig, pub media: MediaConfig, pub lsp: LspConfig, @@ -854,6 +872,7 @@ impl Default for Config { memory: MemoryConfig::default(), embeddings: None, web: WebConfig::default(), + remote: RemoteConfig::default(), mcp: McpConfig::default(), media: MediaConfig::default(), lsp: LspConfig::default(), @@ -886,7 +905,7 @@ impl Default for Config { } /// Top-level tables; an `AZAZEL___` environment variable overrides a key in one of them. -pub const TABLES: [&str; 41] = [ +pub const TABLES: [&str; 42] = [ "roles", "providers", "models", @@ -902,6 +921,7 @@ pub const TABLES: [&str; 41] = [ "memory", "embeddings", "web", + "remote", "mcp", "media", "lsp", @@ -1311,7 +1331,7 @@ pub fn concatenates(path: &[String]) -> bool { /// What a project's configuration may set only once the project is trusted, as `(table, key)`; no /// key means the whole table. Each of these names a program to run or widens permissions. /// `permissions.mode` joins them when it is `bypass`; see [`gated_settings`]. -const TRUST_GATED: [(&str, Option<&str>); 25] = [ +const TRUST_GATED: [(&str, Option<&str>); 26] = [ ("hooks", None), ("providers", None), ("permissions", Some("allow")), @@ -1341,6 +1361,8 @@ const TRUST_GATED: [(&str, Option<&str>); 25] = [ ("triggers", Some("github_authors")), ("triggers", Some("slack_users")), ("triggers", Some("slack_url")), + // A project must not open ports. + ("remote", None), ]; /// Every trust-gated setting as the docs name it (`hooks`, `permissions.allow`), `permissions.mode` diff --git a/crates/azazel-core/src/settings.rs b/crates/azazel-core/src/settings.rs index de27e88a..3b507ea1 100644 --- a/crates/azazel-core/src/settings.rs +++ b/crates/azazel-core/src/settings.rs @@ -509,6 +509,14 @@ settings! { "triggers.slack_users": List, "Slack users who may start runs", "Slack user ids; empty means nobody."; "triggers.slack_url": Text, "Slack API address", "Where the Slack bot token is sent."; } + Advanced / "Remote" { + "remote.port": Number, "Port", "The port `azazel remote` listens on; 7420 by default, 0 lets the system choose."; + "remote.public_url": Text, "Public address", "The address of your own tunnel or reverse proxy, such as https://remote.example.com; it becomes the link and an accepted origin."; + "remote.link_minutes": Number, "Link lifetime", "Minutes a pairing link works."; + "remote.device_hours": Number, "Device lifetime", "Hours a paired device stays signed in."; + "remote.redact": Switch, "Redact output", "Replace API keys and tokens in the messages and tool results sent to a browser."; + "remote.allow_bypass": Switch, "Allow bypass", "Let a browser with control access switch to the bypass mode."; + } Advanced / "Updates" { "update.check": Switch, "Look for updates", "Look for a newer release at most once a day, in the background."; "update.auto": Switch, "Install updates", "Download a newer release in the background and install it when the UI exits."; From 36c9f248309c6b9d038fbf318e93b319a7420edc Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:15:35 +0000 Subject: [PATCH 04/27] Web: SvelteKit frontend for azazel remote (MVP), mock host, fixtures, tests --- web/.gitignore | 8 + web/.prettierignore | 5 + web/.prettierrc | 8 + web/README.md | 48 + web/bun.lock | 801 +++++++++++ web/components.json | 13 + web/eslint.config.js | 35 + web/fixtures/commands.json | 250 ++++ web/fixtures/forms.jsonl | 42 + web/fixtures/mention.jsonl | 9 + web/fixtures/models.json | 250 ++++ web/fixtures/questions.jsonl | 64 + web/fixtures/showcase.jsonl | 48 + web/fixtures/state.json | 89 ++ web/fixtures/team_goal.jsonl | 114 ++ web/fixtures/write_read.jsonl | 30 + web/package.json | 53 + web/scripts/externalize-boot.ts | 38 + web/scripts/gen-types.ts | 29 + web/scripts/mock-host.ts | 649 +++++++++ web/src/app.css | 315 +++++ web/src/app.html | 18 + web/src/lib/answers.ts | 42 + web/src/lib/api.ts | 60 + web/src/lib/app.svelte.ts | 72 + web/src/lib/components/AgentHub.svelte | 114 ++ web/src/lib/components/ApprovalSheet.svelte | 199 +++ web/src/lib/components/Brand.svelte | 13 + web/src/lib/components/Composer.svelte | 260 ++++ web/src/lib/components/DiffView.svelte | 58 + web/src/lib/components/Markdown.svelte | 27 + web/src/lib/components/PairDevice.svelte | 87 ++ web/src/lib/components/QuestionSheet.svelte | 302 ++++ web/src/lib/components/SessionList.svelte | 76 + web/src/lib/components/Sheet.svelte | 113 ++ web/src/lib/components/StateDot.svelte | 20 + web/src/lib/components/StatusBar.svelte | 219 +++ web/src/lib/components/ToolCard.svelte | 101 ++ web/src/lib/components/Transcript.svelte | 199 +++ web/src/lib/components/UsagePanel.svelte | 133 ++ web/src/lib/components/ui/badge/badge.svelte | 50 + web/src/lib/components/ui/badge/index.ts | 2 + .../lib/components/ui/button/button.svelte | 89 ++ web/src/lib/components/ui/button/index.ts | 17 + .../ui/collapsible/collapsible-content.svelte | 7 + .../ui/collapsible/collapsible-trigger.svelte | 7 + .../ui/collapsible/collapsible.svelte | 11 + .../lib/components/ui/collapsible/index.ts | 13 + web/src/lib/components/ui/input/index.ts | 7 + web/src/lib/components/ui/input/input.svelte | 48 + web/src/lib/components/ui/separator/index.ts | 7 + .../components/ui/separator/separator.svelte | 21 + web/src/lib/components/ui/tabs/index.ts | 18 + .../components/ui/tabs/tabs-content.svelte | 17 + .../lib/components/ui/tabs/tabs-list.svelte | 40 + .../components/ui/tabs/tabs-trigger.svelte | 23 + web/src/lib/components/ui/tabs/tabs.svelte | 19 + web/src/lib/components/ui/textarea/index.ts | 7 + .../components/ui/textarea/textarea.svelte | 22 + web/src/lib/context.ts | 6 + web/src/lib/format.ts | 44 + web/src/lib/images.ts | 27 + web/src/lib/markdown.ts | 173 +++ web/src/lib/media.svelte.ts | 17 + web/src/lib/protocol/index.ts | 93 ++ web/src/lib/protocol/rpc.ts | 1257 +++++++++++++++++ web/src/lib/rpc/client.ts | 229 +++ web/src/lib/session/reduce.ts | 601 ++++++++ web/src/lib/session/session.svelte.ts | 282 ++++ web/src/lib/sessions.svelte.ts | 44 + web/src/lib/toasts.svelte.ts | 18 + web/src/lib/tools.ts | 79 ++ web/src/lib/utils.ts | 14 + web/src/routes/+layout.svelte | 127 ++ web/src/routes/+layout.ts | 2 + web/src/routes/+page.svelte | 60 + web/src/routes/s/[id]/+layout.svelte | 193 +++ web/src/routes/s/[id]/+page.svelte | 45 + .../routes/s/[id]/agents/[agent]/+page.svelte | 103 ++ web/static/favicon.svg | 1 + web/svelte.config.js | 12 + web/tests/unit/answers.test.ts | 53 + web/tests/unit/client.test.ts | 172 +++ web/tests/unit/markdown.test.ts | 75 + web/tests/unit/reduce.test.ts | 134 ++ web/tsconfig.json | 14 + web/vite.config.ts | 29 + 87 files changed, 9340 insertions(+) create mode 100644 web/.gitignore create mode 100644 web/.prettierignore create mode 100644 web/.prettierrc create mode 100644 web/README.md create mode 100644 web/bun.lock create mode 100644 web/components.json create mode 100644 web/eslint.config.js create mode 100644 web/fixtures/commands.json create mode 100644 web/fixtures/forms.jsonl create mode 100644 web/fixtures/mention.jsonl create mode 100644 web/fixtures/models.json create mode 100644 web/fixtures/questions.jsonl create mode 100644 web/fixtures/showcase.jsonl create mode 100644 web/fixtures/state.json create mode 100644 web/fixtures/team_goal.jsonl create mode 100644 web/fixtures/write_read.jsonl create mode 100644 web/package.json create mode 100644 web/scripts/externalize-boot.ts create mode 100644 web/scripts/gen-types.ts create mode 100644 web/scripts/mock-host.ts create mode 100644 web/src/app.css create mode 100644 web/src/app.html create mode 100644 web/src/lib/answers.ts create mode 100644 web/src/lib/api.ts create mode 100644 web/src/lib/app.svelte.ts create mode 100644 web/src/lib/components/AgentHub.svelte create mode 100644 web/src/lib/components/ApprovalSheet.svelte create mode 100644 web/src/lib/components/Brand.svelte create mode 100644 web/src/lib/components/Composer.svelte create mode 100644 web/src/lib/components/DiffView.svelte create mode 100644 web/src/lib/components/Markdown.svelte create mode 100644 web/src/lib/components/PairDevice.svelte create mode 100644 web/src/lib/components/QuestionSheet.svelte create mode 100644 web/src/lib/components/SessionList.svelte create mode 100644 web/src/lib/components/Sheet.svelte create mode 100644 web/src/lib/components/StateDot.svelte create mode 100644 web/src/lib/components/StatusBar.svelte create mode 100644 web/src/lib/components/ToolCard.svelte create mode 100644 web/src/lib/components/Transcript.svelte create mode 100644 web/src/lib/components/UsagePanel.svelte create mode 100644 web/src/lib/components/ui/badge/badge.svelte create mode 100644 web/src/lib/components/ui/badge/index.ts create mode 100644 web/src/lib/components/ui/button/button.svelte create mode 100644 web/src/lib/components/ui/button/index.ts create mode 100644 web/src/lib/components/ui/collapsible/collapsible-content.svelte create mode 100644 web/src/lib/components/ui/collapsible/collapsible-trigger.svelte create mode 100644 web/src/lib/components/ui/collapsible/collapsible.svelte create mode 100644 web/src/lib/components/ui/collapsible/index.ts create mode 100644 web/src/lib/components/ui/input/index.ts create mode 100644 web/src/lib/components/ui/input/input.svelte create mode 100644 web/src/lib/components/ui/separator/index.ts create mode 100644 web/src/lib/components/ui/separator/separator.svelte create mode 100644 web/src/lib/components/ui/tabs/index.ts create mode 100644 web/src/lib/components/ui/tabs/tabs-content.svelte create mode 100644 web/src/lib/components/ui/tabs/tabs-list.svelte create mode 100644 web/src/lib/components/ui/tabs/tabs-trigger.svelte create mode 100644 web/src/lib/components/ui/tabs/tabs.svelte create mode 100644 web/src/lib/components/ui/textarea/index.ts create mode 100644 web/src/lib/components/ui/textarea/textarea.svelte create mode 100644 web/src/lib/context.ts create mode 100644 web/src/lib/format.ts create mode 100644 web/src/lib/images.ts create mode 100644 web/src/lib/markdown.ts create mode 100644 web/src/lib/media.svelte.ts create mode 100644 web/src/lib/protocol/index.ts create mode 100644 web/src/lib/protocol/rpc.ts create mode 100644 web/src/lib/rpc/client.ts create mode 100644 web/src/lib/session/reduce.ts create mode 100644 web/src/lib/session/session.svelte.ts create mode 100644 web/src/lib/sessions.svelte.ts create mode 100644 web/src/lib/toasts.svelte.ts create mode 100644 web/src/lib/tools.ts create mode 100644 web/src/lib/utils.ts create mode 100644 web/src/routes/+layout.svelte create mode 100644 web/src/routes/+layout.ts create mode 100644 web/src/routes/+page.svelte create mode 100644 web/src/routes/s/[id]/+layout.svelte create mode 100644 web/src/routes/s/[id]/+page.svelte create mode 100644 web/src/routes/s/[id]/agents/[agent]/+page.svelte create mode 100644 web/static/favicon.svg create mode 100644 web/svelte.config.js create mode 100644 web/tests/unit/answers.test.ts create mode 100644 web/tests/unit/client.test.ts create mode 100644 web/tests/unit/markdown.test.ts create mode 100644 web/tests/unit/reduce.test.ts create mode 100644 web/tsconfig.json create mode 100644 web/vite.config.ts diff --git a/web/.gitignore b/web/.gitignore new file mode 100644 index 00000000..9ccbf8bd --- /dev/null +++ b/web/.gitignore @@ -0,0 +1,8 @@ +node_modules +.svelte-kit +build +.env +.env.* +tmp +test-results +playwright-report diff --git a/web/.prettierignore b/web/.prettierignore new file mode 100644 index 00000000..310c6041 --- /dev/null +++ b/web/.prettierignore @@ -0,0 +1,5 @@ +build +.svelte-kit +bun.lock +src/lib/protocol/rpc.ts +fixtures diff --git a/web/.prettierrc b/web/.prettierrc new file mode 100644 index 00000000..95730232 --- /dev/null +++ b/web/.prettierrc @@ -0,0 +1,8 @@ +{ + "useTabs": true, + "singleQuote": true, + "trailingComma": "none", + "printWidth": 100, + "plugins": ["prettier-plugin-svelte"], + "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }] +} diff --git a/web/README.md b/web/README.md new file mode 100644 index 00000000..77181764 --- /dev/null +++ b/web/README.md @@ -0,0 +1,48 @@ +# azazel web + +The browser front end of `azazel remote`: a SvelteKit 2 static SPA (Svelte 5 runes, TypeScript, Tailwind v4, +shadcn-svelte). It is a thin child: it sends RPC commands and draws frames. The session, agents, tools and +permissions live in the azazel process. The API it speaks is in [docs/remote.md](../docs/remote.md), the +protocol in [docs/rpc.md](../docs/rpc.md). + +Use **bun**. + +```sh +bun install +bun run gen:types # src/lib/protocol/rpc.ts from docs/rpc.schema.json +bun run check # svelte-check +bun run lint # eslint + prettier --check +bun run test # vitest: reducer over fixtures, markdown XSS, reconnect +bun run build # web/build, with no inline scripts (the server's CSP forbids them) +``` + +## Developing without Rust + +```sh +bun run dev:mock # a stand-in for `azazel remote` on :7420, replaying fixtures/*.jsonl +bun run dev # Vite on :5173, proxying /api (and the WebSocket) to :7420 +``` + +Open `http://localhost:5173/#pair=ctl-demo` (full control) or `#pair=view-demo` (watch only). The mock +sessions are `approve` (an approval waits), `team` (sub-agents), `showcase` (thinking, diff, markdown), +`forms` (a form question) and `ended`. + +Against the real server: `azazel remote`, then `AZAZEL_REMOTE=http://127.0.0.1:7420 bun run dev` and open +the link it prints, with the host replaced by `localhost:5173`. + +## Fixtures + +`fixtures/*.jsonl` are frames recorded from `azazel rpc` with the scripted provider (a `--features +test-support` build, `AZAZEL_MOCK_SCRIPT=tests/fixtures/scripts/.json`), one JSON frame per line. +`models.json`, `commands.json` and `state.json` are recorded query answers. Record new ones the same way +rather than writing frames by hand. + +## Layout + +- `src/lib/rpc/client.ts`: the socket, command ids, attach with `since`, reconnect with backoff. +- `src/lib/session/reduce.ts`: pure frame → model reducer. `session.svelte.ts`: runes state around it. +- `src/lib/markdown.ts`: marked + highlight.js + DOMPurify. Model text is untrusted. +- `src/lib/components/`: transcript, tool cards, diff view, approval and question sheets, composer, pickers, + agent hub, usage. +- `scripts/mock-host.ts`: the mock server. `scripts/externalize-boot.ts`: moves SvelteKit's inline start + script into a file after the build. diff --git a/web/bun.lock b/web/bun.lock new file mode 100644 index 00000000..45e7ca8c --- /dev/null +++ b/web/bun.lock @@ -0,0 +1,801 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "azazel-web", + "devDependencies": { + "@eslint/js": "^9", + "@internationalized/date": "^3.12.0", + "@lucide/svelte": "^1.73.0", + "@sveltejs/adapter-static": "^3", + "@sveltejs/kit": "^2", + "@sveltejs/vite-plugin-svelte": "^6", + "@tailwindcss/vite": "^4", + "@testing-library/svelte": "^5.4.2", + "@types/dompurify": "^3.0.5", + "@types/node": "^26.6.6", + "bits-ui": "^2.21.0", + "clsx": "^2.1.1", + "dompurify": "^3.4.18", + "eslint": "^9", + "eslint-plugin-svelte": "^3.24.1", + "globals": "^17.14.0", + "highlight.js": "^11.12.0", + "jsdom": "^26", + "json-schema-to-typescript": "^16.0.0", + "marked": "^18.2.0", + "prettier": "^3.10.1", + "prettier-plugin-svelte": "^4.1.1", + "svelte": "^5.57.3", + "svelte-check": "^4.7.8", + "svelte-eslint-parser": "^1.10.1", + "tailwind-merge": "^3.7.0", + "tailwind-variants": "^3.3.0", + "tailwindcss": "^4", + "typescript": "^5.9", + "typescript-eslint": "^8.72.2", + "uqr": "^0.1.3", + "vite": "^7", + "vitest": "^3", + }, + }, + }, + "packages": { + "@apidevtools/json-schema-ref-parser": ["@apidevtools/json-schema-ref-parser@11.9.3", "", { "dependencies": { "@jsdevtools/ono": "^7.1.3", "@types/json-schema": "^7.0.15", "js-yaml": "^4.1.0" } }, "sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ=="], + + "@asamuzakjp/css-color": ["@asamuzakjp/css-color@3.2.0", "", { "dependencies": { "@csstools/css-calc": "^2.1.3", "@csstools/css-color-parser": "^3.0.9", "@csstools/css-parser-algorithms": "^3.0.4", "@csstools/css-tokenizer": "^3.0.3", "lru-cache": "^10.4.3" } }, "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw=="], + + "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], + + "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + + "@babel/runtime": ["@babel/runtime@7.29.14", "", {}, "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw=="], + + "@csstools/color-helpers": ["@csstools/color-helpers@5.1.0", "", {}, "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA=="], + + "@csstools/css-calc": ["@csstools/css-calc@2.1.4", "", { "peerDependencies": { "@csstools/css-parser-algorithms": "^3.0.5", "@csstools/css-tokenizer": "^3.0.4" } }, "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ=="], + + "@csstools/css-color-parser": ["@csstools/css-color-parser@3.1.0", "", { "dependencies": { "@csstools/color-helpers": "^5.1.0", "@csstools/css-calc": "^2.1.4" }, "peerDependencies": { "@csstools/css-parser-algorithms": "^3.0.5", "@csstools/css-tokenizer": "^3.0.4" } }, "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA=="], + + "@csstools/css-parser-algorithms": ["@csstools/css-parser-algorithms@3.0.5", "", { "peerDependencies": { "@csstools/css-tokenizer": "^3.0.4" } }, "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ=="], + + "@csstools/css-tokenizer": ["@csstools/css-tokenizer@3.0.4", "", {}, "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.2", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.28.2", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.2", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.2", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.2", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="], + + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.2", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="], + + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="], + + "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="], + + "@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.10.1", "", { "dependencies": { "eslint-visitor-keys": "^3.4.3" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg=="], + + "@eslint-community/regexpp": ["@eslint-community/regexpp@4.12.3", "", {}, "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ=="], + + "@eslint/config-array": ["@eslint/config-array@0.21.2", "", { "dependencies": { "@eslint/object-schema": "^2.1.7", "debug": "^4.3.1", "minimatch": "^3.1.5" } }, "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw=="], + + "@eslint/config-helpers": ["@eslint/config-helpers@0.4.2", "", { "dependencies": { "@eslint/core": "^0.17.0" } }, "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw=="], + + "@eslint/core": ["@eslint/core@0.17.0", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ=="], + + "@eslint/eslintrc": ["@eslint/eslintrc@3.3.7", "", { "dependencies": { "ajv": "^6.14.0", "debug": "^4.3.2", "espree": "^10.0.1", "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.3.2", "minimatch": "^3.1.5", "strip-json-comments": "^3.1.1" } }, "sha512-F42g89Qd5oAWtp0k0nnSrjziAKza7w8SVT4mStc18LZMaRb4J1HQAHLCalEtDCxrTuksx7NU9qsmeLwpOfPqWw=="], + + "@eslint/js": ["@eslint/js@9.39.5", "", {}, "sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A=="], + + "@eslint/object-schema": ["@eslint/object-schema@2.1.7", "", {}, "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA=="], + + "@eslint/plugin-kit": ["@eslint/plugin-kit@0.4.1", "", { "dependencies": { "@eslint/core": "^0.17.0", "levn": "^0.4.1" } }, "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA=="], + + "@floating-ui/core": ["@floating-ui/core@1.8.0", "", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="], + + "@floating-ui/dom": ["@floating-ui/dom@1.8.0", "", { "dependencies": { "@floating-ui/core": "^1.8.0", "@floating-ui/utils": "^0.2.12" } }, "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg=="], + + "@floating-ui/utils": ["@floating-ui/utils@0.2.12", "", {}, "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww=="], + + "@humanfs/core": ["@humanfs/core@0.19.2", "", { "dependencies": { "@humanfs/types": "^0.15.0" } }, "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA=="], + + "@humanfs/node": ["@humanfs/node@0.16.8", "", { "dependencies": { "@humanfs/core": "^0.19.2", "@humanfs/types": "^0.15.0", "@humanwhocodes/retry": "^0.4.0" } }, "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ=="], + + "@humanfs/types": ["@humanfs/types@0.15.0", "", {}, "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q=="], + + "@humanwhocodes/module-importer": ["@humanwhocodes/module-importer@1.0.1", "", {}, "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA=="], + + "@humanwhocodes/retry": ["@humanwhocodes/retry@0.4.3", "", {}, "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ=="], + + "@internationalized/date": ["@internationalized/date@3.12.4", "", { "dependencies": { "@swc/helpers": "^0.5.0" } }, "sha512-M1dEn4c1U1HsSlaVR8upZtSqvXrTkHDfv18H01uCSJyjVLDxnBR38v/fMxecmlwXKR4i9HeZcmgQAPE6A+aGJQ=="], + + "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], + + "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.3", "", {}, "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + + "@jsdevtools/ono": ["@jsdevtools/ono@7.1.3", "", {}, "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg=="], + + "@lucide/svelte": ["@lucide/svelte@1.73.0", "", { "peerDependencies": { "svelte": "^5" } }, "sha512-Rz1uA9aTJ7HA/j2Hf9Dm2OVM8NtkzHnNeIQvVWoUkpf1ZD/7dR9cB4ftjbOiWAeJrKkEAVvTDrcVtITFdx6KAA=="], + + "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], + + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.68.3", "", { "os": "android", "cpu": "arm" }, "sha512-mqfypgH/liYjaSCoPI4erckUcROgZtmFUUmyOJ05oyayi/tVqOEYAzWP7ufqCoCT3xB31Fw4XIVO/jX42hYvKA=="], + + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.68.3", "", { "os": "android", "cpu": "arm64" }, "sha512-5tY+GC/1gpt79cKS2DQzu6iD824j6BmI4q5Zb6qftZ4kWqIQmvR3DD4eJ2Gclu6/nVMYDk2IVpqxypWOiAuWJg=="], + + "@rollup/rollup-android-x64": ["@rollup/rollup-android-x64@4.68.3", "", { "os": "android", "cpu": "x64" }, "sha512-nDBcQ/o3PMmGxmAzGBJFn+n1rb83Va9WSdFIq1AHmlEF3tuibVsyJ3kG5x13r7VIy6WI8SvzCdHVNSlSDIdj8w=="], + + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.68.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-dra5zl0QWKkIkaMgNDNPC19gkMlPAfAf41yWlkGztXMIvUQrX9XWZFQRw7abhH3nks+XZGQpybINAxT2pKdFew=="], + + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.68.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-xo5xeo/AjEB/ArzQjGn0JRDZuybZicQ5O3VPfko6ocH1li/qNrN4p5+R/WgjavzRz6UwAOaqsau7VvRQA6i6AA=="], + + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.68.3", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-zdckkcxHDEEKyDbC1t21DeaaiKGymxbkBU9c3zyfaaz+8N96ItJw4nmzHhZF+Mukgt906fnf2tsc90pVyStuHA=="], + + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.68.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-9oXqI7g/ycEz7TyicdGBC4sL6PfWMXAx8u15f/nd7lYkCLJd8U8VdBfbpc4SSnRBU/e7aPALve3mhzasGDeCYg=="], + + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.68.3", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-hbgT4NlaOELE3D5UUzSqF+OFgwz4Scvo2SQD9nZJUFjdIsg9Kg3FabQauUxkHKY9N5yjNXfXRRmiKNN4JpLmFA=="], + + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.68.3", "", { "os": "linux", "cpu": "arm", "libc": "musl" }, "sha512-yECcXZ/Bl+JVRhLFgld42rYrXgPdE0LtySGAmmmH6OtkaJM17A4cWG/eCzDymMVb52/jZjW0R54YrTHj4xXlSA=="], + + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.68.3", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-q4Q4/B7wyqM+TFqY5tJYQlaz5+ksGopcRmMeMdu4q6eaPK7N1PymTjIaH5LL32mMJBqIzpRof7BhlYLim5JgNQ=="], + + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.68.3", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-Ich3TGl/7GqhQ6G6jVPzgGQGJjd3E5hECxSVanPYchy6Vwcq+WI8wG/gmEMilHNy+ZYCR6U8EN50EejG3TaIgw=="], + + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.68.3", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-URBmOhwv4Y0Hi5Hhxc3cmqZLtQlx55DOs5PUhhITDC3zu0qwAfhcNAFAIwAhOUdA6NFVEck07CNZX6cBEs1vTg=="], + + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.68.3", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-PTdJXuZplRyaE3ECArlbZubI2LlUHWm0oCipCexnE/8LM+L7qIqUiNbU0piBxt46EB5zxXX+cpmDvHX4Z3WwcQ=="], + + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.68.3", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-IlSQPDExSm9YdtrWeZIHj87GPXI9lYygRvHVwQ1o9t91JHIiB2CihrvNIASpc/zI28atqm04jS3proaQuaJMww=="], + + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.68.3", "", { "os": "linux", "cpu": "ppc64", "libc": "musl" }, "sha512-O2ssyDcBTZkH5v2P/9ZaXJreL0hCKvUA5UwuHn0jCKeMLKi4GhspZJ1I5FT5QsHtJ/dPx4pup7pg/Lw0emeY0Q=="], + + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.68.3", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-fesqagxcnc87lH2+aBWne/tFCmQVIGH+YezjY1wQwbUODuTBBlhHoyxju6umwn8LnjHVanjpoeaQdLsXP8JQSQ=="], + + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.68.3", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-WAjFDtLW3HjJ2RAytKoWdFwlK/hW8rJHrjhRZFw14nR+c9JN//WIlSBkyXUjEYCNOFs2sGLNutOEPQG4iVYHgA=="], + + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.68.3", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-+fZiTeHV/1fy/14dRqE4thjYwUOABL6qQjxElOEQg2oHLkCamO8dxhHphVgD4+pFxtVEUIWxsGVduPtwnAlvbg=="], + + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.68.3", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-pfn4Zd9Ic3lEaSwW3GsQhTIDd7929C+eiEkOutsSCT2IHD6rDLblwmMQkgeGOso0oDo9Jk/ERtFdtFr9ElLs+g=="], + + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.68.3", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-eUXzaeNQbKXKNqseL3g/usUqOPmRu+DbQsvwr9MXMdV+VQFUNb9bcWSNAAs/TRV95PCbFK46kLzHEOhFSzujsg=="], + + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.68.3", "", { "os": "openbsd", "cpu": "x64" }, "sha512-OiUclE7QDU4H/hr3ACRHhVGKWl+gNx+6Emignfq0hmNmzzTkZnT79wzB9NXKd0QH16S4t/wVqlAFBfC17nkZ5A=="], + + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.68.3", "", { "os": "none", "cpu": "arm64" }, "sha512-s6EclDWmk6zvIfk1yixgYthk7xHNx0xu5cEF5RDpS4IHNTpfswRX6xOXVG5cHF5xWn0B6EpDGARhPQ520KTlsA=="], + + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.68.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-G2xnmxGnU8XHLwtjnnXNRcLrub+Af3nm9VQ1QzL2aEiAL7woBdRgTCZBslJl8umA+YMqdEFpUh9kJB/Vyzk2wQ=="], + + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.68.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-Y/4tApNVrMUYWbAHsyRWJgwuuJOfhTNhA2B04Xpa6+G9btkPZ9kU3XagUKzPTwF3hg36NpQk748JsnoTVho67Q=="], + + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.68.3", "", { "os": "win32", "cpu": "x64" }, "sha512-i2vH/OA5BcW+TdNg12ZTRC4rn+vILaPMP9CvHqnv+QEpMjBHGGNLo4k4EnEqzjYvTD6x1Xark9WhsQbH4bTzUQ=="], + + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.68.3", "", { "os": "win32", "cpu": "x64" }, "sha512-ADb1Uz2MNM0sxVpAlMNdQG16Hw4sgW1aqVL7NeqBMpcZeiHb192d7W6shZdMQs33D+w9ihDYBBPsYqqc4MlD8w=="], + + "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + + "@sveltejs/acorn-typescript": ["@sveltejs/acorn-typescript@1.0.13", "", { "peerDependencies": { "acorn": "^8.9.0" } }, "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ=="], + + "@sveltejs/adapter-static": ["@sveltejs/adapter-static@3.0.11", "", { "peerDependencies": { "@sveltejs/kit": "^2.0.0" } }, "sha512-DyX1bWx9uiPxzq7Mr+jnxqY+w3UhE3pYy5D1LcfdS++2KZTHSZBD60BoP44LjVgtGILfeOQCF8ESqzmLVrz4Ng=="], + + "@sveltejs/kit": ["@sveltejs/kit@2.70.4", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@sveltejs/acorn-typescript": "^1.0.9", "@types/cookie": "^0.6.0", "acorn": "^8.16.0", "cookie": "^0.6.0", "devalue": "^5.8.1", "esm-env": "^1.2.2", "kleur": "^4.1.5", "magic-string": "^0.30.5", "mrmime": "^2.0.0", "set-cookie-parser": "^3.0.0", "sirv": "^3.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0", "@sveltejs/vite-plugin-svelte": "^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0", "svelte": "^4.0.0 || ^5.0.0-next.0", "typescript": "^5.3.3 || ^6.0.0", "vite": "^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0" }, "optionalPeers": ["@opentelemetry/api", "typescript"], "bin": { "svelte-kit": "svelte-kit.js" } }, "sha512-IDfRnmSXgtlmv5Q+KyvP1HGr2XUvZooo0yBwzTnJA7CBbczy+sSMHXubfbcI9gz4EKksRSyYx44y/eCcf/B+rg=="], + + "@sveltejs/load-config": ["@sveltejs/load-config@0.2.3", "", {}, "sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ=="], + + "@sveltejs/vite-plugin-svelte": ["@sveltejs/vite-plugin-svelte@6.2.4", "", { "dependencies": { "@sveltejs/vite-plugin-svelte-inspector": "^5.0.0", "deepmerge": "^4.3.1", "magic-string": "^0.30.21", "obug": "^2.1.0", "vitefu": "^1.1.1" }, "peerDependencies": { "svelte": "^5.0.0", "vite": "^6.3.0 || ^7.0.0" } }, "sha512-ou/d51QSdTyN26D7h6dSpusAKaZkAiGM55/AKYi+9AGZw7q85hElbjK3kEyzXHhLSnRISHOYzVge6x0jRZ7DXA=="], + + "@sveltejs/vite-plugin-svelte-inspector": ["@sveltejs/vite-plugin-svelte-inspector@5.0.2", "", { "dependencies": { "obug": "^2.1.0" }, "peerDependencies": { "@sveltejs/vite-plugin-svelte": "^6.0.0-next.0", "svelte": "^5.0.0", "vite": "^6.3.0 || ^7.0.0" } }, "sha512-TZzRTcEtZffICSAoZGkPSl6Etsj2torOVrx6Uw0KpXxrec9Gg6jFWQ60Q3+LmNGfZSxHRCZL7vXVZIWmuV50Ig=="], + + "@swc/helpers": ["@swc/helpers@0.5.24", "", {}, "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg=="], + + "@tailwindcss/node": ["@tailwindcss/node@4.3.5", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.5", "jiti": "^2.7.0", "lightningcss": "1.33.0", "magic-string": "^1.1.0", "source-map-js": "^1.2.1", "tailwindcss": "4.3.5" } }, "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g=="], + + "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.5", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.5", "@tailwindcss/oxide-darwin-arm64": "4.3.5", "@tailwindcss/oxide-darwin-x64": "4.3.5", "@tailwindcss/oxide-freebsd-x64": "4.3.5", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", "@tailwindcss/oxide-linux-x64-musl": "4.3.5", "@tailwindcss/oxide-wasm32-wasi": "4.3.5", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" } }, "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg=="], + + "@tailwindcss/oxide-android-arm64": ["@tailwindcss/oxide-android-arm64@4.3.5", "", { "os": "android", "cpu": "arm64" }, "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q=="], + + "@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/oxide-darwin-arm64@4.3.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ=="], + + "@tailwindcss/oxide-darwin-x64": ["@tailwindcss/oxide-darwin-x64@4.3.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ=="], + + "@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/oxide-freebsd-x64@4.3.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg=="], + + "@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/oxide-linux-arm-gnueabihf@4.3.5", "", { "os": "linux", "cpu": "arm" }, "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA=="], + + "@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/oxide-linux-arm64-gnu@4.3.5", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ=="], + + "@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/oxide-linux-arm64-musl@4.3.5", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw=="], + + "@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/oxide-linux-x64-gnu@4.3.5", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g=="], + + "@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/oxide-linux-x64-musl@4.3.5", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg=="], + + "@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/oxide-wasm32-wasi@4.3.5", "", { "dependencies": { "@emnapi/core": "^1.11.3", "@emnapi/runtime": "^1.11.3", "@emnapi/wasi-threads": "^1.2.3", "@napi-rs/wasm-runtime": "^1.2.2", "@tybys/wasm-util": "^0.10.3", "tslib": "^2.8.1" } }, "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw=="], + + "@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/oxide-win32-arm64-msvc@4.3.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg=="], + + "@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/oxide-win32-x64-msvc@4.3.5", "", { "os": "win32", "cpu": "x64" }, "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg=="], + + "@tailwindcss/vite": ["@tailwindcss/vite@4.3.5", "", { "dependencies": { "@tailwindcss/node": "4.3.5", "@tailwindcss/oxide": "4.3.5", "tailwindcss": "4.3.5" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-BCNiY0a1ZjdOHVqw7kyb7U72BwfMF3dfUuN+tQsLWky/J5JOI/r7abibglXfygrZhVO/3u3V+E25kkKTeMkXaQ=="], + + "@testing-library/dom": ["@testing-library/dom@10.4.2", "", { "dependencies": { "@babel/code-frame": "^7.10.4", "@babel/runtime": "^7.12.5", "@types/aria-query": "^5.0.1", "aria-query": "5.3.0", "dom-accessibility-api": "^0.5.9", "lz-string": "^1.5.0", "picocolors": "1.1.1", "pretty-format": "^27.0.2" } }, "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q=="], + + "@testing-library/svelte": ["@testing-library/svelte@5.4.2", "", { "dependencies": { "@testing-library/dom": "9.x.x || 10.x.x", "@testing-library/svelte-core": "1.1.3" }, "peerDependencies": { "svelte": "^3 || ^4 || ^5 || ^5.0.0-next.0", "vite": "*", "vitest": "*" }, "optionalPeers": ["vite", "vitest"] }, "sha512-4o31E4HGo5BU5KwPkulNRocEden+7Tt9JYm9uhln5ajF7DULeyFA46BBWVfKJ8Ms9B3JmOFPTIiVamH7n3KpuQ=="], + + "@testing-library/svelte-core": ["@testing-library/svelte-core@1.1.3", "", { "peerDependencies": { "svelte": "^3 || ^4 || ^5 || ^5.0.0-next.0" } }, "sha512-KkMAvXeWorxN2Yn0kdC1lfoAItxpoj4uOWzxK5leDrNxonLvS5nwBFvztrroyTszQ0Wf/EU6iLT8JhY5qcn22g=="], + + "@types/aria-query": ["@types/aria-query@5.0.4", "", {}, "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw=="], + + "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], + + "@types/cookie": ["@types/cookie@0.6.0", "", {}, "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA=="], + + "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], + + "@types/dompurify": ["@types/dompurify@3.0.5", "", { "dependencies": { "@types/trusted-types": "*" } }, "sha512-1Wg0g3BtQF7sSb27fJQAKck1HECM6zV1EB66j8JH9i3LCjYabJa0FSdiSgsD5K/RbrsR0SiraKacLB+T8ZVYAg=="], + + "@types/estree": ["@types/estree@1.0.10", "", {}, "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g=="], + + "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], + + "@types/lodash": ["@types/lodash@4.17.27", "", {}, "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew=="], + + "@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], + + "@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="], + + "@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.72.2", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.72.2", "@typescript-eslint/type-utils": "8.72.2", "@typescript-eslint/utils": "8.72.2", "@typescript-eslint/visitor-keys": "8.72.2", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.72.2", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g=="], + + "@typescript-eslint/parser": ["@typescript-eslint/parser@8.72.2", "", { "dependencies": { "@typescript-eslint/scope-manager": "8.72.2", "@typescript-eslint/types": "8.72.2", "@typescript-eslint/typescript-estree": "8.72.2", "@typescript-eslint/visitor-keys": "8.72.2", "debug": "^4.4.3" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA=="], + + "@typescript-eslint/project-service": ["@typescript-eslint/project-service@8.72.2", "", { "dependencies": { "@typescript-eslint/tsconfig-utils": "^8.72.2", "@typescript-eslint/types": "^8.72.2", "debug": "^4.4.3" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw=="], + + "@typescript-eslint/scope-manager": ["@typescript-eslint/scope-manager@8.72.2", "", { "dependencies": { "@typescript-eslint/types": "8.72.2", "@typescript-eslint/visitor-keys": "8.72.2" } }, "sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ=="], + + "@typescript-eslint/tsconfig-utils": ["@typescript-eslint/tsconfig-utils@8.72.2", "", { "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w=="], + + "@typescript-eslint/type-utils": ["@typescript-eslint/type-utils@8.72.2", "", { "dependencies": { "@typescript-eslint/types": "8.72.2", "@typescript-eslint/typescript-estree": "8.72.2", "@typescript-eslint/utils": "8.72.2", "debug": "^4.4.3", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag=="], + + "@typescript-eslint/types": ["@typescript-eslint/types@8.72.2", "", {}, "sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog=="], + + "@typescript-eslint/typescript-estree": ["@typescript-eslint/typescript-estree@8.72.2", "", { "dependencies": { "@typescript-eslint/project-service": "8.72.2", "@typescript-eslint/tsconfig-utils": "8.72.2", "@typescript-eslint/types": "8.72.2", "@typescript-eslint/visitor-keys": "8.72.2", "debug": "^4.4.3", "minimatch": "^10.2.2", "semver": "^7.7.3", "tinyglobby": "^0.2.15", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "typescript": ">=4.8.4 <6.1.0" } }, "sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow=="], + + "@typescript-eslint/utils": ["@typescript-eslint/utils@8.72.2", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.9.1", "@typescript-eslint/scope-manager": "8.72.2", "@typescript-eslint/types": "8.72.2", "@typescript-eslint/typescript-estree": "8.72.2" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA=="], + + "@typescript-eslint/visitor-keys": ["@typescript-eslint/visitor-keys@8.72.2", "", { "dependencies": { "@typescript-eslint/types": "8.72.2", "eslint-visitor-keys": "^5.0.0" } }, "sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ=="], + + "@vitest/expect": ["@vitest/expect@3.2.7", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.7", "@vitest/utils": "3.2.7", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w=="], + + "@vitest/mocker": ["@vitest/mocker@3.2.7", "", { "dependencies": { "@vitest/spy": "3.2.7", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA=="], + + "@vitest/pretty-format": ["@vitest/pretty-format@3.2.7", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA=="], + + "@vitest/runner": ["@vitest/runner@3.2.7", "", { "dependencies": { "@vitest/utils": "3.2.7", "pathe": "^2.0.3", "strip-literal": "^3.0.0" } }, "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA=="], + + "@vitest/snapshot": ["@vitest/snapshot@3.2.7", "", { "dependencies": { "@vitest/pretty-format": "3.2.7", "magic-string": "^0.30.17", "pathe": "^2.0.3" } }, "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g=="], + + "@vitest/spy": ["@vitest/spy@3.2.7", "", { "dependencies": { "tinyspy": "^4.0.3" } }, "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ=="], + + "@vitest/utils": ["@vitest/utils@3.2.7", "", { "dependencies": { "@vitest/pretty-format": "3.2.7", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw=="], + + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + + "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + + "ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="], + + "ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "argparse": ["argparse@3.0.4", "", {}, "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA=="], + + "aria-query": ["aria-query@5.3.1", "", {}, "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g=="], + + "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], + + "axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="], + + "balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="], + + "bits-ui": ["bits-ui@2.21.0", "", { "dependencies": { "@floating-ui/core": "^1.8.0", "@floating-ui/dom": "^1.8.0", "esm-env": "^1.2.2", "runed": "^0.35.1", "svelte-toolbelt": "^0.10.7", "tabbable": "^6.5.1" }, "peerDependencies": { "@internationalized/date": "^3.8.1", "svelte": "^5.33.0" } }, "sha512-kfJonux4r+XOnqGCBQaqFfhRUvDbuZQgyjXADfk0/QJGc8LlQchkrGc6rCd+ldo1EixCJEXlM7znKVIUtuf7OQ=="], + + "brace-expansion": ["brace-expansion@1.1.22", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ=="], + + "cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="], + + "callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="], + + "chai": ["chai@5.3.3", "", { "dependencies": { "assertion-error": "^2.0.1", "check-error": "^2.1.1", "deep-eql": "^5.0.1", "loupe": "^3.1.0", "pathval": "^2.0.0" } }, "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw=="], + + "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + + "check-error": ["check-error@2.1.3", "", {}, "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA=="], + + "chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="], + + "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], + + "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + + "concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="], + + "cookie": ["cookie@0.6.0", "", {}, "sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw=="], + + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + + "cssstyle": ["cssstyle@4.6.0", "", { "dependencies": { "@asamuzakjp/css-color": "^3.2.0", "rrweb-cssom": "^0.8.0" } }, "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg=="], + + "data-urls": ["data-urls@5.0.0", "", { "dependencies": { "whatwg-mimetype": "^4.0.0", "whatwg-url": "^14.0.0" } }, "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "decimal.js": ["decimal.js@10.6.0", "", {}, "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg=="], + + "deep-eql": ["deep-eql@5.0.2", "", {}, "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q=="], + + "deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="], + + "deepmerge": ["deepmerge@4.3.1", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="], + + "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], + + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + + "devalue": ["devalue@5.9.4", "", {}, "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg=="], + + "dom-accessibility-api": ["dom-accessibility-api@0.5.16", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="], + + "dompurify": ["dompurify@3.4.18", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg=="], + + "enhanced-resolve": ["enhanced-resolve@5.27.0", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ=="], + + "entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], + + "es-module-lexer": ["es-module-lexer@1.7.0", "", {}, "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA=="], + + "esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="], + + "escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="], + + "eslint": ["eslint@9.39.5", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.21.2", "@eslint/config-helpers": "^0.4.2", "@eslint/core": "^0.17.0", "@eslint/eslintrc": "^3.3.6", "@eslint/js": "9.39.5", "@eslint/plugin-kit": "^0.4.1", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", "ajv": "^6.14.0", "chalk": "^4.0.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^8.4.0", "eslint-visitor-keys": "^4.2.1", "espree": "^10.4.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw=="], + + "eslint-plugin-svelte": ["eslint-plugin-svelte@3.24.1", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.6.1", "@jridgewell/sourcemap-codec": "^1.5.0", "esutils": "^2.0.3", "globals": "^16.0.0", "known-css-properties": "^0.37.0", "postcss": "^8.5.10", "postcss-load-config": "^3.1.4", "postcss-safe-parser": "^7.0.0", "semver": "^7.6.3", "svelte-eslint-parser": "^1.10.1" }, "peerDependencies": { "eslint": "^8.57.1 || ^9.0.0 || ^10.0.0", "svelte": "^3.37.0 || ^4.0.0 || ^5.0.0" }, "optionalPeers": ["svelte"] }, "sha512-XYzp318u8UkDH4ZdRkdSomOYnwMTeJP2Zw9u6DuBj3mViFZD8zS+mhfTYq34plm3SH9eF7ZaiYJfQYq2xMhPHg=="], + + "eslint-scope": ["eslint-scope@8.4.0", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg=="], + + "eslint-visitor-keys": ["eslint-visitor-keys@4.2.1", "", {}, "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ=="], + + "esm-env": ["esm-env@1.2.2", "", {}, "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA=="], + + "espree": ["espree@10.4.0", "", { "dependencies": { "acorn": "^8.15.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^4.2.1" } }, "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ=="], + + "esquery": ["esquery@1.7.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="], + + "esrap": ["esrap@2.4.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" }, "peerDependencies": { "@typescript-eslint/types": "^8.2.0" }, "optionalPeers": ["@typescript-eslint/types"] }, "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA=="], + + "esrecurse": ["esrecurse@4.3.0", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="], + + "estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="], + + "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], + + "esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="], + + "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], + + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="], + + "fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "file-entry-cache": ["file-entry-cache@8.0.0", "", { "dependencies": { "flat-cache": "^4.0.0" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="], + + "find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="], + + "flat-cache": ["flat-cache@4.0.1", "", { "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.4" } }, "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw=="], + + "flatted": ["flatted@3.4.4", "", {}, "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin", "hasInstallScript": true }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "glob-parent": ["glob-parent@6.0.2", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="], + + "globals": ["globals@17.14.0", "", {}, "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg=="], + + "graceful-fs": ["graceful-fs@4.2.12", "", {}, "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw=="], + + "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], + + "highlight.js": ["highlight.js@11.12.0", "", {}, "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg=="], + + "html-encoding-sniffer": ["html-encoding-sniffer@4.0.0", "", { "dependencies": { "whatwg-encoding": "^3.1.1" } }, "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ=="], + + "http-proxy-agent": ["http-proxy-agent@7.0.2", "", { "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" } }, "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig=="], + + "https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="], + + "iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], + + "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], + + "import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="], + + "imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="], + + "inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="], + + "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], + + "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], + + "is-potential-custom-element-name": ["is-potential-custom-element-name@1.0.1", "", {}, "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ=="], + + "is-reference": ["is-reference@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.6" } }, "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw=="], + + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], + + "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], + + "js-yaml": ["js-yaml@5.5.0", "", { "dependencies": { "argparse": "^3.0.3" }, "bin": { "js-yaml": "bin/js-yaml.mjs" } }, "sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg=="], + + "jsdom": ["jsdom@26.1.0", "", { "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", "decimal.js": "^10.5.0", "html-encoding-sniffer": "^4.0.0", "http-proxy-agent": "^7.0.2", "https-proxy-agent": "^7.0.6", "is-potential-custom-element-name": "^1.0.1", "nwsapi": "^2.2.16", "parse5": "^7.2.1", "rrweb-cssom": "^0.8.0", "saxes": "^6.0.0", "symbol-tree": "^3.2.4", "tough-cookie": "^5.1.1", "w3c-xmlserializer": "^5.0.0", "webidl-conversions": "^7.0.0", "whatwg-encoding": "^3.1.1", "whatwg-mimetype": "^4.0.0", "whatwg-url": "^14.1.1", "ws": "^8.18.0", "xml-name-validator": "^5.0.0" }, "peerDependencies": { "canvas": "^3.0.0" }, "optionalPeers": ["canvas"] }, "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg=="], + + "json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="], + + "json-schema-to-typescript": ["json-schema-to-typescript@16.0.0", "", { "dependencies": { "@apidevtools/json-schema-ref-parser": "^11.9.3", "@types/json-schema": "^7.0.15", "@types/lodash": "^4.17.25", "js-yaml": "^5.2.3", "lodash": "^4.18.1", "minimist": "^1.2.8", "prettier": "^3.9.6", "tinyglobby": "^0.2.17" }, "bin": { "json2ts": "dist/src/cli.js" } }, "sha512-Ah6kK4q6SjlMzWBH1eNOQkdRh5Qhr5T/RCFwfjQqWZA7UDW+N47A8wfyoiN0L884s4L4bAEI54IjIuN3/u0B/A=="], + + "json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="], + + "json-stable-stringify-without-jsonify": ["json-stable-stringify-without-jsonify@1.0.1", "", {}, "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw=="], + + "keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="], + + "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], + + "known-css-properties": ["known-css-properties@0.37.0", "", {}, "sha512-JCDrsP4Z1Sb9JwG0aJ8Eo2r7k4Ou5MwmThS/6lcIe1ICyb7UBJKGRIUUdqc2ASdE/42lgz6zFUnzAIhtXnBVrQ=="], + + "levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="], + + "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], + + "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], + + "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="], + + "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="], + + "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="], + + "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="], + + "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="], + + "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="], + + "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="], + + "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="], + + "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="], + + "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], + + "lilconfig": ["lilconfig@2.1.0", "", {}, "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ=="], + + "locate-character": ["locate-character@3.0.0", "", {}, "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA=="], + + "locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="], + + "lodash": ["lodash@4.18.1", "", {}, "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="], + + "lodash.merge": ["lodash.merge@4.6.2", "", {}, "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="], + + "loupe": ["loupe@3.2.1", "", {}, "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ=="], + + "lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="], + + "lz-string": ["lz-string@1.5.0", "", { "bin": { "lz-string": "bin/bin.js" } }, "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ=="], + + "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + + "marked": ["marked@18.2.0", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-KaeL+tAbtvI930q7HE2PN5lYXYdT8EiSmxHlN6F3rsfb57wd5mp5W5TLazpdj4inTQBJdgjYwbs40W/0VUGU+Q=="], + + "minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="], + + "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], + + "mri": ["mri@1.2.0", "", {}, "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA=="], + + "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], + + "natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="], + + "nwsapi": ["nwsapi@2.2.28", "", {}, "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg=="], + + "obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="], + + "optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="], + + "p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="], + + "p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="], + + "parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="], + + "parse5": ["parse5@7.3.0", "", { "dependencies": { "entities": "^6.0.0" } }, "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw=="], + + "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + + "pathval": ["pathval@2.0.1", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "postcss": ["postcss@8.5.33", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ=="], + + "postcss-load-config": ["postcss-load-config@3.1.4", "", { "dependencies": { "lilconfig": "^2.0.5", "yaml": "^1.10.2" }, "peerDependencies": { "postcss": ">=8.0.9", "ts-node": ">=9.0.0" }, "optionalPeers": ["postcss", "ts-node"] }, "sha512-6DiM4E7v4coTE4uzA8U//WhtPwyhiim3eyjEMFCnUpzbrkK9wJHgKDT2mR+HbtSrd/NubVaYTOpSpjUl8NQeRg=="], + + "postcss-safe-parser": ["postcss-safe-parser@7.1.0", "", { "peerDependencies": { "postcss": "^8.4.31" } }, "sha512-1WzZxRLaAFwEh6Do+zyGpjWV3nGJNxxhuh7Ubu/q1ICImMgZJnLwhoaEpRbG4pJppp2Y1ncL9ffA2f+LhrefQg=="], + + "postcss-scss": ["postcss-scss@4.0.9", "", { "peerDependencies": { "postcss": "^8.4.29" } }, "sha512-AjKOeiwAitL/MXxQW2DliT28EKukvvbEWx3LBmJIRN8KfBGZbRTxNYW0kSqi1COiTZ57nZ9NW06S6ux//N1c9A=="], + + "postcss-selector-parser": ["postcss-selector-parser@7.2.1", "", { "dependencies": { "util-deprecate": "^1.0.2" } }, "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ=="], + + "prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="], + + "prettier": ["prettier@3.10.1", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-70vp3ZUYoPlFbF9uiTdXHUUCGEIp7d4+6p+8DYbkm2jP7x/3i/paXVF6dopSI3zd/CEitrZN1rc4i85xWmmXlg=="], + + "prettier-plugin-svelte": ["prettier-plugin-svelte@4.1.1", "", { "peerDependencies": { "prettier": "^3.0.0", "svelte": "^5.0.0" } }, "sha512-wXvbXMjSvb4C9ENWTHXyd+ihakKCsJ6rJhLP6/8HFNj4GkZr48jqL9PoKsl2sk7SyCZRTnJ7O2TTowUpOxP/KA=="], + + "pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="], + + "punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="], + + "react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="], + + "readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="], + + "resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="], + + "rollup": ["rollup@4.68.3", "", { "dependencies": { "@types/estree": "^1.0.10" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.68.3", "@rollup/rollup-android-arm64": "4.68.3", "@rollup/rollup-android-x64": "4.68.3", "@rollup/rollup-darwin-arm64": "4.68.3", "@rollup/rollup-darwin-x64": "4.68.3", "@rollup/rollup-freebsd-arm64": "4.68.3", "@rollup/rollup-freebsd-x64": "4.68.3", "@rollup/rollup-linux-arm-gnueabihf": "4.68.3", "@rollup/rollup-linux-arm-musleabihf": "4.68.3", "@rollup/rollup-linux-arm64-gnu": "4.68.3", "@rollup/rollup-linux-arm64-musl": "4.68.3", "@rollup/rollup-linux-loong64-gnu": "4.68.3", "@rollup/rollup-linux-loong64-musl": "4.68.3", "@rollup/rollup-linux-ppc64-gnu": "4.68.3", "@rollup/rollup-linux-ppc64-musl": "4.68.3", "@rollup/rollup-linux-riscv64-gnu": "4.68.3", "@rollup/rollup-linux-riscv64-musl": "4.68.3", "@rollup/rollup-linux-s390x-gnu": "4.68.3", "@rollup/rollup-linux-x64-gnu": "4.68.3", "@rollup/rollup-linux-x64-musl": "4.68.3", "@rollup/rollup-openbsd-x64": "4.68.3", "@rollup/rollup-openharmony-arm64": "4.68.3", "@rollup/rollup-win32-arm64-msvc": "4.68.3", "@rollup/rollup-win32-ia32-msvc": "4.68.3", "@rollup/rollup-win32-x64-gnu": "4.68.3", "@rollup/rollup-win32-x64-msvc": "4.68.3", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-wd2gavj7CEQv52rdcVqfUupO/KPIKcoJKxyFWl4cOqYZGMQEOSijJRkliz0dRa7gpkj/h4TRqyWa+dJJi6T0OA=="], + + "rrweb-cssom": ["rrweb-cssom@0.8.0", "", {}, "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw=="], + + "runed": ["runed@0.35.1", "", { "dependencies": { "dequal": "^2.0.3", "esm-env": "^1.0.0", "lz-string": "^1.5.0" }, "peerDependencies": { "@sveltejs/kit": "^2.21.0", "svelte": "^5.7.0" }, "optionalPeers": ["@sveltejs/kit"] }, "sha512-2F4Q/FZzbeJTFdIS/PuOoPRSm92sA2LhzTnv6FXhCoENb3huf5+fDuNOg1LNvGOouy3u/225qxmuJvcV3IZK5Q=="], + + "sade": ["sade@1.8.1", "", { "dependencies": { "mri": "^1.1.0" } }, "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A=="], + + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + + "saxes": ["saxes@6.0.0", "", { "dependencies": { "xmlchars": "^2.2.0" } }, "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA=="], + + "semver": ["semver@7.8.6", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], + + "set-cookie-parser": ["set-cookie-parser@3.2.2", "", {}, "sha512-df017qMeYuXo4emL09nlyMpi2i2MtEIKS/6jtXH3vmjFgIRsOi852/5RmhJ4EkvN3ZF8jXadM/EkTPXgc8yPIw=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], + + "sirv": ["sirv@3.0.2", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g=="], + + "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], + + "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], + + "std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="], + + "strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="], + + "strip-literal": ["strip-literal@3.1.0", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="], + + "style-to-object": ["style-to-object@1.0.14", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="], + + "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + + "svelte": ["svelte@5.57.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "@jridgewell/sourcemap-codec": "^1.6.0", "@sveltejs/acorn-typescript": "^1.0.13", "@types/estree": "^1.0.9", "acorn": "^8.18.0", "aria-query": "5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "devalue": "^5.9.2", "esm-env": "^1.2.1", "esrap": "^2.3.6", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg=="], + + "svelte-check": ["svelte-check@4.7.8", "", { "dependencies": { "@jridgewell/trace-mapping": "^0.3.25", "@sveltejs/load-config": "^0.2.3", "chokidar": "^4.0.1", "fdir": "^6.2.0", "picocolors": "^1.0.0", "sade": "^1.7.4" }, "peerDependencies": { "svelte": "^4.0.0 || ^5.0.0-next.0", "typescript": "^5.0.0 || ^6.0.0" }, "bin": { "svelte-check": "bin/svelte-check" } }, "sha512-laZ49GFHZ3b0z2PWinJWL0syehc/PTR8aHaUaTiBkWJ+4Y38nhxjmXsSz7CbGa3VdKopViVbrBH3bGNqIAI0bQ=="], + + "svelte-eslint-parser": ["svelte-eslint-parser@1.10.1", "", { "dependencies": { "eslint-scope": "^8.2.0", "eslint-visitor-keys": "^4.0.0", "espree": "^10.0.0", "postcss": "^8.4.49", "postcss-scss": "^4.0.9", "postcss-selector-parser": "^7.0.0", "semver": "^7.7.2" }, "peerDependencies": { "svelte": "^3.37.0 || ^4.0.0 || ^5.0.0" }, "optionalPeers": ["svelte"] }, "sha512-owYBhrNRp/m+hDaQCH0S683kc0TMFy2bB+qvsMQQZRsjSFD9xp/3FYgI8FZoOKA3xk62gwkUj1HpVek0p6WgNw=="], + + "svelte-toolbelt": ["svelte-toolbelt@0.10.7", "", { "dependencies": { "clsx": "^2.1.1", "runed": "^0.35.1", "style-to-object": "^1.0.8" }, "peerDependencies": { "svelte": "^5.30.2" } }, "sha512-gjuUVEEpo38UJCeI1ssE3NxG31tYENczPTcTGTXf4338qAQNdR9I1oAEbQY0KQFmbdUojNIhHuRNix7ThwFNxQ=="], + + "symbol-tree": ["symbol-tree@3.2.4", "", {}, "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw=="], + + "tabbable": ["tabbable@6.5.2", "", {}, "sha512-XgdnB1nGU6KU4VgMnZPaZCx7M1hBrLyEiZYau2G2gq9UT0d7d4FUBlNX7vvPlm/B1vk1PjrzJBx9Lbv4fsqS9g=="], + + "tailwind-merge": ["tailwind-merge@3.7.0", "", {}, "sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA=="], + + "tailwind-variants": ["tailwind-variants@3.3.1", "", { "peerDependencies": { "tailwind-merge": ">=3.0.0", "tailwindcss": "*" }, "optionalPeers": ["tailwind-merge", "tailwindcss"] }, "sha512-4pAvwUtM4HKBiRZftncAbpn6V9Hhwoa5Fl7O2u5zbp7Z5Cvu+/o/6+176WY3WCEES209543quG8zFIcXCsc5Jw=="], + + "tailwindcss": ["tailwindcss@4.3.5", "", {}, "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ=="], + + "tapable": ["tapable@2.3.4", "", {}, "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg=="], + + "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], + + "tinyexec": ["tinyexec@0.3.2", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "tinypool": ["tinypool@1.1.1", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="], + + "tinyrainbow": ["tinyrainbow@2.0.0", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="], + + "tinyspy": ["tinyspy@4.0.6", "", {}, "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg=="], + + "tldts": ["tldts@6.1.86", "", { "dependencies": { "tldts-core": "^6.1.86" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ=="], + + "tldts-core": ["tldts-core@6.1.86", "", {}, "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA=="], + + "totalist": ["totalist@3.0.1", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="], + + "tough-cookie": ["tough-cookie@5.1.2", "", { "dependencies": { "tldts": "^6.1.32" } }, "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A=="], + + "tr46": ["tr46@5.1.1", "", { "dependencies": { "punycode": "^2.3.1" } }, "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw=="], + + "ts-api-utils": ["ts-api-utils@2.5.0", "", { "peerDependencies": { "typescript": ">=4.8.4" } }, "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA=="], + + "type-check": ["type-check@0.4.0", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "typescript-eslint": ["typescript-eslint@8.72.2", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.72.2", "@typescript-eslint/parser": "8.72.2", "@typescript-eslint/typescript-estree": "8.72.2", "@typescript-eslint/utils": "8.72.2" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg=="], + + "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + + "uqr": ["uqr@0.1.3", "", {}, "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA=="], + + "uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="], + + "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], + + "vite": ["vite@7.3.8", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw=="], + + "vite-node": ["vite-node@3.2.4", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.4.1", "es-module-lexer": "^1.7.0", "pathe": "^2.0.3", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg=="], + + "vitefu": ["vitefu@1.1.3", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg=="], + + "vitest": ["vitest@3.2.7", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/expect": "3.2.7", "@vitest/mocker": "3.2.7", "@vitest/pretty-format": "^3.2.7", "@vitest/runner": "3.2.7", "@vitest/snapshot": "3.2.7", "@vitest/spy": "3.2.7", "@vitest/utils": "3.2.7", "chai": "^5.2.0", "debug": "^4.4.1", "expect-type": "^1.2.1", "magic-string": "^0.30.17", "pathe": "^2.0.3", "picomatch": "^4.0.2", "std-env": "^3.9.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.14", "tinypool": "^1.1.1", "tinyrainbow": "^2.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", "vite-node": "3.2.4", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/debug": "^4.1.12", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "@vitest/browser": "3.2.7", "@vitest/ui": "3.2.7", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/debug", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg=="], + + "w3c-xmlserializer": ["w3c-xmlserializer@5.0.0", "", { "dependencies": { "xml-name-validator": "^5.0.0" } }, "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA=="], + + "webidl-conversions": ["webidl-conversions@7.0.0", "", {}, "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g=="], + + "whatwg-encoding": ["whatwg-encoding@3.1.1", "", { "dependencies": { "iconv-lite": "0.6.3" } }, "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ=="], + + "whatwg-mimetype": ["whatwg-mimetype@4.0.0", "", {}, "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg=="], + + "whatwg-url": ["whatwg-url@14.2.0", "", { "dependencies": { "tr46": "^5.1.0", "webidl-conversions": "^7.0.0" } }, "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw=="], + + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], + + "word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="], + + "ws": ["ws@8.23.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ=="], + + "xml-name-validator": ["xml-name-validator@5.0.0", "", {}, "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg=="], + + "xmlchars": ["xmlchars@2.2.0", "", {}, "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="], + + "yaml": ["yaml@1.10.3", "", {}, "sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA=="], + + "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], + + "zimmerframe": ["zimmerframe@1.1.5", "", {}, "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA=="], + + "@apidevtools/json-schema-ref-parser/js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="], + + "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], + + "@eslint/eslintrc/globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="], + + "@eslint/eslintrc/js-yaml": ["js-yaml@4.3.2", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA=="], + + "@tailwindcss/node/magic-string": ["magic-string@1.4.5", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], + + "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.7", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" }, "bundled": true }, "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ=="], + + "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/wasm-util@0.10.4", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A=="], + + "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.9.1", "", { "bundled": true }, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + + "@testing-library/dom/aria-query": ["aria-query@5.3.0", "", { "dependencies": { "dequal": "^2.0.3" } }, "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A=="], + + "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.14", "", {}, "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ=="], + + "@typescript-eslint/typescript-estree/minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="], + + "@typescript-eslint/visitor-keys/eslint-visitor-keys": ["eslint-visitor-keys@5.0.1", "", {}, "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA=="], + + "eslint-plugin-svelte/globals": ["globals@16.5.0", "", {}, "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ=="], + + "pretty-format/ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="], + + "strip-literal/js-tokens": ["js-tokens@9.0.1", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="], + + "@apidevtools/json-schema-ref-parser/js-yaml/argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], + + "@eslint/eslintrc/js-yaml/argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], + + "@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@5.0.13", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ=="], + + "@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + } +} diff --git a/web/components.json b/web/components.json new file mode 100644 index 00000000..3148c498 --- /dev/null +++ b/web/components.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://shadcn-svelte.com/schema.json", + "tailwind": { "css": "src/app.css", "baseColor": "neutral" }, + "aliases": { + "components": "$lib/components", + "utils": "$lib/utils", + "ui": "$lib/components/ui", + "hooks": "$lib/hooks", + "lib": "$lib" + }, + "typescript": true, + "registry": "https://shadcn-svelte.com/registry" +} diff --git a/web/eslint.config.js b/web/eslint.config.js new file mode 100644 index 00000000..5da3df7d --- /dev/null +++ b/web/eslint.config.js @@ -0,0 +1,35 @@ +import js from '@eslint/js'; +import svelte from 'eslint-plugin-svelte'; +import globals from 'globals'; +import ts from 'typescript-eslint'; +import svelteConfig from './svelte.config.js'; + +export default ts.config( + { ignores: ['build/', '.svelte-kit/', 'node_modules/', 'src/lib/protocol/rpc.ts', 'fixtures/'] }, + js.configs.recommended, + ...ts.configs.recommended, + ...svelte.configs.recommended, + { + languageOptions: { globals: { ...globals.browser, ...globals.node } }, + rules: { + 'no-undef': 'off', + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_', varsIgnorePattern: '^_' } + ], + // The app is a static SPA mounted at the server's root; links never need a base path. + 'svelte/no-navigation-without-resolve': 'off' + } + }, + { + files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'], + languageOptions: { + parserOptions: { + projectService: true, + extraFileExtensions: ['.svelte'], + parser: ts.parser, + svelteConfig + } + } + } +); diff --git a/web/fixtures/commands.json b/web/fixtures/commands.json new file mode 100644 index 00000000..fae47c85 --- /dev/null +++ b/web/fixtures/commands.json @@ -0,0 +1,250 @@ +[ + { + "name": "cost", + "description": "Tokens and money spent in this session" + }, + { + "name": "context", + "description": "What the last request was made of: tokens by category, and the text of each" + }, + { + "name": "session", + "description": "What this session is: file, messages, tokens, cost, agents" + }, + { + "name": "tools", + "description": "List the tools offered to the agent, by where they come from" + }, + { + "name": "todo", + "description": "The agent's task list: /todo, /todo add , /todo done , /todo clear" + }, + { + "name": "dirs", + "description": "List the directories agents may work in" + }, + { + "name": "add-dir", + "description": "Let agents work in another directory too: /add-dir " + }, + { + "name": "rules", + "description": "List the rule files and whether each has applied in this session" + }, + { + "name": "hooks", + "description": "List the hooks, where they come from and how each last ran" + }, + { + "name": "doctor", + "description": "Check the installation and this project's setup" + }, + { + "name": "trust", + "description": "Whether this project is trusted, and what that covers: /trust [yes|no]" + }, + { + "name": "forget-approvals", + "description": "Forget every remembered approval and every rule added in this session" + }, + { + "name": "account", + "description": "The accounts of a provider: usage, switch, make default, sign out, add [provider]" + }, + { + "name": "advise", + "description": "Ask the advisor, a second model, about the work so far; only you see the answer [question]" + }, + { + "name": "agents", + "description": "The agents of this session and the definitions they can be started from" + }, + { + "name": "allow-edit", + "description": "Let the next edit of a file through, whatever the agent has read of it " + }, + { + "name": "bg", + "description": "Run a prompt in the background, in a copy of this session " + }, + { + "name": "coordinator", + "description": "Have the lead only plan and delegate: it keeps no tool that edits or runs commands on | off | status" + }, + { + "name": "ext", + "description": "List the loaded extensions and Luau scripts, with the errors of disabled scripts" + }, + { + "name": "fast", + "description": "Faster replies at a higher price (the priority tier) [on|off|status]" + }, + { + "name": "goal", + "description": "Set an objective the agent works on until it is verified | status | pause | resume | drop" + }, + { + "name": "login", + "description": "Sign in to a provider or store its API key [provider] [account] [--device] [--enterprise ]" + }, + { + "name": "logout", + "description": "Forget the stored key or login of a provider [account]" + }, + { + "name": "lsp", + "description": "Language servers and their state" + }, + { + "name": "mcp", + "description": "MCP servers: state, reconnect, enable or disable, approve, log in [reconnect|enable|disable|approve|reject|login|logout ]" + }, + { + "name": "media", + "description": "Media backends, configured models and the output directory" + }, + { + "name": "msg", + "description": "Send a message to an agent " + }, + { + "name": "playtest", + "description": "Have a playtester run a build, play it and report defects with frames [-- ]" + }, + { + "name": "preset", + "description": "List the saved sets of models, apply one, or save the current one [name | save ]" + }, + { + "name": "reload", + "description": "Drop all Luau extension state and load the scripts again" + }, + { + "name": "repomap", + "description": "The repository map: the project's most referenced definitions [refresh]" + }, + { + "name": "reset-usage", + "description": "Spend a banked reset of a Claude or ChatGPT subscription, after showing what it gives back [provider]" + }, + { + "name": "review", + "description": "Have a reviewer read the uncommitted changes, or the commits since a ref [ref]" + }, + { + "name": "security-review", + "description": "Have a reviewer look for security defects in the same changes [ref]" + }, + { + "name": "settings", + "description": "Sign in, add API keys, choose models and change every setting" + }, + { + "name": "skills", + "description": "List skills and where they come from" + }, + { + "name": "slow", + "description": "Cheaper, slower replies (the economy tier) [on|off|status]" + }, + { + "name": "stats", + "description": "Tokens and cost per day, provider, model, project and agent, from the usage log [days]" + }, + { + "name": "stop", + "description": "Stop an agent and the agents it started " + }, + { + "name": "task", + "description": "Start an agent yourself; its report goes to the lead [name=] " + }, + { + "name": "usage", + "description": "What your Claude and ChatGPT subscriptions have left, and when each window resets" + }, + { + "name": "verify", + "description": "Run the project's checks and a verifier agent on the work so far [what should be true]" + }, + { + "name": "skill:api-design", + "description": "Use when designing or reviewing an interface other programs call: an HTTP or RPC API, a library's public surface, or a wire format. Covers resource and RPC conventions, errors, pagination, idempotency and versioning." + }, + { + "name": "skill:azazel-extensions", + "description": "Use when customising this harness: writing a Luau extension (tools, event handlers, commands), configuring hooks, defining a custom agent, adding a slash command, or writing a skill. Contains the file locations, formats and API tables for each." + }, + { + "name": "skill:browser-testing", + "description": "Use to check a web page or web app in a real browser with the browser tool: confirming a change works, walking a user flow, finding why a page is broken, or capturing evidence. Snapshot, act, assert, with console and network checks." + }, + { + "name": "skill:code-review", + "description": "Use to review a change (a diff, a branch, a pull request, or work another agent just finished) before it is accepted. Gives a rubric, severity levels and a findings format that separates defects from preferences." + }, + { + "name": "skill:debugging", + "description": "Use when something fails, crashes, hangs or gives a wrong result and the cause is not yet known. A disciplined loop of reproduce, isolate, hypothesise, instrument, fix and prove, including bisection across history and inputs." + }, + { + "name": "skill:design-tokens", + "description": "Use when starting a project's visual system or replacing scattered values with one: derives colour, type, spacing, radius and shadow tokens from a brief or an existing brand colour and emits them as CSS variables and a Tailwind theme." + }, + { + "name": "skill:docs-writing", + "description": "Use when writing or restructuring documentation: a README, a getting-started tutorial, a how-to guide, reference pages or a changelog. Gives the structure for each kind and the checks that keep documentation true." + }, + { + "name": "skill:frontend-design", + "description": "Use when building or restyling a user interface (a page, a component, a whole app) and the result has to look designed rather than generated. Covers hierarchy, type, spacing, colour, states, responsive behaviour and motion, and how to check the work in a real browser." + }, + { + "name": "skill:game-dev", + "description": "Use when working on a game project in Godot, Unity, Unreal Engine, Roblox or Bevy: finding your way around the project, following the engine's conventions, producing and importing assets with the generate tools and sprite_sheet, and building, running and playtesting from the command line." + }, + { + "name": "skill:git-workflow", + "description": "Use when the task involves git beyond a simple status or diff: shaping commits, working on branches, resolving merge or rebase conflicts, finding the commit that introduced a bug, recovering lost work, or using worktrees. Sub-agents never push; the lead pushes only when the user asks." + }, + { + "name": "skill:mcp-builder", + "description": "Use when writing, extending or debugging a Model Context Protocol server so that agents can use a service, a data source or a local program as tools. Covers tool design, the stdio and HTTP transports, and testing the server against this harness." + }, + { + "name": "skill:media-generation", + "description": "Use when producing images, video, 3D models or audio with the generate tools, or sprite sheets from generated frames. Prompt patterns for each kind, how to keep a set of assets in one style, and how to check results before using them." + }, + { + "name": "skill:performance", + "description": "Use when something is too slow or uses too much memory, or before optimising anything. Measure first, find the bottleneck with the right profiler for the ecosystem, change one thing, and prove the gain with a benchmark." + }, + { + "name": "skill:playtest", + "description": "Use to run a game or application build and try it the way a player or user would: launching it, operating it through screen capture and input (or the browser for web builds), and reporting defects with the frames that show them." + }, + { + "name": "skill:refactoring", + "description": "Use when restructuring code without changing what it does: extracting, renaming, moving, splitting modules, replacing a pattern across a codebase, or cleaning up before a feature. Characterisation tests first, then small mechanical steps that each keep the build green." + }, + { + "name": "skill:release-engineering", + "description": "Use when preparing a release or the machinery around one: choosing a version number, writing a changelog, setting up CI build and test matrices, cross-compiling, and packaging binaries for Windows, macOS and Linux. Publishing itself stays with the user." + }, + { + "name": "skill:reverse-engineering", + "description": "Use when the task is to understand software or data without its source: triaging an unknown binary, recovering behaviour and data structures in a disassembler, working out a file format or a network protocol, or finding what changed between two builds. For software you own or are authorised to analyse." + }, + { + "name": "skill:security-review", + "description": "Use to look for security defects in code you are allowed to assess: a change before merge, a feature that handles untrusted input, or a whole service. Covers injection, authorisation, secrets, deserialisation, request forgery to internal services, and dependency risk, with a findings format that requires evidence." + }, + { + "name": "skill:testing", + "description": "Use when writing or extending tests, deciding what level a test belongs at, or dealing with flaky or slow tests. Covers choosing behaviours and boundaries, fixtures and test data, doubles, and making tests deterministic." + }, + { + "name": "skill:ui-review", + "description": "Use to audit an existing interface for accessibility and usability problems: contrast, keyboard and focus order, semantics and names, forms and error states, responsive behaviour. Produces a findings report with severity, evidence and a fix for each item." + } +] \ No newline at end of file diff --git a/web/fixtures/forms.jsonl b/web/fixtures/forms.jsonl new file mode 100644 index 00000000..9f3e52ff --- /dev/null +++ b/web/fixtures/forms.jsonl @@ -0,0 +1,42 @@ +{"type": "agent_start", "agent": "lead"} +{"type": "turn_start", "turn": 1, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c1", "name": "ask_user"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"questions\":[{\"question\":\"Which store should the service use?\",\"header\":\"Store\",\"context\":\"The service keeps sessions between restarts.\",\"code\":\"CREATE TABLE sessions (id TEXT PRIMARY KEY, data BLOB);\",\"options\":[\"sqlite\",\"postgres\"],\"recommended\":\"postgres\"},{\"question\":\"Anything else I should know?\",\"header\":\"Notes\"},{\"question\":\"Apply this change?\",\"header\":\"Patch\",\"type\":\"confirm\",\"diff\":\"--- a/src/store.rs\\n+++ b/src/store.rs\\n@@ -1,2 +1,2 @@\\n fn open() {\\n- memory();\\n+ disk();\\n\"}]}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c1", "name": "ask_user", "input": {"questions": [{"question": "Which store should the service use?", "header": "Store", "context": "The service keeps sessions between restarts.", "code": "CREATE TABLE sessions (id TEXT PRIMARY KEY, data BLOB);", "options": ["sqlite", "postgres"], "recommended": "postgres"}, {"question": "Anything else I should know?", "header": "Notes"}, {"question": "Apply this change?", "header": "Patch", "type": "confirm", "diff": "--- a/src/store.rs\n+++ b/src/store.rs\n@@ -1,2 +1,2 @@\n fn open() {\n- memory();\n+ disk();\n"}]}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c1", "name": "ask_user", "input": {"questions": [{"question": "Which store should the service use?", "header": "Store", "context": "The service keeps sessions between restarts.", "code": "CREATE TABLE sessions (id TEXT PRIMARY KEY, data BLOB);", "options": ["sqlite", "postgres"], "recommended": "postgres"}, {"question": "Anything else I should know?", "header": "Notes"}, {"question": "Apply this change?", "header": "Patch", "type": "confirm", "diff": "--- a/src/store.rs\n+++ b/src/store.rs\n@@ -1,2 +1,2 @@\n fn open() {\n- memory();\n+ disk();\n"}]}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c1", "name": "ask_user", "input": {"questions": [{"question": "Which store should the service use?", "header": "Store", "context": "The service keeps sessions between restarts.", "code": "CREATE TABLE sessions (id TEXT PRIMARY KEY, data BLOB);", "options": ["sqlite", "postgres"], "recommended": "postgres"}, {"question": "Anything else I should know?", "header": "Notes"}, {"question": "Apply this change?", "header": "Patch", "type": "confirm", "diff": "--- a/src/store.rs\n+++ b/src/store.rs\n@@ -1,2 +1,2 @@\n fn open() {\n- memory();\n+ disk();\n"}]}, "agent": "lead"} +{"type": "ui_request", "request_id": "r1", "kind": "form", "questions": [{"question": "Which store should the service use?", "header": "Store", "context": "The service keeps sessions between restarts.", "code": "CREATE TABLE sessions (id TEXT PRIMARY KEY, data BLOB);", "expects": "select", "options": ["sqlite", "postgres"], "multi": false, "recommended": "postgres"}, {"question": "Anything else I should know?", "header": "Notes", "expects": "text", "options": [], "multi": false}, {"question": "Apply this change?", "header": "Patch", "diff": "--- a/src/store.rs\n+++ b/src/store.rs\n@@ -1,2 +1,2 @@\n fn open() {\n- memory();\n+ disk();\n", "expects": "confirm", "options": [], "multi": false}]} +{"type": "tool_end", "call_id": "c1", "output": {"content": [{"type": "text", "text": "1. Which store should the service use?\nsqlite\n\n2. Anything else I should know?\nx\n\n3. Apply this change?\n(no answer)"}], "is_error": false, "details": {"questions": [{"question": "Which store should the service use?", "context": "The service keeps sessions between restarts.", "type": "select", "options": ["sqlite", "postgres"], "recommended": "postgres", "answers": ["sqlite"], "freeform": false, "cancelled": false, "reason": null}, {"question": "Anything else I should know?", "context": null, "type": "text", "options": [], "recommended": null, "answers": ["x"], "freeform": false, "cancelled": false, "reason": null}, {"question": "Apply this change?", "context": null, "type": "confirm", "options": [], "recommended": null, "answers": [], "freeform": false, "cancelled": false, "reason": null}], "cancelled": false, "reason": null}}, "duration_ms": 51, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 2, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c2", "name": "ask_user"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"question\":\"Ship it when the tests pass?\",\"type\":\"confirm\",\"recommended\":\"yes\",\"async\":true}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c2", "name": "ask_user", "input": {"question": "Ship it when the tests pass?", "type": "confirm", "recommended": "yes", "async": true}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c2", "name": "ask_user", "input": {"question": "Ship it when the tests pass?", "type": "confirm", "recommended": "yes", "async": true}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c2", "name": "ask_user", "input": {"question": "Ship it when the tests pass?", "type": "confirm", "recommended": "yes", "async": true}, "agent": "lead"} +{"type": "tool_end", "call_id": "c2", "output": {"content": [{"type": "text", "text": "The question is with the user. The answer will reach you as a message; go on with what does not depend on it."}], "is_error": false, "details": {"question": "Ship it when the tests pass?", "async": true}}, "duration_ms": 0, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 3, "agent": "lead"} +{"type": "ui_request", "request_id": "r2", "kind": "ask", "question": "Ship it when the tests pass?", "expects": "confirm", "options": [], "multi": false, "recommended": "yes"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "text_delta", "index": 0, "delta": "Working on the store meanwhile."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "text", "text": "Working on the store meanwhile."}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Working on the store meanwhile."}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "stop", "duration_ms": 0}}, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "idle", "stop": "stop", "agent": "lead"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "idle", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}]} +{"type": "ui_request", "request_id": "r3", "kind": "notify", "level": "info", "text": "your answer was sent to lead"} +{"type": "agent_start", "agent": "lead"} +{"type": "turn_start", "turn": 1, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "text_delta", "index": 0, "delta": "Shipping."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "text", "text": "Shipping."}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Shipping."}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "stop", "duration_ms": 0}}, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "idle", "stop": "stop", "agent": "lead"} diff --git a/web/fixtures/mention.jsonl b/web/fixtures/mention.jsonl new file mode 100644 index 00000000..6e6fd878 --- /dev/null +++ b/web/fixtures/mention.jsonl @@ -0,0 +1,9 @@ +{"type": "agent_start", "agent": "lead"} +{"type": "turn_start", "turn": 1, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "text_delta", "index": 0, "delta": "Noted."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "text", "text": "Noted."}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Noted."}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "stop", "duration_ms": 0}}, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "idle", "stop": "stop", "agent": "lead"} diff --git a/web/fixtures/models.json b/web/fixtures/models.json new file mode 100644 index 00000000..ec280898 --- /dev/null +++ b/web/fixtures/models.json @@ -0,0 +1,250 @@ +[ + { + "model": "bedrock/amazon.nova-lite-v1:0", + "provider": "bedrock", + "id": "amazon.nova-lite-v1:0", + "name": "Nova Lite", + "context_window": 300000, + "max_output": 10000, + "vision": true, + "reasoning": false, + "cost": { + "input": 0.06, + "output": 0.24 + }, + "usable": true, + "login": false + }, + { + "model": "bedrock/amazon.nova-pro-v1:0", + "provider": "bedrock", + "id": "amazon.nova-pro-v1:0", + "name": "Nova Pro", + "context_window": 300000, + "max_output": 10000, + "vision": true, + "reasoning": false, + "cost": { + "input": 0.8, + "output": 3.2 + }, + "usable": true, + "login": false + }, + { + "model": "bedrock/anthropic.claude-fable-5-2", + "provider": "bedrock", + "id": "anthropic.claude-fable-5-2", + "name": "Claude Fable 5.2", + "context_window": 1000000, + "max_output": 128000, + "vision": true, + "reasoning": true, + "thinking_levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ], + "cost": { + "input": 8.0, + "output": 40.0 + }, + "usable": true, + "login": false + }, + { + "model": "bedrock/anthropic.claude-haiku-5-5", + "provider": "bedrock", + "id": "anthropic.claude-haiku-5-5", + "name": "Claude Haiku 5.5", + "context_window": 1000000, + "max_output": 128000, + "vision": true, + "reasoning": true, + "thinking_levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ], + "cost": { + "input": 0.1, + "output": 0.5 + }, + "usable": true, + "login": false + }, + { + "model": "bedrock/anthropic.claude-opus-4-7", + "provider": "bedrock", + "id": "anthropic.claude-opus-4-7", + "name": "Claude Opus 4.7", + "context_window": 1000000, + "max_output": 128000, + "vision": true, + "reasoning": true, + "thinking_levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ], + "cost": { + "input": 5.0, + "output": 25.0 + }, + "usable": true, + "login": false + }, + { + "model": "bedrock/anthropic.claude-opus-4-8", + "provider": "bedrock", + "id": "anthropic.claude-opus-4-8", + "name": "Claude Opus 4.8", + "context_window": 1000000, + "max_output": 128000, + "vision": true, + "reasoning": true, + "thinking_levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ], + "cost": { + "input": 5.0, + "output": 25.0 + }, + "usable": true, + "login": false + }, + { + "model": "vertex/claude-fable-5-1@default", + "provider": "vertex", + "id": "claude-fable-5-1@default", + "name": "Claude Fable 5.1", + "context_window": 1000000, + "max_output": 128000, + "vision": true, + "reasoning": true, + "thinking_levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ], + "cost": { + "input": 10.0, + "output": 50.0 + }, + "usable": true, + "login": false + }, + { + "model": "vertex/claude-fable-5-2@default", + "provider": "vertex", + "id": "claude-fable-5-2@default", + "name": "Claude Fable 5.2", + "context_window": 1000000, + "max_output": 128000, + "vision": true, + "reasoning": true, + "thinking_levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ], + "cost": { + "input": 8.0, + "output": 40.0 + }, + "usable": true, + "login": false + }, + { + "model": "vertex/claude-fable-5@default", + "provider": "vertex", + "id": "claude-fable-5@default", + "name": "Claude Fable 5", + "context_window": 1000000, + "max_output": 128000, + "vision": true, + "reasoning": true, + "thinking_levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ], + "cost": { + "input": 10.0, + "output": 50.0 + }, + "usable": true, + "login": false + }, + { + "model": "vertex/claude-haiku-4-5@20251001", + "provider": "vertex", + "id": "claude-haiku-4-5@20251001", + "name": "Claude Haiku 4.5", + "context_window": 200000, + "max_output": 64000, + "vision": true, + "reasoning": true, + "cost": { + "input": 1.0, + "output": 5.0 + }, + "usable": true, + "login": false + }, + { + "model": "vertex/claude-haiku-5-5@default", + "provider": "vertex", + "id": "claude-haiku-5-5@default", + "name": "Claude Haiku 5.5", + "context_window": 1000000, + "max_output": 128000, + "vision": true, + "reasoning": true, + "thinking_levels": [ + "low", + "medium", + "high", + "xhigh", + "max" + ], + "cost": { + "input": 0.1, + "output": 0.5 + }, + "usable": true, + "login": false + }, + { + "model": "vertex/claude-opus-4-1@20250805", + "provider": "vertex", + "id": "claude-opus-4-1@20250805", + "name": "Claude Opus 4.1", + "context_window": 200000, + "max_output": 32000, + "vision": true, + "reasoning": true, + "cost": { + "input": 15.0, + "output": 75.0 + }, + "usable": true, + "login": false + } +] \ No newline at end of file diff --git a/web/fixtures/questions.jsonl b/web/fixtures/questions.jsonl new file mode 100644 index 00000000..ab0dae2e --- /dev/null +++ b/web/fixtures/questions.jsonl @@ -0,0 +1,64 @@ +{"type": "agent_start", "agent": "lead"} +{"type": "turn_start", "turn": 1, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c1", "name": "ask_user"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"question\":\"Which colour?\",\"context\":\"Two paints are left.\",\"options\":[\"red\",\"blue\"],\"allow_freeform\":true}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c1", "name": "ask_user", "input": {"question": "Which colour?", "context": "Two paints are left.", "options": ["red", "blue"], "allow_freeform": true}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c1", "name": "ask_user", "input": {"question": "Which colour?", "context": "Two paints are left.", "options": ["red", "blue"], "allow_freeform": true}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c1", "name": "ask_user", "input": {"question": "Which colour?", "context": "Two paints are left.", "options": ["red", "blue"], "allow_freeform": true}, "agent": "lead"} +{"type": "ui_request", "request_id": "r1", "kind": "ask", "question": "Which colour?", "context": "Two paints are left.", "expects": "select", "options": ["red", "blue"], "multi": false, "allow_freeform": true} +{"type": "tool_end", "call_id": "c1", "output": {"content": [{"type": "text", "text": "red"}], "is_error": false, "details": {"question": "Which colour?", "context": "Two paints are left.", "type": "select", "options": ["red", "blue"], "recommended": null, "answers": ["red"], "freeform": false, "cancelled": false, "reason": null}}, "duration_ms": 51, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 2, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c2", "name": "ask_user"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"question\":\"Paint it?\",\"type\":\"confirm\"}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c2", "name": "ask_user", "input": {"question": "Paint it?", "type": "confirm"}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c2", "name": "ask_user", "input": {"question": "Paint it?", "type": "confirm"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c2", "name": "ask_user", "input": {"question": "Paint it?", "type": "confirm"}, "agent": "lead"} +{"type": "ui_request", "request_id": "r2", "kind": "ask", "question": "Paint it?", "expects": "confirm", "options": [], "multi": false} +{"type": "tool_end", "call_id": "c2", "output": {"content": [{"type": "text", "text": "yes"}], "is_error": false, "details": {"question": "Paint it?", "context": null, "type": "confirm", "options": [], "recommended": null, "answers": ["yes"], "freeform": false, "cancelled": false, "reason": null}}, "duration_ms": 50, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 3, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c3", "name": "write"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"path\":\"notes/a.txt\",\"content\":\"teal\\n\"}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c3", "name": "write", "input": {"path": "notes/a.txt", "content": "teal\n"}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c3", "name": "write", "input": {"path": "notes/a.txt", "content": "teal\n"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c3", "name": "write", "input": {"path": "notes/a.txt", "content": "teal\n"}, "agent": "lead"} +{"type": "approval_request", "request_id": "r3", "agent": "lead", "tool": "write", "access": "write", "subjects": ["notes/a.txt"], "input": {"path": "notes/a.txt", "content": "teal\n"}, "rule": "write(notes/**)"} +{"type": "tool_end", "call_id": "c3", "output": {"content": [{"type": "text", "text": "created notes/a.txt (5 bytes)"}], "is_error": false, "details": {"path": "notes/a.txt", "diff": "--- a/notes/a.txt\n+++ b/notes/a.txt\n@@ -0,0 +1 @@\n+teal\n"}}, "duration_ms": 52, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 4, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c4", "name": "write"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"path\":\"notes/b.txt\",\"content\":\"dry\\n\"}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c4", "name": "write", "input": {"path": "notes/b.txt", "content": "dry\n"}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c4", "name": "write", "input": {"path": "notes/b.txt", "content": "dry\n"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c4", "name": "write", "input": {"path": "notes/b.txt", "content": "dry\n"}, "agent": "lead"} +{"type": "approval_request", "request_id": "r4", "agent": "lead", "tool": "write", "access": "write", "subjects": ["notes/b.txt"], "input": {"path": "notes/b.txt", "content": "dry\n"}, "rule": "write(notes/**)"} +{"type": "tool_end", "call_id": "c4", "output": {"content": [{"type": "text", "text": "created notes/b.txt (4 bytes)"}], "is_error": false, "details": {"path": "notes/b.txt", "diff": "--- a/notes/b.txt\n+++ b/notes/b.txt\n@@ -0,0 +1 @@\n+dry\n"}}, "duration_ms": 51, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 5, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c5", "name": "ask_user"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"question\":\"Anything else?\"}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c5", "name": "ask_user", "input": {"question": "Anything else?"}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c5", "name": "ask_user", "input": {"question": "Anything else?"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c5", "name": "ask_user", "input": {"question": "Anything else?"}, "agent": "lead"} +{"type": "ui_request", "request_id": "r5", "kind": "ask", "question": "Anything else?", "expects": "text", "options": [], "multi": false} +{"type": "tool_end", "call_id": "c5", "output": {"content": [{"type": "text", "text": "sample answer"}], "is_error": false, "details": {"question": "Anything else?", "context": null, "type": "text", "options": [], "recommended": null, "answers": ["sample answer"], "freeform": false, "cancelled": false, "reason": null}}, "duration_ms": 50, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 6, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "text_delta", "index": 0, "delta": "Painted."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "text", "text": "Painted."}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Painted."}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "stop", "duration_ms": 0}}, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "idle", "stop": "stop", "agent": "lead"} diff --git a/web/fixtures/showcase.jsonl b/web/fixtures/showcase.jsonl new file mode 100644 index 00000000..47a34dd3 --- /dev/null +++ b/web/fixtures/showcase.jsonl @@ -0,0 +1,48 @@ +{"type": "agent_start", "agent": "lead"} +{"type": "turn_start", "turn": 1, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "thinking_delta", "index": 0, "delta": "The user wants the retry policy made exponential. backoff() is linear today, so I should read it first, then change it and make the cap explicit."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "thinking", "text": "The user wants the retry policy made exponential. backoff() is linear today, so I should read it first, then change it and make the cap explicit."}}, "agent": "lead"} +{"type": "stream", "event": {"type": "text_delta", "index": 1, "delta": "I'll look at the current policy before changing it."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 1, "block": {"type": "text", "text": "I'll look at the current policy before changing it."}}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 2, "id": "s1", "name": "read"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 2, "delta": "{\"path\":\"src/retry.rs\"}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 2, "block": {"type": "tool_call", "id": "s1", "name": "read", "input": {"path": "src/retry.rs"}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "thinking", "text": "The user wants the retry policy made exponential. backoff() is linear today, so I should read it first, then change it and make the cap explicit."}, {"type": "text", "text": "I'll look at the current policy before changing it."}, {"type": "tool_call", "id": "s1", "name": "read", "input": {"path": "src/retry.rs"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 1840, "output": 96, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "s1", "name": "read", "input": {"path": "src/retry.rs"}, "agent": "lead"} +{"type": "tool_end", "call_id": "s1", "output": {"content": [{"type": "text", "text": "1\tpub fn backoff(attempt: u32) -> u64 {\n2\t 100 * attempt as u64\n3\t}\n4\t\n5\tpub fn give_up(attempt: u32) -> bool {\n6\t attempt > 3\n7\t}"}], "is_error": false}, "duration_ms": 34, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 2, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "s2", "name": "edit"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"path\":\"src/retry.rs\",\"edits\":[{\"old\":\" 100 * attempt as u64\\n\",\"new\":\" // Doubles each attempt, capped at 30 s.\\n (100u64 << attempt.min(9)).min(30_000)\\n\"},{\"old\":\" attempt > 3\\n\",\"new\":\" attempt >= MAX_ATTEMPTS\\n\"}]}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "s2", "name": "edit", "input": {"path": "src/retry.rs", "edits": [{"old": " 100 * attempt as u64\n", "new": " // Doubles each attempt, capped at 30 s.\n (100u64 << attempt.min(9)).min(30_000)\n"}, {"old": " attempt > 3\n", "new": " attempt >= MAX_ATTEMPTS\n"}]}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "s2", "name": "edit", "input": {"path": "src/retry.rs", "edits": [{"old": " 100 * attempt as u64\n", "new": " // Doubles each attempt, capped at 30 s.\n (100u64 << attempt.min(9)).min(30_000)\n"}, {"old": " attempt > 3\n", "new": " attempt >= MAX_ATTEMPTS\n"}]}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "s2", "name": "edit", "input": {"path": "src/retry.rs", "edits": [{"old": " 100 * attempt as u64\n", "new": " // Doubles each attempt, capped at 30 s.\n (100u64 << attempt.min(9)).min(30_000)\n"}, {"old": " attempt > 3\n", "new": " attempt >= MAX_ATTEMPTS\n"}]}, "agent": "lead"} +{"type": "tool_end", "call_id": "s2", "output": {"content": [{"type": "text", "text": "edited src/retry.rs (2 replacements); formatted with rustfmt"}], "is_error": false, "details": {"path": "src/retry.rs", "diff": "--- a/src/retry.rs\n+++ b/src/retry.rs\n@@ -1,7 +1,8 @@\n pub fn backoff(attempt: u32) -> u64 {\n- 100 * attempt as u64\n+ // Doubles each attempt, capped at 30 s.\n+ (100u64 << attempt.min(9)).min(30_000)\n }\n \n pub fn give_up(attempt: u32) -> bool {\n- attempt > 3\n+ attempt >= MAX_ATTEMPTS\n }\n"}}, "duration_ms": 76, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 3, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "s3", "name": "shell"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"command\":\"printf 'running 2 tests\\ntest retry::backoff_doubles ... ok\\ntest retry::give_up_at_max ... ok\\n\\ntest result: ok. 2 passed\\n'\"}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "s3", "name": "shell", "input": {"command": "printf 'running 2 tests\ntest retry::backoff_doubles ... ok\ntest retry::give_up_at_max ... ok\n\ntest result: ok. 2 passed\n'"}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "s3", "name": "shell", "input": {"command": "printf 'running 2 tests\ntest retry::backoff_doubles ... ok\ntest retry::give_up_at_max ... ok\n\ntest result: ok. 2 passed\n'"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "s3", "name": "shell", "input": {"command": "printf 'running 2 tests\ntest retry::backoff_doubles ... ok\ntest retry::give_up_at_max ... ok\n\ntest result: ok. 2 passed\n'"}, "agent": "lead"} +{"type": "tool_update", "call_id": "s3", "text": "running 2 tests", "agent": "lead"} +{"type": "tool_update", "call_id": "s3", "text": "test retry::backoff_doubles ... ok", "agent": "lead"} +{"type": "tool_update", "call_id": "s3", "text": "test retry::give_up_at_max ... ok", "agent": "lead"} +{"type": "tool_update", "call_id": "s3", "text": "", "agent": "lead"} +{"type": "tool_update", "call_id": "s3", "text": "test result: ok. 2 passed", "agent": "lead"} +{"type": "tool_end", "call_id": "s3", "output": {"content": [{"type": "text", "text": "running 2 tests\ntest retry::backoff_doubles ... ok\ntest retry::give_up_at_max ... ok\n\ntest result: ok. 2 passed\nexit code: 0"}], "is_error": false, "details": {"exit_code": 0, "timed_out": false}}, "duration_ms": 57, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 4, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "text_delta", "index": 0, "delta": "Done. `backoff` now doubles each attempt and never waits longer than 30 s.\n\n## What changed\n\n- `backoff(attempt)` returns `100ms << attempt`, capped at **30 000 ms**\n- `give_up` compares against `MAX_ATTEMPTS` instead of a literal `3`\n\n```rust\npub fn backoff(attempt: u32) -> u64 {\n (100u64 << attempt.min(9)).min(30_000)\n}\n```\n\n| attempt | wait |\n|---|---|\n| 1 | 200 ms |\n| 5 | 3.2 s |\n| 9+ | 30 s |\n\nThe tests did not run here, so `MAX_ATTEMPTS` still needs defining. See [the retry notes](https://example.com/retry)."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "text", "text": "Done. `backoff` now doubles each attempt and never waits longer than 30 s.\n\n## What changed\n\n- `backoff(attempt)` returns `100ms << attempt`, capped at **30 000 ms**\n- `give_up` compares against `MAX_ATTEMPTS` instead of a literal `3`\n\n```rust\npub fn backoff(attempt: u32) -> u64 {\n (100u64 << attempt.min(9)).min(30_000)\n}\n```\n\n| attempt | wait |\n|---|---|\n| 1 | 200 ms |\n| 5 | 3.2 s |\n| 9+ | 30 s |\n\nThe tests did not run here, so `MAX_ATTEMPTS` still needs defining. See [the retry notes](https://example.com/retry)."}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Done. `backoff` now doubles each attempt and never waits longer than 30 s.\n\n## What changed\n\n- `backoff(attempt)` returns `100ms << attempt`, capped at **30 000 ms**\n- `give_up` compares against `MAX_ATTEMPTS` instead of a literal `3`\n\n```rust\npub fn backoff(attempt: u32) -> u64 {\n (100u64 << attempt.min(9)).min(30_000)\n}\n```\n\n| attempt | wait |\n|---|---|\n| 1 | 200 ms |\n| 5 | 3.2 s |\n| 9+ | 30 s |\n\nThe tests did not run here, so `MAX_ATTEMPTS` still needs defining. See [the retry notes](https://example.com/retry)."}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 2410, "output": 233, "cache_read": 1840, "cache_write": 0, "reasoning": 0}, "stop": "stop", "duration_ms": 0}}, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "idle", "stop": "stop", "agent": "lead"} diff --git a/web/fixtures/state.json b/web/fixtures/state.json new file mode 100644 index 00000000..b8aadd69 --- /dev/null +++ b/web/fixtures/state.json @@ -0,0 +1,89 @@ +{ + "session_id": "01a1e0e0-96af-759d-ac3d-3931ebd4d68a", + "session_file": "session.jsonl", + "name": null, + "cwd": "/home/dev/project", + "mode": "manual", + "busy": false, + "turn": 2, + "model": "mock/lead", + "chain": [ + "mock/lead" + ], + "thinking": "off", + "tier": null, + "context_tokens": 2346, + "context_window": 128000, + "usage": { + "input": 0, + "output": 0, + "cache_read": 0, + "cache_write": 0, + "reasoning": 0 + }, + "requests": 1, + "agents": [ + { + "id": "lead", + "def": "lead", + "parent": null, + "depth": 0, + "state": "idle", + "elapsed_ms": 0, + "tokens": 0, + "cost_usd": null + }, + { + "id": "scout-1", + "def": "scout", + "parent": "lead", + "depth": 1, + "state": "done", + "elapsed_ms": 30, + "tokens": 0, + "cost_usd": null + }, + { + "id": "scout-2", + "def": "scout", + "parent": "lead", + "depth": 1, + "state": "failed", + "elapsed_ms": 39, + "tokens": 0, + "cost_usd": null + }, + { + "id": "scout-3", + "def": "scout", + "parent": "lead", + "depth": 1, + "state": "failed", + "elapsed_ms": 39, + "tokens": 0, + "cost_usd": null + } + ], + "branch": null, + "coordinator": false, + "agent": "build", + "primary_agents": [ + { + "name": "build", + "description": "The lead as it works by default, with every tool. Tab switches to plan." + }, + { + "name": "plan", + "description": "Investigates read-only and writes a plan under .azazel/plans/; changes nothing else. Tab switches to build.", + "color": "#539bf5" + } + ], + "goal": null, + "todo": [], + "roles": { + "artist": "mock/lead", + "coder": "mock/lead", + "default": "mock/lead", + "designer": "mock/lead" + } +} \ No newline at end of file diff --git a/web/fixtures/team_goal.jsonl b/web/fixtures/team_goal.jsonl new file mode 100644 index 00000000..d04393e7 --- /dev/null +++ b/web/fixtures/team_goal.jsonl @@ -0,0 +1,114 @@ +{"type": "agent_start", "agent": "lead"} +{"type": "turn_start", "turn": 1, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "text_delta", "index": 0, "delta": "Three scouts first."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "text", "text": "Three scouts first."}}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 1, "id": "t1", "name": "task"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 1, "delta": "{\"agents\":[{\"agent\":\"scout\",\"prompt\":\"Read src/lib.rs and report what `add` does.\"},{\"agent\":\"scout\",\"prompt\":\"Find the tests of this crate and report what they expect.\"},{\"agent\":\"scout\",\"prompt\":\"Read Cargo.toml and report how the crate is built and tested.\"}]}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 1, "block": {"type": "tool_call", "id": "t1", "name": "task", "input": {"agents": [{"agent": "scout", "prompt": "Read src/lib.rs and report what `add` does."}, {"agent": "scout", "prompt": "Find the tests of this crate and report what they expect."}, {"agent": "scout", "prompt": "Read Cargo.toml and report how the crate is built and tested."}]}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Three scouts first."}, {"type": "tool_call", "id": "t1", "name": "task", "input": {"agents": [{"agent": "scout", "prompt": "Read src/lib.rs and report what `add` does."}, {"agent": "scout", "prompt": "Find the tests of this crate and report what they expect."}, {"agent": "scout", "prompt": "Read Cargo.toml and report how the crate is built and tested."}]}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "t1", "name": "task", "input": {"agents": [{"agent": "scout", "prompt": "Read src/lib.rs and report what `add` does."}, {"agent": "scout", "prompt": "Find the tests of this crate and report what they expect."}, {"agent": "scout", "prompt": "Read Cargo.toml and report how the crate is built and tested."}]}, "agent": "lead"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}]} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}]} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}]} +{"type": "user_input", "kind": "prompt", "text": "Find the tests of this crate and report what they expect.", "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}]} +{"type": "user_input", "kind": "prompt", "text": "Read Cargo.toml and report how the crate is built and tested.", "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "queued", "elapsed_ms": 0, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": "starting"}]} +{"type": "user_input", "kind": "prompt", "text": "Read src/lib.rs and report what `add` does.", "agent": "scout-1"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": "starting"}]} +{"type": "agent_start", "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "turn_start", "turn": 1, "agent": "scout-3"} +{"type": "message_start", "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "agent_start", "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "turn_start", "turn": 1, "agent": "scout-2"} +{"type": "message_start", "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "starting"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 9, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "agent_start", "agent": "scout-1"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 11, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 11, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 11, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "turn_start", "turn": 1, "agent": "scout-1"} +{"type": "message_start", "agent": "scout-1"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 11, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 11, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 11, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "stream", "event": {"type": "start"}, "agent": "scout-1"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "t4", "name": "read"}, "agent": "scout-1"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"path\":\"src/lib.rs\"}"}, "agent": "scout-1"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "t4", "name": "read", "input": {"path": "src/lib.rs"}}}, "agent": "scout-1"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "t4", "name": "read", "input": {"path": "src/lib.rs"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "scout-1"} +{"type": "tool_start", "call_id": "t4", "name": "read", "input": {"path": "src/lib.rs"}, "agent": "scout-1"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 15, "tokens": 0, "cost_usd": null, "activity": "read src/lib.rs"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 15, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 15, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "stream", "event": {"type": "start"}, "agent": "scout-2"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "t3", "name": "goal_done"}, "agent": "scout-2"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"summary\":\"The scouts looked at the crate.\",\"evidence\":\"None yet.\"}"}, "agent": "scout-2"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "t3", "name": "goal_done", "input": {"summary": "The scouts looked at the crate.", "evidence": "None yet."}}}, "agent": "scout-2"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "t3", "name": "goal_done", "input": {"summary": "The scouts looked at the crate.", "evidence": "None yet."}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "scout-2"} +{"type": "tool_start", "call_id": "t3", "name": "goal_done", "input": {"summary": "The scouts looked at the crate.", "evidence": "None yet."}, "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "read src/lib.rs"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "tool_end", "call_id": "t3", "output": {"content": [{"type": "text", "text": "unknown tool `goal_done`"}], "is_error": true}, "duration_ms": 0, "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "read src/lib.rs"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "turn_end", "agent": "scout-2"} +{"type": "turn_start", "turn": 2, "agent": "scout-2"} +{"type": "message_start", "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "read src/lib.rs"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 23, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "stream", "event": {"type": "start"}, "agent": "scout-3"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "t2", "name": "shell"}, "agent": "scout-3"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"command\":\"git status --short\"}"}, "agent": "scout-3"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "t2", "name": "shell", "input": {"command": "git status --short"}}}, "agent": "scout-3"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "t2", "name": "shell", "input": {"command": "git status --short"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "scout-3"} +{"type": "tool_start", "call_id": "t2", "name": "shell", "input": {"command": "git status --short"}, "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 24, "tokens": 0, "cost_usd": null, "activity": "read src/lib.rs"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 24, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 24, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "tool_end", "call_id": "t2", "output": {"content": [{"type": "text", "text": "unknown tool `shell`"}], "is_error": true}, "duration_ms": 0, "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 25, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 24, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 24, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "turn_end", "agent": "scout-3"} +{"type": "turn_start", "turn": 2, "agent": "scout-3"} +{"type": "message_start", "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 25, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 24, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 24, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "tool_end", "call_id": "t4", "output": {"content": [{"type": "text", "text": "H:\\Projects\\azazel-cli\\.azazel\\worktrees\\Lane11C\\tmp\\rec\\project\\src\\lib.rs: The system cannot find the path specified. (os error 3)"}], "is_error": true}, "duration_ms": 1, "agent": "scout-1"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 25, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 25, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 24, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "turn_end", "agent": "scout-1"} +{"type": "turn_start", "turn": 2, "agent": "scout-1"} +{"type": "message_start", "agent": "scout-1"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 25, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 25, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 25, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "stream", "event": {"type": "start"}, "agent": "scout-1"} +{"type": "stream", "event": {"type": "text_delta", "index": 0, "delta": "The tests pass now: `add` subtracted its arguments and adds them now."}, "agent": "scout-1"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "text", "text": "The tests pass now: `add` subtracted its arguments and adds them now."}}, "agent": "scout-1"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "The tests pass now: `add` subtracted its arguments and adds them now."}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "stop", "duration_ms": 0}}, "agent": "scout-1"} +{"type": "turn_end", "agent": "scout-1"} +{"type": "idle", "stop": "stop", "agent": "scout-1"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "done", "elapsed_ms": 30, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 30, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 30, "tokens": 0, "cost_usd": null, "activity": "thinking"}]} +{"type": "stream", "event": {"type": "start"}, "agent": "scout-3"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "t6", "name": "goal_done"}, "agent": "scout-3"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"summary\":\"`add` subtracted; it adds now.\",\"evidence\":\"cargo test passes.\"}"}, "agent": "scout-3"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "t6", "name": "goal_done", "input": {"summary": "`add` subtracted; it adds now.", "evidence": "cargo test passes."}}}, "agent": "scout-3"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "t6", "name": "goal_done", "input": {"summary": "`add` subtracted; it adds now.", "evidence": "cargo test passes."}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "scout-3"} +{"type": "tool_start", "call_id": "t6", "name": "goal_done", "input": {"summary": "`add` subtracted; it adds now.", "evidence": "cargo test passes."}, "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "done", "elapsed_ms": 30, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 39, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}]} +{"type": "tool_end", "call_id": "t6", "output": {"content": [{"type": "text", "text": "unknown tool `goal_done`"}], "is_error": true}, "duration_ms": 0, "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "done", "elapsed_ms": 30, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 39, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}]} +{"type": "turn_end", "agent": "scout-3"} +{"type": "turn_start", "turn": 3, "agent": "scout-3"} +{"type": "turn_end", "agent": "scout-3"} +{"type": "failed", "error": "invalid request: mock script exhausted for lead", "agent": "scout-3"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "done", "elapsed_ms": 30, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "running", "elapsed_ms": 39, "tokens": 0, "cost_usd": null, "activity": "thinking"}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}]} +{"type": "stream", "event": {"type": "start"}, "agent": "scout-2"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "t5", "name": "edit"}, "agent": "scout-2"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"path\":\"src/lib.rs\",\"edits\":[{\"old\":\"a - b\",\"new\":\"a + b\"}]}"}, "agent": "scout-2"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "t5", "name": "edit", "input": {"path": "src/lib.rs", "edits": [{"old": "a - b", "new": "a + b"}]}}}, "agent": "scout-2"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "t5", "name": "edit", "input": {"path": "src/lib.rs", "edits": [{"old": "a - b", "new": "a + b"}]}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "scout-2"} +{"type": "tool_start", "call_id": "t5", "name": "edit", "input": {"path": "src/lib.rs", "edits": [{"old": "a - b", "new": "a + b"}]}, "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "done", "elapsed_ms": 30, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}]} +{"type": "tool_end", "call_id": "t5", "output": {"content": [{"type": "text", "text": "unknown tool `edit`"}], "is_error": true}, "duration_ms": 0, "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "done", "elapsed_ms": 30, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}]} +{"type": "turn_end", "agent": "scout-2"} +{"type": "turn_start", "turn": 3, "agent": "scout-2"} +{"type": "turn_end", "agent": "scout-2"} +{"type": "failed", "error": "invalid request: mock script exhausted for lead", "agent": "scout-2"} +{"type": "roster", "members": [{"id": "lead", "def": "lead", "parent": null, "depth": 0, "state": "running", "elapsed_ms": 0, "tokens": 0, "cost_usd": null, "activity": ""}, {"id": "scout-1", "def": "scout", "parent": "lead", "depth": 1, "state": "done", "elapsed_ms": 30, "tokens": 0, "cost_usd": null}, {"id": "scout-2", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}, {"id": "scout-3", "def": "scout", "parent": "lead", "depth": 1, "state": "failed", "elapsed_ms": 39, "tokens": 0, "cost_usd": null}]} +{"type": "tool_end", "call_id": "t1", "output": {"content": [{"type": "text", "text": "## scout-1 (done, 0s)\nThe tests pass now: `add` subtracted its arguments and adds them now.\n\n## scout-2 (failed, 0s)\ninvalid request: mock script exhausted for lead\n\n## scout-3 (failed, 0s)\ninvalid request: mock script exhausted for lead"}], "is_error": false, "details": {"agents": [{"id": "scout-1", "status": "done"}, {"id": "scout-2", "status": "failed"}, {"id": "scout-3", "status": "failed"}]}}, "duration_ms": 40, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 2, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "failed", "error": "invalid request: mock script exhausted for lead", "agent": "lead"} diff --git a/web/fixtures/write_read.jsonl b/web/fixtures/write_read.jsonl new file mode 100644 index 00000000..a757dab4 --- /dev/null +++ b/web/fixtures/write_read.jsonl @@ -0,0 +1,30 @@ +{"type": "agent_start", "agent": "lead"} +{"type": "turn_start", "turn": 1, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c1", "name": "write"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"path\":\"hello.txt\",\"content\":\"hello from azazel\\n\"}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c1", "name": "write", "input": {"path": "hello.txt", "content": "hello from azazel\n"}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c1", "name": "write", "input": {"path": "hello.txt", "content": "hello from azazel\n"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c1", "name": "write", "input": {"path": "hello.txt", "content": "hello from azazel\n"}, "agent": "lead"} +{"type": "approval_request", "request_id": "r1", "agent": "lead", "tool": "write", "access": "write", "subjects": ["hello.txt"], "input": {"path": "hello.txt", "content": "hello from azazel\n"}, "rule": "write(hello.txt)"} +{"type": "tool_end", "call_id": "c1", "output": {"content": [{"type": "text", "text": "created hello.txt (18 bytes)"}], "is_error": false, "details": {"path": "hello.txt", "diff": "--- a/hello.txt\n+++ b/hello.txt\n@@ -0,0 +1 @@\n+hello from azazel\n"}}, "duration_ms": 52, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 2, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_start", "index": 0, "id": "c2", "name": "read"}, "agent": "lead"} +{"type": "stream", "event": {"type": "tool_call_delta", "index": 0, "delta": "{\"path\":\"hello.txt\"}"}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "tool_call", "id": "c2", "name": "read", "input": {"path": "hello.txt"}}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "tool_call", "id": "c2", "name": "read", "input": {"path": "hello.txt"}}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "tool_use", "duration_ms": 0}}, "agent": "lead"} +{"type": "tool_start", "call_id": "c2", "name": "read", "input": {"path": "hello.txt"}, "agent": "lead"} +{"type": "tool_end", "call_id": "c2", "output": {"content": [{"type": "text", "text": "1\thello from azazel"}], "is_error": false}, "duration_ms": 0, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "turn_start", "turn": 3, "agent": "lead"} +{"type": "message_start", "agent": "lead"} +{"type": "stream", "event": {"type": "start"}, "agent": "lead"} +{"type": "stream", "event": {"type": "text_delta", "index": 0, "delta": "Wrote and verified hello.txt."}, "agent": "lead"} +{"type": "stream", "event": {"type": "block_end", "index": 0, "block": {"type": "text", "text": "Wrote and verified hello.txt."}}, "agent": "lead"} +{"type": "message_end", "message": {"role": "assistant", "content": [{"type": "text", "text": "Wrote and verified hello.txt."}], "meta": {"provider": "mock", "model": "lead", "api": "openai-chat", "usage": {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "reasoning": 0}, "stop": "stop", "duration_ms": 0}}, "agent": "lead"} +{"type": "turn_end", "agent": "lead"} +{"type": "idle", "stop": "stop", "agent": "lead"} diff --git a/web/package.json b/web/package.json new file mode 100644 index 00000000..4e6d1ad8 --- /dev/null +++ b/web/package.json @@ -0,0 +1,53 @@ +{ + "name": "azazel-web", + "private": true, + "version": "0.11.0", + "type": "module", + "packageManager": "bun@1.4.4", + "scripts": { + "dev": "vite dev", + "dev:mock": "bun scripts/mock-host.ts", + "build": "vite build && bun scripts/externalize-boot.ts", + "preview": "vite preview", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "lint": "eslint . && prettier --check .", + "format": "prettier --write .", + "test": "vitest run", + "gen:types": "bun scripts/gen-types.ts" + }, + "devDependencies": { + "@eslint/js": "^9", + "@internationalized/date": "^3.12.0", + "@lucide/svelte": "^1.73.0", + "@sveltejs/adapter-static": "^3", + "@sveltejs/kit": "^2", + "@sveltejs/vite-plugin-svelte": "^6", + "@tailwindcss/vite": "^4", + "@testing-library/svelte": "^5.4.2", + "@types/dompurify": "^3.0.5", + "@types/node": "^26.6.6", + "bits-ui": "^2.21.0", + "clsx": "^2.1.1", + "dompurify": "^3.4.18", + "eslint": "^9", + "eslint-plugin-svelte": "^3.24.1", + "globals": "^17.14.0", + "highlight.js": "^11.12.0", + "jsdom": "^26", + "json-schema-to-typescript": "^16.0.0", + "marked": "^18.2.0", + "prettier": "^3.10.1", + "prettier-plugin-svelte": "^4.1.1", + "svelte": "^5.57.3", + "svelte-check": "^4.7.8", + "svelte-eslint-parser": "^1.10.1", + "tailwind-merge": "^3.7.0", + "tailwind-variants": "^3.3.0", + "tailwindcss": "^4", + "typescript": "^5.9", + "typescript-eslint": "^8.72.2", + "uqr": "^0.1.3", + "vite": "^7", + "vitest": "^3" + } +} diff --git a/web/scripts/externalize-boot.ts b/web/scripts/externalize-boot.ts new file mode 100644 index 00000000..531df68e --- /dev/null +++ b/web/scripts/externalize-boot.ts @@ -0,0 +1,38 @@ +// SvelteKit's static adapter writes one inline `; + }); + if (next !== src) writeFileSync(file, next); +} +const left = [...html(build)].filter((f) => + /]*\bsrc=)[^>]*>/.test(readFileSync(f, 'utf8')) +); +if (left.length) { + console.error(`inline scripts remain in: ${left.join(', ')}`); + process.exit(1); +} +console.log(`moved ${moved} inline script(s) out of the HTML`); diff --git a/web/scripts/gen-types.ts b/web/scripts/gen-types.ts new file mode 100644 index 00000000..7e21df98 --- /dev/null +++ b/web/scripts/gen-types.ts @@ -0,0 +1,29 @@ +// Generates src/lib/protocol/rpc.ts from the repository's docs/rpc.schema.json. +// Every definition is listed as a property of one root object so that each becomes a named export. +import { compile } from 'json-schema-to-typescript'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; + +const root = resolve(import.meta.dir, '..'); +const schema = JSON.parse(await readFile(resolve(root, '../docs/rpc.schema.json'), 'utf8')); +const properties = Object.fromEntries( + Object.keys(schema.$defs).map((name) => [name, { $ref: `#/$defs/${name}` }]) +); +const everything = { + $schema: schema.$schema, + title: 'Rpc', + description: schema.description, + type: 'object', + properties, + additionalProperties: false, + $defs: schema.$defs +}; +const out = resolve(root, 'src/lib/protocol/rpc.ts'); +const ts = await compile(everything, 'Rpc', { + bannerComment: '/* Generated from docs/rpc.schema.json by `bun run gen:types`. Do not edit. */', + additionalProperties: false, + style: { singleQuote: true, useTabs: true, printWidth: 100 } +}); +await mkdir(dirname(out), { recursive: true }); +await writeFile(out, ts); +console.log(`wrote ${out}`); diff --git a/web/scripts/mock-host.ts b/web/scripts/mock-host.ts new file mode 100644 index 00000000..b6240344 --- /dev/null +++ b/web/scripts/mock-host.ts @@ -0,0 +1,649 @@ +// A stand-in for `azazel remote` so the page can be built and tested without Rust. +// +// bun run dev:mock serves the API on :7420 (and web/build when it exists) +// bun run dev then the Vite dev server proxies /api here +// +// It speaks the contract of docs/remote.md: /api/pair, /api/me, /api/sessions, /api/links, +// /api/logout and /api/ws/{id}, and replays frames recorded from the real `azazel rpc` with the +// scripted provider (fixtures/*.jsonl). A secret starting with `view` pairs a view-only device. +import { existsSync, readFileSync } from 'node:fs'; +import { extname, join, normalize } from 'node:path'; + +const root = join(import.meta.dir, '..'); +const fx = (name: string) => join(root, 'fixtures', name); +const lines = (name: string): Frame[] => + readFileSync(fx(name), 'utf8') + .split('\n') + .filter(Boolean) + .map((l) => JSON.parse(l)); +const json = (name: string) => JSON.parse(readFileSync(fx(name), 'utf8')); + +type Frame = Record; // eslint-disable-line @typescript-eslint/no-explicit-any + +const port = Number(process.env.PORT ?? process.argv[2] ?? 7420); +const speed = Number(process.env.MOCK_SPEED ?? 1); +const ids = { counter: 0 }; + +const VIEW_COMMANDS = new Set([ + 'attach', + 'get_state', + 'get_messages', + 'get_agent_messages', + 'get_tree', + 'get_usage', + 'list_models', + 'list_roles', + 'list_commands' +]); + +// --- sessions ------------------------------------------------------------------------------ + +interface Scenario { + id: string; + name: string | null; + state: string; + cwd: string; + cost: number | null; + mode: string; + started: string; + frames: string; + prompt: string; + /** Frames sent at once when the session is first opened; the run goes on live after them. */ + prefill: (frames: Frame[]) => number; + autostart: boolean; +} + +const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString(); +const firstIndex = (frames: Frame[], f: (x: Frame) => boolean) => frames.findIndex(f); + +const scenarios: Scenario[] = [ + { + id: 'approve', + name: 'Add rate limiting to /login', + state: 'waiting for you', + cwd: '/home/dev/api-server', + cost: 0.84, + mode: 'manual', + started: minutesAgo(18), + frames: 'write_read.jsonl', + prompt: 'Write hello.txt, then read it back to make sure it is there.', + prefill: (f) => firstIndex(f, (x) => x.type === 'approval_request') + 1, + autostart: true + }, + { + id: 'team', + name: 'Fix the add() regression', + state: 'working', + cwd: '/home/dev/crate-add', + cost: 1.92, + mode: 'auto', + started: minutesAgo(41), + frames: 'team_goal.jsonl', + prompt: 'Fix add(): it subtracts. Use three scouts first, then make the change.', + prefill: (f) => + firstIndex( + f, + (x) => + x.type === 'roster' && + x.members.some((m: Frame) => m.id === 'scout-1' && m.state === 'running') + ) + 6, + autostart: true + }, + { + id: 'showcase', + name: 'Exponential retry backoff', + state: 'idle', + cwd: '/home/dev/net-client', + cost: 0.31, + mode: 'auto', + started: minutesAgo(130), + frames: 'showcase.jsonl', + prompt: 'Make the retry backoff exponential, capped at 30 s.', + prefill: (f) => f.length, + autostart: true + }, + { + id: 'forms', + name: 'Pick a session store', + state: 'waiting for you', + cwd: '/home/dev/sessions-svc', + cost: 0.12, + mode: 'manual', + started: minutesAgo(7), + frames: 'forms.jsonl', + prompt: 'Set up persistence for the session service.', + prefill: (f) => firstIndex(f, (x) => x.type === 'ui_request') + 1, + autostart: true + }, + { + id: 'ended', + name: null, + state: 'interrupted', + cwd: '/home/dev/docs-site', + cost: null, + mode: 'plan', + started: minutesAgo(60 * 26), + frames: 'mention.jsonl', + prompt: 'Summarise the changelog.', + prefill: (f) => f.length, + autostart: true + } +]; + +class Client { + constructor(readonly ws: Bun.ServerWebSocket) {} + send(o: object) { + this.ws.send(JSON.stringify(o)); + } +} +interface WsData { + session: string; + access: 'view' | 'control'; +} + +class MockSession { + log: Frame[] = []; + rows: Frame[] = []; + clients = new Set(); + waiting = new Map void>(); + pendingFrames = new Map(); + state: Frame; + runId = 0; + started = false; + aborted = false; + busy = false; + + constructor(readonly s: Scenario) { + const st = json('state.json'); + st.session_id = s.id; + st.name = s.name; + st.cwd = s.cwd; + st.mode = s.mode; + st.busy = false; + st.model = 'bedrock/anthropic.claude-opus-4-8'; + st.chain = ['bedrock/anthropic.claude-opus-4-8']; + st.thinking = 'medium'; + st.context_tokens = 38_400; + st.context_window = 1_000_000; + st.usage = { + input: 51_200, + output: 6_410, + cache_read: 31_000, + cache_write: 4_000, + reasoning: 0, + cost_usd: s.cost + }; + st.requests = 9; + st.branch = 'main'; + st.agents = [ + { + id: 'lead', + def: 'lead', + parent: null, + depth: 0, + state: 'idle', + elapsed_ms: 0, + tokens: 0, + cost_usd: null + } + ]; + st.todo = [ + { text: 'Read the current retry policy', status: 'done' }, + { text: 'Make backoff exponential with a 30 s cap', status: 'in_progress' }, + { text: 'Run the retry tests', status: 'pending' } + ]; + this.state = st; + } + + get at() { + return this.log.length; + } + + emit(frame: Frame, except?: Client) { + const f = { ...frame, at: this.log.length + 1 }; + this.log.push(f); + this.index(f); + for (const c of this.clients) if (c !== except) c.send(f); + return f; + } + + /** Keeps what `attach` reports as the tail of the conversation. */ + private index(f: Frame) { + const id = `e${this.rows.length + 1}`; + const ts = new Date().toISOString(); + if (f.type === 'user_input' && !f.agent) { + this.rows.push({ + entry_id: id, + timestamp: ts, + message: { role: 'user', content: [{ type: 'text', text: f.text }] } + }); + } else if (f.type === 'message_end' && f.agent === 'lead') { + this.rows.push({ entry_id: id, timestamp: ts, message: f.message }); + } else if (f.type === 'tool_end' && f.agent === 'lead') { + this.rows.push({ + entry_id: id, + timestamp: ts, + message: { + role: 'tool', + content: [ + { + type: 'tool_result', + call_id: f.call_id, + content: f.output.content, + is_error: f.output.is_error + } + ] + } + }); + } else if (f.type === 'roster') { + this.state.agents = f.members; + } else if (f.type === 'agent_start' && f.agent === 'lead') { + this.busy = true; + } else if (f.type === 'idle' && f.agent === 'lead') { + this.busy = false; + } + } + + snapshot() { + return { + busy: this.busy, + tail: this.rows.slice(-20), + streaming: [], + tools: [], + queue: [], + pending: [...this.pendingFrames.keys()] + }; + } + + async run(frames: Frame[], prefill: number, prompt: string) { + const my = ++this.runId; + this.aborted = false; + this.emit({ type: 'user_input', kind: 'prompt', text: prompt }); + for (let i = 0; i < frames.length; i++) { + if (my !== this.runId || this.aborted) return; + let f = frames[i]; + if (f.type === 'user_input' && !f.agent && i === 0) continue; + const live = i >= prefill; + if (f.type === 'stream' && live && ['text_delta', 'thinking_delta'].includes(f.event.type)) { + const text: string = f.event.delta; + for (let p = 0; p < text.length && my === this.runId; p += 14) { + this.emit({ ...f, event: { ...f.event, delta: text.slice(p, p + 14) } }); + await sleep(28); + } + continue; + } + const blocking = + f.type === 'approval_request' || (f.type === 'ui_request' && f.kind !== 'notify'); + f = this.emit(f); + if (blocking) { + this.pendingFrames.set(f.request_id, f); + await new Promise((resolve) => this.waiting.set(f.request_id, resolve)); + if (my !== this.runId) return; + } else if (live) { + await sleep( + f.type === 'tool_end' ? 350 : f.type === 'roster' ? 500 : f.type === 'stream' ? 12 : 70 + ); + } + } + } + + answer(requestId: string, from: Client) { + if (!this.pendingFrames.has(requestId)) return false; + this.pendingFrames.delete(requestId); + for (const c of this.clients) + if (c !== from) c.send({ type: 'request_closed', request_id: requestId }); + this.waiting.get(requestId)?.(); + this.waiting.delete(requestId); + return true; + } + + start(prefillAll = false, prompt?: string) { + const frames = lines(this.s.frames); + const pre = prefillAll ? this.s.prefill(frames) : 0; + void this.run(frames, pre, prompt ?? this.s.prompt); + } +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms / speed)); +const sessions = new Map(scenarios.map((s) => [s.id, new MockSession(s)])); +for (const s of sessions.values()) if (s.s.autostart) s.start(true); + +// --- devices ------------------------------------------------------------------------------- + +const devices = new Map(); +const usedSecrets = new Set(); +const links = new Map(); + +function device(req: Request): 'view' | 'control' | null { + const cookie = req.headers.get('cookie') ?? ''; + const m = /azazel_device=([^;]+)/.exec(cookie); + return m ? (devices.get(m[1]) ?? null) : null; +} + +const me = (access: 'view' | 'control') => ({ + access, + expires: new Date(Date.now() + 24 * 3600_000).toISOString(), + allow_bypass: false, + protocol: 1, + version: '0.11.0-mock' +}); +const j = (body: unknown, init: ResponseInit = {}) => + new Response(JSON.stringify(body), { + ...init, + headers: { + 'content-type': 'application/json', + 'cache-control': 'no-store', + ...(init.headers ?? {}) + } + }); + +// --- commands ------------------------------------------------------------------------------ + +const roles = { roles: [], presets: [], project: false }; +const usage = [ + { + provider: 'anthropic', + account: 'work', + windows: [ + { + name: '5h', + used: 0.42, + resets_at: Math.floor(Date.now() / 1000) + 3 * 3600, + status: 'allowed' + }, + { + name: '7d', + used: 0.81, + resets_at: Math.floor(Date.now() / 1000) + 2 * 86400, + status: 'allowed_warning' + } + ] + } +]; +const files = [ + 'Cargo.toml', + 'src/lib.rs', + 'src/retry.rs', + 'src/net.rs', + 'tests/retry.rs', + 'README.md' +]; + +function respond(c: Client, id: unknown, data: unknown = null) { + c.send({ type: 'response', id, success: true, data }); +} +function fail(c: Client, id: unknown, error: string) { + c.send({ type: 'response', id, success: false, error }); +} + +function handle(s: MockSession, c: Client, access: 'view' | 'control', msg: Frame) { + const { id, type } = msg; + if (access === 'view' && !VIEW_COMMANDS.has(type)) + return fail(c, id, `A view link cannot send \`${type}\`. Ask for a control link.`); + switch (type) { + case 'attach': { + const since: number | undefined = msg.since; + const known = + since === undefined || since === 0 || (since <= s.log.length && s.log[since - 1]); + const missed = since !== undefined && known ? s.log.slice(since) : []; + respond(c, id, { + host: s.s.id, + pid: 4242, + session_id: s.s.id, + session_file: `${s.s.id}.jsonl`, + clients: s.clients.size, + snapshot: s.snapshot(), + cursor: s.log.length, + gap: since !== undefined && !known + }); + for (const f of missed) c.send(f); + for (const f of s.pendingFrames.values()) if (!missed.includes(f)) c.send(f); + return; + } + case 'get_state': + return respond(c, id, { ...s.state, busy: s.busy }); + case 'list_models': + return respond(c, id, json('models.json')); + case 'get_usage': + return respond(c, id, usage); + case 'list_roles': + return respond(c, id, roles); + case 'list_commands': + return respond(c, id, json('commands.json')); + case 'list_files': + return respond(c, id, files); + case 'get_messages': { + const before = s.rows.findIndex((r) => r.entry_id === msg.before); + const end = before < 0 ? s.rows.length : before; + return respond(c, id, s.rows.slice(Math.max(0, end - (msg.limit ?? 50)), end)); + } + case 'get_agent_messages': { + const text = `Task for ${msg.agent}`; + return respond(c, id, [ + { + entry_id: 'x1', + timestamp: minutesAgo(3), + message: { role: 'user', content: [{ type: 'text', text }] } + }, + { + entry_id: 'x2', + timestamp: minutesAgo(2), + message: { + role: 'assistant', + content: [ + { + type: 'text', + text: 'I read the file and found the cause: `add` subtracts its second argument.' + } + ] + } + } + ]); + } + case 'prompt': + case 'steer': + case 'follow_up': { + respond(c, id, null); + s.emit({ type: 'user_input', kind: type === 'prompt' ? 'prompt' : type, text: msg.text }, c); + if (type === 'prompt' && !s.busy) { + const scenario = lines(s.s.frames); + void s.run(scenario, 0, msg.text).catch(() => {}); + // `run` emits its own user_input; the sender does not see it twice because it ignores echoes. + } + return; + } + case 'abort': + s.aborted = true; + s.runId++; + for (const [rid, wake] of s.waiting) { + s.pendingFrames.delete(rid); + wake(); + } + s.waiting.clear(); + respond(c, id, null); + s.emit({ type: 'idle', stop: 'aborted', agent: 'lead' }); + return; + case 'approval_response': + case 'ui_response': + if (!s.answer(msg.request_id, c)) return fail(c, id, 'That request was answered already.'); + return respond(c, id, null); + case 'set_model': + s.state.model = msg.chain[0]; + s.state.chain = msg.chain; + return respond(c, id, { models: msg.chain }); + case 'set_mode': + s.state.mode = msg.mode; + return respond(c, id, { mode: msg.mode }); + case 'set_thinking': + s.state.thinking = msg.level; + return respond(c, id, null); + case 'set_agent': + s.state.agent = msg.agent; + return respond(c, id, { agent: msg.agent }); + case 'agent_send': + return respond(c, id, { agents: [msg.to] }); + case 'agent_stop': + return respond(c, id, { agents: [msg.agent] }); + case 'agent_mention': + return respond(c, id, { agent: msg.name, started: false }); + default: + return respond(c, id, null); + } +} + +// --- static files -------------------------------------------------------------------------- + +const build = join(root, 'build'); +const mime: Record = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript', + '.css': 'text/css', + '.svg': 'image/svg+xml', + '.json': 'application/json', + '.webmanifest': 'application/manifest+json', + '.png': 'image/png', + '.woff2': 'font/woff2' +}; +const CSP = + "default-src 'self'; connect-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'"; + +function asset(path: string): Response { + if (!existsSync(join(build, 'index.html'))) { + return new Response( + 'The web UI was not built. Run `bun run build` in web/, or use `bun run dev`.', + { status: 404 } + ); + } + const clean = normalize(path).replace(/^([/\\])+/, ''); + let file = join(build, clean); + if (!file.startsWith(build) || !existsSync(file) || clean === '') + file = join(build, 'index.html'); + const type = mime[extname(file)] ?? 'application/octet-stream'; + const immutable = file.includes('_app') && file.includes('immutable'); + return new Response(Bun.file(file), { + headers: { + 'content-type': type, + 'content-security-policy': CSP, + 'x-content-type-options': 'nosniff', + 'referrer-policy': 'no-referrer', + 'cache-control': immutable ? 'public, max-age=31536000, immutable' : 'no-cache' + } + }); +} + +// --- server -------------------------------------------------------------------------------- + +const server = Bun.serve({ + port, + hostname: '127.0.0.1', + async fetch(req, srv) { + const url = new URL(req.url); + const p = url.pathname; + if (!p.startsWith('/api/')) return asset(p); + + if (p === '/api/pair' && req.method === 'POST') { + const { secret } = (await req.json().catch(() => ({}))) as { secret?: string }; + if (!secret || usedSecrets.has(secret)) + return j( + { error: 'That link was used already or has expired. Ask for a new one.' }, + { status: 401 } + ); + const access = links.get(secret) ?? (secret.startsWith('view') ? 'view' : 'control'); + if (!secret.endsWith('-demo')) usedSecrets.add(secret); + const token = `tok${++ids.counter}${Math.random().toString(36).slice(2)}`; + devices.set(token, access); + return j(me(access), { + headers: { + 'set-cookie': `azazel_device=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=86400` + } + }); + } + const access = device(req); + if (!access) { + if (p.startsWith('/api/ws/') && req.headers.get('upgrade') === 'websocket') { + // A close code needs an upgraded socket. + return srv.upgrade(req, { data: { session: '!401', access: 'view' } }) + ? undefined + : new Response('unauthorised', { status: 401 }); + } + return j({ error: 'Not signed in. Open a pairing link.' }, { status: 401 }); + } + if (p === '/api/me') return j(me(access)); + if (p === '/api/sessions') { + return j({ + sessions: scenarios.map((s) => ({ + id: s.id, + name: s.name, + kind: 'background', + cwd: s.cwd, + cost_usd: s.cost, + mode: s.mode, + started: s.started, + state: sessions.get(s.id)?.busy ? 'working' : s.state + })) + }); + } + if (p === '/api/links' && req.method === 'POST') { + const { access: want } = (await req.json().catch(() => ({}))) as { + access?: 'view' | 'control'; + }; + if (access === 'view' && want === 'control') + return j({ error: 'A view device cannot make control links.' }, { status: 403 }); + const secret = `${want === 'view' ? 'view' : 'ctl'}${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`; + links.set(secret, want ?? 'view'); + return j({ + url: `${url.origin}/#pair=${secret}`, + access: want, + expires: new Date(Date.now() + 15 * 60_000).toISOString() + }); + } + if (p === '/api/logout' && req.method === 'POST') { + return new Response(null, { + status: 204, + headers: { 'set-cookie': 'azazel_device=; Max-Age=0; Path=/' } + }); + } + const m = /^\/api\/ws\/([^/]+)$/.exec(p); + if (m) { + const id = decodeURIComponent(m[1]); + return srv.upgrade(req, { data: { session: id, access } }) + ? undefined + : new Response('upgrade required', { status: 426 }); + } + return j({ error: 'No such route.' }, { status: 404 }); + }, + websocket: { + open(ws) { + const { session, access } = ws.data; + if (session === '!401') return ws.close(4401, 'not signed in'); + const s = sessions.get(session); + if (!s) return ws.close(4404, 'no such session'); + const c = new Client(ws); + (ws as unknown as { client: Client }).client = c; + s.clients.add(c); + void access; + c.send({ type: 'hello', protocol: 1, version: '0.11.0-mock' }); + }, + message(ws, raw) { + const { session, access } = ws.data; + const s = sessions.get(session); + const c = (ws as unknown as { client: Client }).client; + if (!s || !c) return; + let msg: Frame; + try { + msg = JSON.parse(String(raw)); + } catch { + return c.send({ type: 'response', id: null, success: false, error: 'not JSON' }); + } + handle(s, c, access, msg); + }, + close(ws) { + const c = (ws as unknown as { client?: Client }).client; + if (c) sessions.get(ws.data.session)?.clients.delete(c); + } + } +}); + +console.log(`mock azazel remote on http://127.0.0.1:${server.port}`); +console.log(`control link: http://127.0.0.1:${server.port}/#pair=ctl-demo`); +console.log(`view link: http://127.0.0.1:${server.port}/#pair=view-demo`); diff --git a/web/src/app.css b/web/src/app.css new file mode 100644 index 00000000..b8c880a4 --- /dev/null +++ b/web/src/app.css @@ -0,0 +1,315 @@ +@import 'tailwindcss'; + +/* + * Tokens use shadcn-svelte's names and are defined once with light-dark(). The page follows the + * system; `html.light` / `html.dark` (the theme toggle) overrides it. One accent (amber) marks + * "this needs you" and the primary action. Green, red and blue are status only. + */ +:root { + color-scheme: light dark; + --background: light-dark(#f6f6f7, #0f1012); + --foreground: light-dark(#17181b, #e6e7e9); + --card: light-dark(#ffffff, #15171a); + --raised: light-dark(#eeeef0, #1c1e22); + --border: light-dark(#dcdde1, #272a30); + --input: light-dark(#c4c7ce, #353941); + --muted-foreground: light-dark(#575c66, #8d929c); + --primary: light-dark(#d98a1c, #e8a23c); + --primary-foreground: light-dark(#1c1305, #1a1204); + --accent-text: light-dark(#8a4b00, #f0b45a); + --ring: light-dark(#b86f06, #e8a23c); + --destructive: light-dark(#c4323a, #f0646a); + --destructive-foreground: light-dark(#ffffff, #1a0709); + --success: light-dark(#197a47, #5cc98a); + --info: light-dark(#1f5fbf, #6ea8fe); + --diff-add: light-dark(#dcf3e5, #12281c); + --diff-del: light-dark(#fbe3e4, #301518); + --diff-add-fg: light-dark(#14613a, #7fdba4); + --diff-del-fg: light-dark(#a2262d, #f58d92); + --muted: var(--raised); + --secondary: var(--raised); + --secondary-foreground: var(--foreground); + --accent: var(--raised); + --accent-foreground: var(--foreground); + --popover: var(--card); + --popover-foreground: var(--foreground); + --card-foreground: var(--foreground); +} +:root.light { + color-scheme: light; +} +:root.dark { + color-scheme: dark; +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-raised: var(--raised); + --color-border: var(--border); + --color-input: var(--input); + --color-muted-foreground: var(--muted-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-accent-text: var(--accent-text); + --color-ring: var(--ring); + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + --color-success: var(--success); + --color-info: var(--info); + --color-diff-add: var(--diff-add); + --color-diff-del: var(--diff-del); + --color-diff-add-fg: var(--diff-add-fg); + --color-diff-del-fg: var(--diff-del-fg); + --color-muted: var(--muted); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-card-foreground: var(--card-foreground); + --font-sans: + ui-sans-serif, system-ui, -apple-system, 'Segoe UI Variable', 'Segoe UI', Roboto, + 'Helvetica Neue', Arial, sans-serif; + --font-mono: + ui-monospace, 'SF Mono', 'Cascadia Mono', 'JetBrains Mono', Menlo, Consolas, 'Liberation Mono', + monospace; + --radius-sm: 4px; + --radius-md: 6px; + --radius-lg: 10px; + --radius-xl: 14px; + --text-2xs: 0.6875rem; + --text-2xs--line-height: 1rem; +} + +@layer base { + * { + border-color: var(--border); + } + html, + body { + height: 100%; + overscroll-behavior: none; + } + body { + background: var(--background); + color: var(--foreground); + font-family: var(--font-sans); + font-size: 14px; + line-height: 1.5; + -webkit-font-smoothing: antialiased; + -webkit-text-size-adjust: 100%; + } + :focus-visible { + outline: 2px solid var(--ring); + outline-offset: 2px; + } + button, + [role='button'], + summary, + label[for] { + cursor: pointer; + } + button:disabled { + cursor: not-allowed; + } + ::selection { + background: color-mix(in oklab, var(--primary) 35%, transparent); + } + @media (pointer: coarse) { + input, + textarea, + select { + font-size: 16px; + } + } +} + +@layer components { + .scroll-thin { + scrollbar-width: thin; + scrollbar-color: var(--input) transparent; + } + .no-scrollbar { + scrollbar-width: none; + } + .no-scrollbar::-webkit-scrollbar { + display: none; + } + .num { + font-variant-numeric: tabular-nums; + } + + /* Rendered model markdown. Everything inside is sanitised first. */ + .md { + font-size: 0.9375rem; + line-height: 1.65; + overflow-wrap: anywhere; + } + .md > * + * { + margin-top: 0.75em; + } + .md h1, + .md h2, + .md h3, + .md h4 { + font-weight: 600; + line-height: 1.3; + letter-spacing: -0.01em; + margin-top: 1.25em; + } + .md h1 { + font-size: 1.25rem; + } + .md h2 { + font-size: 1.125rem; + } + .md h3, + .md h4 { + font-size: 1rem; + } + .md ul, + .md ol { + padding-left: 1.4em; + } + .md ul { + list-style: disc; + } + .md ol { + list-style: decimal; + } + .md li + li { + margin-top: 0.25em; + } + .md li::marker { + color: var(--muted-foreground); + } + .md a { + color: var(--accent-text); + text-decoration: underline; + text-underline-offset: 3px; + text-decoration-thickness: 1px; + } + .md blockquote { + border-left: 2px solid var(--input); + padding-left: 0.9em; + color: var(--muted-foreground); + } + .md hr { + border: 0; + border-top: 1px solid var(--border); + margin: 1.25em 0; + } + .md code { + font-family: var(--font-mono); + font-size: 0.85em; + background: var(--raised); + border-radius: 4px; + padding: 0.12em 0.4em; + } + .md pre { + background: var(--card); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: 0.75rem 0.9rem; + overflow-x: auto; + font-size: 0.8125rem; + line-height: 1.55; + scrollbar-width: thin; + } + .md pre code { + background: none; + padding: 0; + font-size: inherit; + } + .md table { + display: block; + overflow-x: auto; + border-collapse: collapse; + font-size: 0.875rem; + } + .md th, + .md td { + border: 1px solid var(--border); + padding: 0.35rem 0.65rem; + text-align: left; + } + .md th { + background: var(--raised); + font-weight: 600; + } + .hljs-comment, + .hljs-quote { + color: var(--muted-foreground); + font-style: italic; + } + .hljs-keyword, + .hljs-selector-tag, + .hljs-built_in, + .hljs-literal { + color: var(--accent-text); + } + .hljs-string, + .hljs-regexp, + .hljs-addition { + color: var(--success); + } + .hljs-number, + .hljs-attr, + .hljs-symbol, + .hljs-bullet { + color: var(--info); + } + .hljs-title, + .hljs-section, + .hljs-name, + .hljs-type { + font-weight: 600; + } + .hljs-deletion { + color: var(--destructive); + } +} + +@keyframes pulse-dot { + 50% { + opacity: 0.35; + } +} +@keyframes sheet-up { + from { + transform: translateY(28px); + opacity: 0; + } +} +@keyframes fade-in { + from { + opacity: 0; + } +} +@keyframes caret { + 50% { + opacity: 0; + } +} +@keyframes hold { + from { + transform: scaleX(0); + } + to { + transform: scaleX(1); + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.001ms !important; + scroll-behavior: auto !important; + } +} diff --git a/web/src/app.html b/web/src/app.html new file mode 100644 index 00000000..2e371f0b --- /dev/null +++ b/web/src/app.html @@ -0,0 +1,18 @@ + + + + + + + + + azazel + %sveltekit.head% + + +
%sveltekit.body%
+ + diff --git a/web/src/lib/answers.ts b/web/src/lib/answers.ts new file mode 100644 index 00000000..29e31a3a --- /dev/null +++ b/web/src/lib/answers.ts @@ -0,0 +1,42 @@ +// What a `ui_response` value looks like for each kind of question (docs/rpc.md, "ui_request"). +import type { Question } from '$lib/protocol'; + +export type Answer = string | string[] | boolean | null; + +/** The state of one question's input in a sheet. */ +export interface Draft { + chosen: string[]; + text: string; + confirm: boolean | null; +} + +export function emptyDraft(q: Pick): Draft { + const rec = q.recommended ?? null; + return { + chosen: rec && q.options?.includes(rec) ? [rec] : [], + text: '', + confirm: rec === 'yes' ? true : rec === 'no' ? false : null + }; +} + +/** The `value` for one question, or null when it is left open. */ +export function answerOf(q: Pick, d: Draft): Answer { + switch (q.expects) { + case 'confirm': + return d.confirm; + case 'text': + return d.text.trim() ? d.text : null; + case 'select': + case 'multiselect': { + const extra = q.allow_freeform && d.text.trim() ? [d.text.trim()] : []; + const all = q.expects === 'select' && extra.length ? extra : [...d.chosen, ...extra]; + return all.length ? all : null; + } + default: + return null; + } +} + +export function answered(q: Pick, d: Draft): boolean { + return answerOf(q, d) !== null; +} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts new file mode 100644 index 00000000..ffc538b2 --- /dev/null +++ b/web/src/lib/api.ts @@ -0,0 +1,60 @@ +// The HTTP half of the remote API (docs/remote.md): pairing, who am I, the session list, links. +import type { Me, SessionInfo } from '$lib/protocol'; + +export class ApiError extends Error { + constructor( + readonly status: number, + message: string + ) { + super(message); + } +} + +async function call(path: string, init: RequestInit = {}): Promise { + const headers: Record = { Accept: 'application/json' }; + if (init.method && init.method !== 'GET') { + headers['X-Azazel'] = '1'; + if (init.body) headers['Content-Type'] = 'application/json'; + } + let res: Response; + try { + res = await fetch(path, { credentials: 'same-origin', cache: 'no-store', ...init, headers }); + } catch { + throw new ApiError(0, 'Cannot reach the azazel server. Is it still running?'); + } + if (!res.ok) { + let message = `${res.status} ${res.statusText}`; + try { + const body = (await res.json()) as { error?: string }; + if (body.error) message = body.error; + } catch { + /* no body */ + } + throw new ApiError(res.status, message); + } + if (res.status === 204) return undefined as T; + return (await res.json()) as T; +} + +export const api = { + me: () => call('/api/me'), + sessions: async () => (await call<{ sessions: SessionInfo[] }>('/api/sessions')).sessions, + pair: (secret: string) => + call('/api/pair', { method: 'POST', body: JSON.stringify({ secret }) }), + link: (access: 'view' | 'control') => + call<{ url: string; access: string; expires: string }>('/api/links', { + method: 'POST', + body: JSON.stringify({ access }) + }), + logout: () => call('/api/logout', { method: 'POST', body: '{}' }) +}; + +/** The secret in `#pair=`, or null. */ +export function pairSecret(hash: string): string | null { + const m = /^#?pair=([A-Za-z0-9_-]+)$/.exec(hash); + return m ? m[1] : null; +} + +export function wsUrl(id: string, loc: Pick = location): string { + return `${loc.protocol === 'https:' ? 'wss:' : 'ws:'}//${loc.host}/api/ws/${encodeURIComponent(id)}`; +} diff --git a/web/src/lib/app.svelte.ts b/web/src/lib/app.svelte.ts new file mode 100644 index 00000000..9ea7e9e1 --- /dev/null +++ b/web/src/lib/app.svelte.ts @@ -0,0 +1,72 @@ +// Page-wide state: who this device is, the theme, toasts. +import { api, ApiError, pairSecret } from '$lib/api'; +import type { Me } from '$lib/protocol'; + +export type Auth = 'checking' | 'pairing' | 'ok' | 'needs-link' | 'error'; + +class App { + me = $state(null); + auth = $state('checking'); + error = $state(null); + theme = $state<'system' | 'light' | 'dark'>('system'); + + applyTheme() { + const stored = (localStorage.getItem('azazel-theme') as App['theme'] | null) ?? 'system'; + this.theme = stored; + this.paint(); + } + setTheme(t: App['theme']) { + this.theme = t; + if (t === 'system') localStorage.removeItem('azazel-theme'); + else localStorage.setItem('azazel-theme', t); + this.paint(); + } + private paint() { + const el = document.documentElement; + el.classList.toggle('light', this.theme === 'light'); + el.classList.toggle('dark', this.theme === 'dark'); + const dark = + this.theme === 'dark' || + (this.theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches); + document + .querySelector('meta[name=theme-color]') + ?.setAttribute('content', dark ? '#0f1012' : '#f6f6f7'); + } + + /** Pairs when the URL carries `#pair=…`, then asks who this device is. */ + async init() { + this.auth = 'checking'; + const secret = pairSecret(location.hash); + try { + if (secret) { + this.auth = 'pairing'; + // The secret must not stay in the address bar or the history. + history.replaceState(null, '', location.pathname + location.search); + this.me = await api.pair(secret); + } else { + this.me = await api.me(); + } + this.auth = 'ok'; + } catch (e) { + this.me = null; + if (e instanceof ApiError && (e.status === 401 || e.status === 429)) { + this.auth = 'needs-link'; + this.error = secret ? e.message : null; + } else { + this.auth = 'error'; + this.error = e instanceof Error ? e.message : String(e); + } + } + } + + get canControl() { + return this.me?.access === 'control'; + } + async logout() { + await api.logout().catch(() => {}); + this.me = null; + this.auth = 'needs-link'; + } +} + +export const app = new App(); diff --git a/web/src/lib/components/AgentHub.svelte b/web/src/lib/components/AgentHub.svelte new file mode 100644 index 00000000..053c1e3b --- /dev/null +++ b/web/src/lib/components/AgentHub.svelte @@ -0,0 +1,114 @@ + + +
+
+ {members.length + ? `${members.length} agent${members.length === 1 ? '' : 's'}` + : 'No agents yet'} + {#if live}{live} active{/if} +
+ + {#if members.length <= 1} +

+ When the lead hands work to sub-agents, they show up here with what each one is doing. You can + open one to read its work, message it or stop it. +

+ {/if} + + +
diff --git a/web/src/lib/components/ApprovalSheet.svelte b/web/src/lib/components/ApprovalSheet.svelte new file mode 100644 index 00000000..24a54f17 --- /dev/null +++ b/web/src/lib/components/ApprovalSheet.svelte @@ -0,0 +1,199 @@ + + + +
+
+ {f.access} + {#if f.destructive}Destroys work{/if} + {#if f.secret}Secret file{/if} + {#if f.agent !== 'lead'}{f.agent}{/if} +
+ + {#if f.subjects?.length} +
    + {#each f.subjects as s (s)}
  • {s}
  • {/each} +
+ {:else} +

{summarize(f.tool, f.input)}

+ {/if} + + {#if f.note}

{f.note}

{/if} + + {#if diff} + + {:else} +
{prettyInput(
+					f.input,
+					900
+				)}
+ {/if} + + {#if denying} + + {/if} + {#if error}{/if} + {#if !canControl}

+ Waiting for an answer from someone with a control link. +

{/if} +
+ + {#snippet footer()} + {#if canControl} + {#if denying} +
+ + +
+ {:else} +
+ {#if f.destructive} + + {:else} + + {/if} + {#if f.rule} + + {#if !f.secret} + + {/if} + {/if} + +
+ {/if} + {:else} +

+ View link: you can watch but not answer. +

+ {/if} + {/snippet} +
diff --git a/web/src/lib/components/Brand.svelte b/web/src/lib/components/Brand.svelte new file mode 100644 index 00000000..a4217c70 --- /dev/null +++ b/web/src/lib/components/Brand.svelte @@ -0,0 +1,13 @@ + + + azazel + diff --git a/web/src/lib/components/Composer.svelte b/web/src/lib/components/Composer.svelte new file mode 100644 index 00000000..ae2643c2 --- /dev/null +++ b/web/src/lib/components/Composer.svelte @@ -0,0 +1,260 @@ + + +
{ + e.preventDefault(); + void submit(); + }} + data-composer +> +
+ {#if mention} +
    + {#each mention.items as it, i (it.kind + it.label)} +
  • + +
  • + {/each} +
+ {/if} + + {#if images.length} +
    + {#each images as im, i (i)} +
  • + Attached {i + 1} + +
  • + {/each} +
+ {/if} + +
+ { + void addFiles(e.currentTarget.files ?? []); + e.currentTarget.value = ''; + }} + /> + + + {#if busy} + + {/if} + +
+ + {#if busy && canControl} +
+ The agent is working. Your message {followUp + ? 'waits until it is done' + : 'reaches it before its next step'}. + +
+ {/if} +
+ diff --git a/web/src/lib/components/DiffView.svelte b/web/src/lib/components/DiffView.svelte new file mode 100644 index 00000000..5f290a64 --- /dev/null +++ b/web/src/lib/components/DiffView.svelte @@ -0,0 +1,58 @@ + + +
+
+
+ {#each shown as l, i (i)} + {#if l.kind === 'meta'} +
{l.text}
+ {:else if l.kind === 'hunk'} +
{l.text}
+ {:else} +
+ + {l.text || ' '} + {#if l.kind === 'add'}added{:else if l.kind === 'del'}removed{/if} +
+ {/if} + {/each} +
+
+
+ +{stats.add} + −{stats.del} + {#if lines.length > max} + + {/if} +
+
diff --git a/web/src/lib/components/Markdown.svelte b/web/src/lib/components/Markdown.svelte new file mode 100644 index 00000000..734b54bb --- /dev/null +++ b/web/src/lib/components/Markdown.svelte @@ -0,0 +1,27 @@ + + +
+ {#each blocks as html, i (i)} + + {@html html} + {/each} + {#if streaming}{/if} +
diff --git a/web/src/lib/components/PairDevice.svelte b/web/src/lib/components/PairDevice.svelte new file mode 100644 index 00000000..c9066ca2 --- /dev/null +++ b/web/src/lib/components/PairDevice.svelte @@ -0,0 +1,87 @@ + + + +
+
+ {#each [['view', 'Watch only'], ['control', 'Full control']] as [v, label] (v)} + + {/each} +
+ {#if !link} + + {:else} + + {link.url} + +

+ Expires {new Date(link.expires).toLocaleTimeString([], { + hour: '2-digit', + minute: '2-digit' + })}. Anyone who opens it first gets in, so share it only with yourself. +

+ {/if} + {#if error}{/if} +
+
diff --git a/web/src/lib/components/QuestionSheet.svelte b/web/src/lib/components/QuestionSheet.svelte new file mode 100644 index 00000000..d1e67f26 --- /dev/null +++ b/web/src/lib/components/QuestionSheet.svelte @@ -0,0 +1,302 @@ + + + +
+ {#if isPlan} +

{f.path}

+
+ +
+ {#if revising} + + {/if} + {:else if q && d} + {#if multiple} +
+ {#each questions as qq, i (i)} + + {/each} +
+ {/if} + + {#if q.context}

+ {q.context} +

{/if} +

{q.question}

+ {#if q.diff} + + {:else if q.code} +
{q.code}
+ {/if} + + {#if q.expects === 'confirm'} +
+ {#each [[true, 'Yes'], [false, 'No']] as [v, label] (label)} + + {/each} +
+ {:else if q.expects === 'select' || q.expects === 'multiselect'} +
    + {#each q.options as opt (opt)} + {@const on = d.chosen.includes(opt)} +
  • + +
  • + {/each} +
+ {/if} + + {#if q.expects === 'text' || q.allow_freeform} + + {/if} + {/if} + {#if error}{/if} +
+ + {#snippet footer()} + {#if !canControl} +

+ View link: waiting for someone with a control link to answer. +

+ {:else if isPlan} + {#if revising} +
+ + +
+ {:else} +
+ + +
+ {/if} + {:else} +
+ + {#if multiple && tab < questions.length - 1} + + {/if} + {#if !multiple || tab === questions.length - 1 || drafts.some((_, i) => answerOf(questions[i], drafts[i]) !== null)} + + {/if} +
+ {/if} + {/snippet} +
diff --git a/web/src/lib/components/SessionList.svelte b/web/src/lib/components/SessionList.svelte new file mode 100644 index 00000000..d9b9a2cf --- /dev/null +++ b/web/src/lib/components/SessionList.svelte @@ -0,0 +1,76 @@ + + + diff --git a/web/src/lib/components/Sheet.svelte b/web/src/lib/components/Sheet.svelte new file mode 100644 index 00000000..033d80e9 --- /dev/null +++ b/web/src/lib/components/Sheet.svelte @@ -0,0 +1,113 @@ + + + { + if (!dismissible) e.preventDefault(); + else onclose?.(); + }} +> + {#if open} +
+ {#if modal} + + {/if} +
+
+

+ {title} +

+ {#if subtitle}

{subtitle}

{/if} +
+ {#if dismissible && onclose} + + {/if} +
+
{@render children()}
+ {#if footer} +
+ {@render footer()} +
+ {:else} +
+ {/if} +
+ {/if} +
+ + diff --git a/web/src/lib/components/StateDot.svelte b/web/src/lib/components/StateDot.svelte new file mode 100644 index 00000000..d8a23ca4 --- /dev/null +++ b/web/src/lib/components/StateDot.svelte @@ -0,0 +1,20 @@ + + + diff --git a/web/src/lib/components/StatusBar.svelte b/web/src/lib/components/StatusBar.svelte new file mode 100644 index 00000000..9638271b --- /dev/null +++ b/web/src/lib/components/StatusBar.svelte @@ -0,0 +1,219 @@ + + +
+ + + + {#if st?.primary_agents && st.primary_agents.length > 1} + + {/if} + {#if st && st.context_window} + + {/if} +
+ + (which = null)} +> + +
    + {#each filtered as m (m.model)} +
  • + +
  • + {:else} +
  • + {session.models.length ? 'No model matches.' : 'Loading models…'} +
  • + {/each} +
+
+ + (which = null)}> +
    + {#each levels as l (l)} +
  • + +
  • + {/each} +
+ {#if levels.length === 1}

+ This model does not think. +

{/if} +
+ + ((which = null), (confirmBypass = false))} +> + {#if confirmBypass} +
+

+ Bypass lifts every guard except deny rules and the push guard. Agents will edit files and + run commands without asking. +

+
+ + +
+
+ {:else} +
    + {#each MODES.filter((m) => m !== 'bypass' || app.me?.allow_bypass) as m (m)} +
  • + +
  • + {/each} +
+ {/if} +
+ + (which = null)}> +
    + {#each st?.primary_agents ?? [] as a (a.name)} +
  • + +
  • + {/each} +
+
diff --git a/web/src/lib/components/ToolCard.svelte b/web/src/lib/components/ToolCard.svelte new file mode 100644 index 00000000..41dee5b4 --- /dev/null +++ b/web/src/lib/components/ToolCard.svelte @@ -0,0 +1,101 @@ + + +
+ + + {#if diff && !open} +
+ {/if} + + {#if open} +
+ {#if diff}{/if} + {#if !diff || (tool.name !== 'edit' && tool.name !== 'write')} +
+
Input
+
{prettyInput(
+							tool.input
+						)}
+
+ {/if} + {#if body} +
+
+ {tool.output ? 'Result' : 'Output so far'}{lines} line{lines === 1 ? '' : 's'} +
+
{body}
+
+ {:else if tool.status === 'done' && !diff} +

No output.

+ {/if} + {#if tool.imageCount}

+ {tool.imageCount} image{tool.imageCount > 1 ? 's' : ''} in the result (not shown here). +

{/if} +
+ {/if} +
diff --git a/web/src/lib/components/Transcript.svelte b/web/src/lib/components/Transcript.svelte new file mode 100644 index 00000000..9a4ec962 --- /dev/null +++ b/web/src/lib/components/Transcript.svelte @@ -0,0 +1,199 @@ + + +
+
+
+ {#if canLoadEarlier} + + {/if} + + {#if items.length === 0} +

{empty}

+ {/if} + + {#each items as item (item.id)} + {#if item.kind === 'user'} +
+
+ {item.via === 'steer' + ? 'Steering' + : item.via === 'follow_up' + ? 'Queued follow-up' + : 'You'} + {#if showAgent && item.agent !== 'lead'}{item.agent}{/if} + {#if item.images}{item.images} image{item.images > 1 ? 's' : ''}{/if} +
+

{item.text}

+
+ {:else if item.kind === 'assistant'} +
+ {#if showAgent && item.agent !== 'lead'}
+ {item.agent} +
{/if} + {#each item.blocks as b (b.index + b.type)} + {#if b.type === 'thinking'} +
+ + {#if thinkingOpen[item.id] ?? item.streaming} +

+ {b.text} +

+ {/if} +
+ {:else} + + {/if} + {/each} + {#if item.streaming && item.blocks.length === 0} + Waiting for the model… + {/if} + {#if item.tokens && !item.streaming} +
+ {tokens(item.tokens.input)} in · {tokens(item.tokens.output)} out{item.model + ? ` · ${item.model}` + : ''} +
+ {/if} +
+ {:else if item.kind === 'tool'} + + {:else} +
+ {item.text} +
+ {/if} + {/each} + + {#if busy && items[items.length - 1]?.kind !== 'assistant'} + + {/if} +
+
+ + {#if !pinned} + + {/if} +
{announce}
+
diff --git a/web/src/lib/components/UsagePanel.svelte b/web/src/lib/components/UsagePanel.svelte new file mode 100644 index 00000000..1aca8052 --- /dev/null +++ b/web/src/lib/components/UsagePanel.svelte @@ -0,0 +1,133 @@ + + +
+ {#if st} +
+
+ Context + {tokens(st.context_tokens)} + of {tokens(st.context_window)} +
+
+
+
+
+ +
+ {#each [['Cost', cost(st.usage.cost_usd)], ['In', tokens(st.usage.input ?? 0)], ['Out', tokens(st.usage.output ?? 0)]] as [k, v] (k)} +
+
{k}
+
{v}
+
+ {/each} +
+

+ {st.requests} request{st.requests === 1 ? '' : 's'} · {tokens(st.usage.cache_read ?? 0)} read from + cache +

+ {/if} + + {#if session.usage.length} +
+

Provider allowance

+
    + {#each session.usage as a (a.provider + a.account)} +
  • +
    + {a.provider} {a.account} +
    + {#each a.windows as w (w.name + (w.scope ?? ''))} +
    +
    + {w.name}{w.scope ? ` · ${w.scope}` : ''} + {Math.round(w.used * 100)}%{w.resets_at + ? ` · resets in ${resetsIn(w.resets_at)}` + : ''} +
    +
    +
    +
    +
    + {/each} +
  • + {/each} +
+
+ {/if} + + {#if todo.length} +
+

+ Plan{done}/{todo.length} +

+
    + {#each todo as t (t.text)} +
  • + + {t.text} + {t.status.replace('_', ' ')} +
  • + {/each} +
+
+ {/if} +
diff --git a/web/src/lib/components/ui/badge/badge.svelte b/web/src/lib/components/ui/badge/badge.svelte new file mode 100644 index 00000000..975feab6 --- /dev/null +++ b/web/src/lib/components/ui/badge/badge.svelte @@ -0,0 +1,50 @@ + + + + + + {@render children?.()} + diff --git a/web/src/lib/components/ui/badge/index.ts b/web/src/lib/components/ui/badge/index.ts new file mode 100644 index 00000000..f05fb87f --- /dev/null +++ b/web/src/lib/components/ui/badge/index.ts @@ -0,0 +1,2 @@ +export { default as Badge } from './badge.svelte'; +export { badgeVariants, type BadgeVariant } from './badge.svelte'; diff --git a/web/src/lib/components/ui/button/button.svelte b/web/src/lib/components/ui/button/button.svelte new file mode 100644 index 00000000..f6170cec --- /dev/null +++ b/web/src/lib/components/ui/button/button.svelte @@ -0,0 +1,89 @@ + + + + +{#if href} + + {@render children?.()} + +{:else} + +{/if} diff --git a/web/src/lib/components/ui/button/index.ts b/web/src/lib/components/ui/button/index.ts new file mode 100644 index 00000000..5414d9d3 --- /dev/null +++ b/web/src/lib/components/ui/button/index.ts @@ -0,0 +1,17 @@ +import Root, { + type ButtonProps, + type ButtonSize, + type ButtonVariant, + buttonVariants +} from './button.svelte'; + +export { + Root, + type ButtonProps as Props, + // + Root as Button, + buttonVariants, + type ButtonProps, + type ButtonSize, + type ButtonVariant +}; diff --git a/web/src/lib/components/ui/collapsible/collapsible-content.svelte b/web/src/lib/components/ui/collapsible/collapsible-content.svelte new file mode 100644 index 00000000..59b068c5 --- /dev/null +++ b/web/src/lib/components/ui/collapsible/collapsible-content.svelte @@ -0,0 +1,7 @@ + + + diff --git a/web/src/lib/components/ui/collapsible/collapsible-trigger.svelte b/web/src/lib/components/ui/collapsible/collapsible-trigger.svelte new file mode 100644 index 00000000..c88cebaf --- /dev/null +++ b/web/src/lib/components/ui/collapsible/collapsible-trigger.svelte @@ -0,0 +1,7 @@ + + + diff --git a/web/src/lib/components/ui/collapsible/collapsible.svelte b/web/src/lib/components/ui/collapsible/collapsible.svelte new file mode 100644 index 00000000..7a8c5da4 --- /dev/null +++ b/web/src/lib/components/ui/collapsible/collapsible.svelte @@ -0,0 +1,11 @@ + + + diff --git a/web/src/lib/components/ui/collapsible/index.ts b/web/src/lib/components/ui/collapsible/index.ts new file mode 100644 index 00000000..0798b15e --- /dev/null +++ b/web/src/lib/components/ui/collapsible/index.ts @@ -0,0 +1,13 @@ +import Content from './collapsible-content.svelte'; +import Trigger from './collapsible-trigger.svelte'; +import Root from './collapsible.svelte'; + +export { + Root, + Content, + Trigger, + // + Root as Collapsible, + Content as CollapsibleContent, + Trigger as CollapsibleTrigger +}; diff --git a/web/src/lib/components/ui/input/index.ts b/web/src/lib/components/ui/input/index.ts new file mode 100644 index 00000000..15c0933d --- /dev/null +++ b/web/src/lib/components/ui/input/index.ts @@ -0,0 +1,7 @@ +import Root from './input.svelte'; + +export { + Root, + // + Root as Input +}; diff --git a/web/src/lib/components/ui/input/input.svelte b/web/src/lib/components/ui/input/input.svelte new file mode 100644 index 00000000..9b425490 --- /dev/null +++ b/web/src/lib/components/ui/input/input.svelte @@ -0,0 +1,48 @@ + + +{#if type === 'file'} + +{:else} + +{/if} diff --git a/web/src/lib/components/ui/separator/index.ts b/web/src/lib/components/ui/separator/index.ts new file mode 100644 index 00000000..768efac9 --- /dev/null +++ b/web/src/lib/components/ui/separator/index.ts @@ -0,0 +1,7 @@ +import Root from './separator.svelte'; + +export { + Root, + // + Root as Separator +}; diff --git a/web/src/lib/components/ui/separator/separator.svelte b/web/src/lib/components/ui/separator/separator.svelte new file mode 100644 index 00000000..47440296 --- /dev/null +++ b/web/src/lib/components/ui/separator/separator.svelte @@ -0,0 +1,21 @@ + + + diff --git a/web/src/lib/components/ui/tabs/index.ts b/web/src/lib/components/ui/tabs/index.ts new file mode 100644 index 00000000..c5a15a0b --- /dev/null +++ b/web/src/lib/components/ui/tabs/index.ts @@ -0,0 +1,18 @@ +import Content from './tabs-content.svelte'; +import Trigger from './tabs-trigger.svelte'; +import Root from './tabs.svelte'; +import List, { tabsListVariants, type TabsListVariant } from './tabs-list.svelte'; + +export { + Root, + Content, + List, + Trigger, + tabsListVariants, + type TabsListVariant, + // + Root as Tabs, + Content as TabsContent, + List as TabsList, + Trigger as TabsTrigger +}; diff --git a/web/src/lib/components/ui/tabs/tabs-content.svelte b/web/src/lib/components/ui/tabs/tabs-content.svelte new file mode 100644 index 00000000..b3f21369 --- /dev/null +++ b/web/src/lib/components/ui/tabs/tabs-content.svelte @@ -0,0 +1,17 @@ + + + diff --git a/web/src/lib/components/ui/tabs/tabs-list.svelte b/web/src/lib/components/ui/tabs/tabs-list.svelte new file mode 100644 index 00000000..c427f3b4 --- /dev/null +++ b/web/src/lib/components/ui/tabs/tabs-list.svelte @@ -0,0 +1,40 @@ + + + + + diff --git a/web/src/lib/components/ui/tabs/tabs-trigger.svelte b/web/src/lib/components/ui/tabs/tabs-trigger.svelte new file mode 100644 index 00000000..e44b29cc --- /dev/null +++ b/web/src/lib/components/ui/tabs/tabs-trigger.svelte @@ -0,0 +1,23 @@ + + + diff --git a/web/src/lib/components/ui/tabs/tabs.svelte b/web/src/lib/components/ui/tabs/tabs.svelte new file mode 100644 index 00000000..fa3450e2 --- /dev/null +++ b/web/src/lib/components/ui/tabs/tabs.svelte @@ -0,0 +1,19 @@ + + + diff --git a/web/src/lib/components/ui/textarea/index.ts b/web/src/lib/components/ui/textarea/index.ts new file mode 100644 index 00000000..9ccb3bff --- /dev/null +++ b/web/src/lib/components/ui/textarea/index.ts @@ -0,0 +1,7 @@ +import Root from './textarea.svelte'; + +export { + Root, + // + Root as Textarea +}; diff --git a/web/src/lib/components/ui/textarea/textarea.svelte b/web/src/lib/components/ui/textarea/textarea.svelte new file mode 100644 index 00000000..706f28e8 --- /dev/null +++ b/web/src/lib/components/ui/textarea/textarea.svelte @@ -0,0 +1,22 @@ + + + diff --git a/web/src/lib/context.ts b/web/src/lib/context.ts new file mode 100644 index 00000000..99dd2937 --- /dev/null +++ b/web/src/lib/context.ts @@ -0,0 +1,6 @@ +import { getContext, setContext } from 'svelte'; +import type { Session } from '$lib/session/session.svelte'; + +const KEY = Symbol('session'); +export const setSession = (s: Session) => setContext(KEY, s); +export const getSession = () => getContext(KEY); diff --git a/web/src/lib/format.ts b/web/src/lib/format.ts new file mode 100644 index 00000000..a8f552c7 --- /dev/null +++ b/web/src/lib/format.ts @@ -0,0 +1,44 @@ +export function duration(ms: number): string { + if (ms < 1000) return `${Math.round(ms)} ms`; + const s = ms / 1000; + if (s < 60) return `${s < 10 ? s.toFixed(1) : Math.round(s)} s`; + const m = Math.floor(s / 60); + return `${m}m ${String(Math.round(s % 60)).padStart(2, '0')}s`; +} + +export function tokens(n: number): string { + if (n < 1000) return String(n); + if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`; + return `${(n / 1_000_000).toFixed(1)}M`; +} + +export function cost(usd: number | null | undefined): string { + if (usd === null || usd === undefined) return '—'; + return usd < 0.01 && usd > 0 ? '<$0.01' : `$${usd.toFixed(2)}`; +} + +export function basename(path: string): string { + const parts = path.replace(/[\\/]+$/, '').split(/[\\/]/); + return parts[parts.length - 1] || path; +} + +/** `src/lib/a.rs` shortened to its last segments when long. */ +export function shortPath(path: string, keep = 3): string { + const parts = path.split(/[\\/]/).filter(Boolean); + return parts.length <= keep ? path : `…/${parts.slice(-keep).join('/')}`; +} + +export function ago(iso: string, now = Date.now()): string { + const s = Math.max(0, (now - Date.parse(iso)) / 1000); + if (s < 60) return 'just now'; + if (s < 3600) return `${Math.floor(s / 60)} min ago`; + if (s < 86400) return `${Math.floor(s / 3600)} h ago`; + return `${Math.floor(s / 86400)} d ago`; +} + +export function resetsIn(unix: number, now = Date.now()): string { + const s = Math.max(0, unix - now / 1000); + if (s < 3600) return `${Math.ceil(s / 60)} min`; + if (s < 86400) return `${Math.round(s / 3600)} h`; + return `${Math.round(s / 86400)} d`; +} diff --git a/web/src/lib/images.ts b/web/src/lib/images.ts new file mode 100644 index 00000000..fee790b9 --- /dev/null +++ b/web/src/lib/images.ts @@ -0,0 +1,27 @@ +// Images attached to a prompt are downscaled in a canvas so a phone photo does not exceed the +// 12 MiB message limit, and are sent as `{mime, data}` with base64 data. +import type { Image } from '$lib/protocol'; + +export const MAX_SIDE = 2048; + +/** Size after fitting inside MAX_SIDE, keeping the aspect ratio. Never upscales. */ +export function fit(w: number, h: number, max = MAX_SIDE): { w: number; h: number } { + const scale = Math.min(1, max / Math.max(w, h)); + return { w: Math.max(1, Math.round(w * scale)), h: Math.max(1, Math.round(h * scale)) }; +} + +export async function toImage(file: File): Promise { + const bitmap = await createImageBitmap(file); + const { w, h } = fit(bitmap.width, bitmap.height); + const canvas = document.createElement('canvas'); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext('2d'); + if (!ctx) throw new Error('This browser cannot resize images.'); + ctx.drawImage(bitmap, 0, 0, w, h); + bitmap.close(); + const keepPng = file.type === 'image/png' && w * h < 1_500_000; + const mime = keepPng ? 'image/png' : 'image/jpeg'; + const url = canvas.toDataURL(mime, 0.85); + return { mime, data: url.slice(url.indexOf(',') + 1), preview: url }; +} diff --git a/web/src/lib/markdown.ts b/web/src/lib/markdown.ts new file mode 100644 index 00000000..c7453974 --- /dev/null +++ b/web/src/lib/markdown.ts @@ -0,0 +1,173 @@ +// Markdown from the model is untrusted. It is parsed with marked, highlighted, then sanitised with +// DOMPurify against a short allowlist before it is ever put into the page. +import DOMPurify from 'dompurify'; +import hljs from 'highlight.js/lib/core'; +import { Marked, type Tokens } from 'marked'; + +type Loader = () => Promise<{ default: Parameters[1] }>; +const languages: Record = { + javascript: { + names: ['js', 'jsx', 'mjs'], + load: () => import('highlight.js/lib/languages/javascript') + }, + typescript: { names: ['ts', 'tsx'], load: () => import('highlight.js/lib/languages/typescript') }, + json: { names: ['jsonc'], load: () => import('highlight.js/lib/languages/json') }, + bash: { + names: ['sh', 'shell', 'zsh', 'console'], + load: () => import('highlight.js/lib/languages/bash') + }, + rust: { names: ['rs'], load: () => import('highlight.js/lib/languages/rust') }, + python: { names: ['py'], load: () => import('highlight.js/lib/languages/python') }, + go: { names: ['golang'], load: () => import('highlight.js/lib/languages/go') }, + diff: { names: ['patch'], load: () => import('highlight.js/lib/languages/diff') }, + yaml: { names: ['yml'], load: () => import('highlight.js/lib/languages/yaml') }, + css: { names: [], load: () => import('highlight.js/lib/languages/css') }, + xml: { + names: ['html', 'svg', 'svelte', 'vue'], + load: () => import('highlight.js/lib/languages/xml') + }, + ini: { names: ['toml'], load: () => import('highlight.js/lib/languages/ini') }, + sql: { names: [], load: () => import('highlight.js/lib/languages/sql') }, + markdown: { names: ['md'], load: () => import('highlight.js/lib/languages/markdown') } +}; +const alias = new Map(); +for (const [name, { names }] of Object.entries(languages)) { + alias.set(name, name); + for (const n of names) alias.set(n, name); +} +const loaded = new Set(); +const cache = new Map(); + +/** Loads the highlighters the fenced blocks of `source` ask for. Resolves true when something new loaded. */ +export async function loadLanguages(source: string): Promise { + const wanted = new Set(); + for (const m of source.matchAll(/^[ \t]*(?:```|~~~)\s*([\w+-]+)/gm)) { + const name = alias.get(m[1].toLowerCase()); + if (name && !loaded.has(name)) wanted.add(name); + } + await Promise.all( + [...wanted].map(async (name) => { + const mod = await languages[name].load(); + hljs.registerLanguage(name, mod.default); + loaded.add(name); + }) + ); + if (wanted.size) cache.clear(); + return wanted.size > 0; +} + +const escape = (s: string) => + s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + +const marked = new Marked({ + gfm: true, + breaks: false, + renderer: { + code({ text, lang }: Tokens.Code) { + const name = alias.get((lang ?? '').trim().split(/\s+/)[0].toLowerCase()); + let body = escape(text); + let cls = ''; + if (name && loaded.has(name)) { + body = hljs.highlight(text, { language: name, ignoreIllegals: true }).value; + cls = ` class="hljs language-${name}"`; + } + return `
${body}
`; + }, + // Raw HTML typed by the model is shown as text, not parsed. + html({ text }: Tokens.HTML | Tokens.Tag) { + return escape(text); + }, + image({ text }: Tokens.Image) { + return escape(text); + } + } +}); + +const SAFE_CLASS = /^(hljs(-[a-z_]+)?|language-[a-z0-9+-]+)$/; +let hooked = false; +function purifier() { + if (!hooked) { + hooked = true; + DOMPurify.addHook('afterSanitizeAttributes', (node) => { + if (node.hasAttribute('class')) { + // A class from the model must not reach the page's own utility classes. + const kept = (node.getAttribute('class') ?? '') + .split(/\s+/) + .filter((c) => SAFE_CLASS.test(c)); + if (kept.length) node.setAttribute('class', kept.join(' ')); + else node.removeAttribute('class'); + } + if (node.tagName === 'A') { + node.setAttribute('target', '_blank'); + node.setAttribute('rel', 'noopener noreferrer nofollow'); + } + }); + } + return DOMPurify; +} + +const ALLOWED_TAGS = [ + 'p', + 'br', + 'hr', + 'strong', + 'em', + 'del', + 'code', + 'pre', + 'blockquote', + 'ul', + 'ol', + 'li', + 'a', + 'span', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'table', + 'thead', + 'tbody', + 'tr', + 'th', + 'td', + 'input' +]; + +export function sanitize(html: string): string { + return purifier().sanitize(html, { + ALLOWED_TAGS, + ALLOWED_ATTR: ['href', 'title', 'class', 'start', 'type', 'checked', 'disabled'], + ALLOW_DATA_ATTR: false, + ALLOWED_URI_REGEXP: /^(?:https?|mailto):/i + }); +} + +/** Renders markdown to safe HTML. */ +export function renderMarkdown(source: string): string { + return sanitize(marked.parse(source, { async: false }) as string); +} + +/** + * Renders a growing text as one HTML string per top-level block. A block that the text has moved past + * is rendered once and served from a cache, so a long reply costs one render of its last block per + * delta, not one of the whole reply. + */ +export function renderBlocks(source: string, final = false): string[] { + const tokens = marked.lexer(source); + const out: string[] = []; + tokens.forEach((t, i) => { + const open = !final && i === tokens.length - 1; + if (t.type === 'space') return; + if (open) return void out.push(renderMarkdown(t.raw)); + const hit = cache.get(t.raw); + if (hit !== undefined) return void out.push(hit); + const html = renderMarkdown(t.raw); + if (cache.size > 800) cache.clear(); + cache.set(t.raw, html); + out.push(html); + }); + return out; +} diff --git a/web/src/lib/media.svelte.ts b/web/src/lib/media.svelte.ts new file mode 100644 index 00000000..20feaa4c --- /dev/null +++ b/web/src/lib/media.svelte.ts @@ -0,0 +1,17 @@ +// Viewport facts the layout needs in script (the rest is CSS). +class Viewport { + wide = $state(false); // >= 768: sheets dock beside the chat instead of covering the screen + lg = $state(false); // >= 1024: the agents and usage pane has room + coarse = $state(false); // a touch screen: Enter in the composer makes a new line + init() { + const watch = (q: string, set: (v: boolean) => void) => { + const m = matchMedia(q); + set(m.matches); + m.addEventListener('change', (e) => set(e.matches)); + }; + watch('(min-width: 768px)', (v) => (this.wide = v)); + watch('(min-width: 1024px)', (v) => (this.lg = v)); + watch('(pointer: coarse)', (v) => (this.coarse = v)); + } +} +export const viewport = new Viewport(); diff --git a/web/src/lib/protocol/index.ts b/web/src/lib/protocol/index.ts new file mode 100644 index 00000000..4d00af33 --- /dev/null +++ b/web/src/lib/protocol/index.ts @@ -0,0 +1,93 @@ +// Types of the RPC protocol, from the generated schema, plus what the schema does not carry yet: +// the optional members of the remote protocol (`at`, `since`, `cursor`, `gap`, paged history). +import type { Frame, Request, Attached, Snapshot, MessageRow } from './rpc'; + +export type { + Frame, + Request, + State, + Member, + Question1 as Question, + ModelRow, + AccountUsage, + Window, + Todo, + Usage1 as Usage, + PrimaryAgent, + RoleRow, + Roles, + CommandRow, + Image, + Decision, + MessageRow, + Attached, + Snapshot, + Streaming, + RunningTool, + Queued, + StreamEvent +} from './rpc'; + +/** One frame of a given `type`, with the log position the host added. */ +export type FrameOf = Extract & { at?: number }; +export type AnyFrame = Frame & { at?: number }; + +/** `Attached` as a remote host answers it: with a cursor and a gap flag. */ +export type AttachedRemote = Attached & { cursor?: number; gap?: boolean }; +export type SnapshotRemote = Snapshot; + +/** Commands the page sends. `id` is added by the client. */ +export type Command = Request extends infer R + ? R extends { type: string } + ? Omit + : never + : never; +export type CommandType = Command['type']; + +/** Content blocks of a message, as `azazel-ai` writes them. */ +export type Block = + | { type: 'text'; text: string } + | { type: 'thinking'; text: string; redacted?: boolean } + | { type: 'image'; mime: string; data: string } + | { type: 'tool_call'; id: string; name: string; input: unknown } + | { type: 'tool_result'; call_id: string; content: Block[]; is_error?: boolean } + | { type: 'opaque'; provider: string; item: unknown }; + +export interface WireMessage { + role: 'user' | 'assistant' | 'tool' | 'system'; + content: Block[]; + meta?: { + provider?: string; + model?: string; + usage?: { input: number; output: number; cache_read?: number; cache_write?: number }; + stop?: string; + duration_ms?: number; + }; +} + +export type Row = Omit & { message: WireMessage }; + +/** `GET /api/me`. */ +export interface Me { + access: 'view' | 'control'; + expires: string; + allow_bypass: boolean; + protocol: number; + version: string; +} + +/** One entry of `GET /api/sessions`. */ +export interface SessionInfo { + id: string; + name: string | null; + kind: 'background' | 'terminal'; + state: string; + cwd: string; + cost_usd: number | null; + mode: string | null; + started: string; +} + +export const MODES = ['plan', 'manual', 'accept-edits', 'auto', 'bypass'] as const; +export const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const; +export const TIERS = ['priority', 'standard', 'economy'] as const; diff --git a/web/src/lib/protocol/rpc.ts b/web/src/lib/protocol/rpc.ts new file mode 100644 index 00000000..3d6af9b3 --- /dev/null +++ b/web/src/lib/protocol/rpc.ts @@ -0,0 +1,1257 @@ +/* Generated from docs/rpc.schema.json by `bun run gen:types`. Do not edit. */ + +/** + * One line from the client: a command and the id its response repeats. + */ +export type Request = { + /** + * Any JSON value of the client's choosing; `null` when left out. + */ + id?: { + [k: string]: unknown; + }; +} & Request1; +export type Request1 = + | { + type: 'prompt'; + text: string; + images?: Image[]; + /** + * A name of the client's choosing for this prompt, to send it again safely. + */ + request_id?: string | null; + } + | { + type: 'continue_run'; + } + | { + type: 'steer'; + text: string; + images?: Image[]; + } + | { + type: 'follow_up'; + text: string; + } + | { + type: 'abort'; + } + | { + type: 'get_state'; + } + | { + type: 'set_model'; + chain: string[]; + } + | { + type: 'set_mode'; + mode: string; + } + | { + type: 'set_agent'; + agent: string; + } + | { + type: 'agent_send'; + to: string; + message: string; + } + | { + type: 'agent_stop'; + agent: string; + } + | { + type: 'agent_mention'; + name: string; + text: string; + } + | { + type: 'approval_response'; + request_id: string; + decision: Decision; + feedback?: string | null; + } + | { + type: 'ui_response'; + request_id: string; + value?: { + [k: string]: unknown; + }; + } + | { + type: 'new_session'; + name?: string | null; + } + | { + type: 'resume_session'; + session_id?: string | null; + path?: string | null; + } + | { + type: 'fork_session'; + entry_id?: string | null; + } + | { + type: 'list_sessions'; + query?: string | null; + } + | { + type: 'get_messages'; + leaf?: string | null; + } + | { + type: 'get_tree'; + } + | { + type: 'set_leaf'; + entry_id: string; + before?: boolean; + } + | { + type: 'set_label'; + entry_id: string; + label: string; + } + | { + type: 'get_session'; + } + | { + type: 'set_name'; + name: string; + } + | { + type: 'set_thinking'; + level: string; + } + | { + type: 'set_tier'; + tier: string; + } + | { + type: 'compact'; + instructions?: string | null; + } + | { + type: 'retry'; + } + | { + type: 'rewind'; + entry_id: string; + /** + * What `rewind` takes back. + */ + what?: 'both' | 'code' | 'conversation'; + } + | { + type: 'shell'; + command: string; + share?: boolean; + } + | { + type: 'export'; + format?: ExportFormat | null; + path?: string | null; + } + | { + type: 'btw'; + question: string; + } + | { + type: 'list_models'; + all?: boolean; + } + | { + type: 'list_providers'; + } + | { + type: 'refresh_models'; + provider: string; + } + | { + type: 'list_roles'; + } + | { + type: 'set_role'; + role: string; + chain?: string[] | null; + /** + * Where `set_role` keeps a change. + */ + save?: 'session' | 'home' | 'project'; + } + | { + type: 'save_preset'; + name: string; + } + | { + type: 'apply_preset'; + name: string; + } + | { + type: 'list_commands'; + } + | { + type: 'list_files'; + } + | { + type: 'get_usage'; + } + | { + type: 'run_command'; + name: string; + args?: string; + } + | { + type: 'attach'; + pid?: number | null; + /** + * What a client that attaches to a background session is sent of what happened before. + */ + replay?: 'missed' | 'all' | 'none'; + } + | { + type: 'stop'; + now?: boolean; + }; +/** + * The answer to an `approval_request`. + */ +export type Decision = 'allow' | 'session' | 'always' | 'deny'; +/** + * The file format of `export`. + */ +export type ExportFormat = 'markdown' | 'html' | 'jsonl'; +/** + * What `rewind` takes back. + */ +export type RewindWhat = 'both' | 'code' | 'conversation'; +/** + * Where `set_role` keeps a change. + */ +export type SaveTo = 'session' | 'home' | 'project'; +/** + * What a client that attaches to a background session is sent of what happened before. + */ +export type Replay = 'missed' | 'all' | 'none'; +/** + * One line from azazel. `type` names the frame; frames of an agent carry its id as `agent` + * (`lead` for the main agent). + */ +export type Frame = + | { + type: 'hello'; + protocol: number; + version: string; + } + | Response + | { + type: 'agent_start'; + agent: string; + } + | { + type: 'turn_start'; + agent: string; + turn: number; + } + | { + type: 'message_start'; + agent: string; + } + | { + type: 'stream'; + agent: string; + event: StreamEvent; + } + | { + type: 'message_end'; + agent: string; + message: unknown; + } + | { + type: 'tool_start'; + agent: string; + call_id: string; + name: string; + input: unknown; + } + | { + type: 'tool_update'; + agent: string; + call_id: string; + text: string; + } + | { + type: 'tool_end'; + agent: string; + call_id: string; + output: ToolOutput; + duration_ms: number; + } + | { + type: 'turn_end'; + agent: string; + } + | { + type: 'retry'; + agent: string; + attempt: number; + model: string; + /** + * The model had sent nothing for this many seconds; absent after any other failure. + */ + stalled_secs?: number | null; + } + | { + type: 'fallback'; + agent: string; + from: string; + to: string; + } + | { + type: 'account'; + agent: string; + provider: string; + from: string; + to: string; + until: number; + limit: string; + } + | { + type: 'tier_dropped'; + agent: string; + model: string; + tier: string; + } + | { + type: 'rule'; + agent: string; + name: string; + } + | { + type: 'compaction'; + agent: string; + tokens_before: number; + tokens_after: number; + } + | { + type: 'idle'; + agent: string; + stop: string; + } + | { + type: 'failed'; + agent: string; + error: string; + } + | { + type: 'roster'; + members: Member[]; + } + | { + type: 'approval_request'; + request_id: string; + agent: string; + tool: string; + /** + * `read`, `write`, `exec` or `net`. + */ + access: string; + /** + * What permission rules are matched against: paths, commands, `domain:`. + */ + subjects: string[]; + input: unknown; + /** + * The allow rule that `always` would add. + */ + rule?: string | null; + /** + * A remark to show, such as a cost warning. + */ + note?: string | null; + /** + * The call would destroy work: approval should not be the answer a stray key gives. + */ + destructive?: boolean; + /** + * The call reads or writes a secret file (`.env`, a private key): `session` allows that + * file until the session ends, and `always` is not on offer. + */ + secret?: boolean; + } + | (( + | Question + | { + kind: 'form'; + questions: Question1[]; + } + | { + kind: 'confirm'; + prompt: string; + } + | { + kind: 'select'; + prompt: string; + options: string[]; + } + | { + kind: 'input'; + prompt: string; + secret?: boolean; + } + | { + kind: 'plan'; + path: string; + plan: string; + } + | { + kind: 'notify'; + level: string; + text: string; + } + ) & { + type: 'ui_request'; + request_id: string; + }) + | { + type: 'btw_delta'; + id: unknown; + delta: string; + } + | { + type: 'user_input'; + kind: string; + text: string; + agent?: string | null; + } + | { + type: 'request_closed'; + request_id: string; + }; +/** + * A part of the message the model is writing. Deltas are for display; `message_end` carries + * the complete message. + */ +export type StreamEvent = + | { + type: 'start'; + } + | { + type: 'text_delta'; + index: number; + delta: string; + } + | { + type: 'thinking_delta'; + index: number; + delta: string; + } + | { + type: 'tool_call_start'; + index: number; + id: string; + name: string; + } + | { + type: 'tool_call_delta'; + index: number; + delta: string; + } + | { + type: 'block_end'; + index: number; + block: unknown; + }; +/** + * How an `ask` request is answered. + */ +export type AskKind = 'select' | 'multiselect' | 'text' | 'confirm'; +/** + * Where a role's chain comes from. + */ +export type RoleSource = ('home' | 'project' | 'project_local') | 'builtin' | 'session' | 'unset'; +/** + * The data of `run_command`. + */ +export type CommandResult = + | { + outcome: 'done'; + } + | { + outcome: 'show'; + text: string; + } + | { + outcome: 'prompt'; + text: string; + }; + +/** + * Protocol 1 of `azazel rpc`. Each line is one JSON object: a Request from the client, or a Frame from azazel. + */ +export interface Rpc { + Request?: Request; + Image?: Image; + Decision?: Decision; + RewindWhat?: RewindWhat; + ExportFormat?: ExportFormat; + SaveTo?: SaveTo; + Replay?: Replay; + Frame?: Frame; + Response?: Response1; + StreamEvent?: StreamEvent; + ToolOutput?: ToolOutput; + Member?: Member; + AskKind?: AskKind; + Question?: Question1; + State?: State; + Usage?: Usage1; + PrimaryAgent?: PrimaryAgent; + Todo?: Todo; + Models?: Models; + SessionRow?: SessionRow; + MessageRow?: MessageRow; + TreeRow?: TreeRow; + ModelRow?: ModelRow; + ModelCost?: ModelCost; + ProviderRow?: ProviderRow; + Roles?: Roles; + RoleRow?: RoleRow; + RoleSource?: RoleSource; + AccountUsage?: AccountUsage; + Window?: Window; + UsageBlock?: UsageBlock; + ShellResult?: ShellResult; + Exported?: Exported; + BtwAnswer?: BtwAnswer; + CommandResult?: CommandResult; + Attached?: Attached; + Snapshot?: Snapshot1; + Streaming?: Streaming; + RunningTool?: RunningTool; + Queued?: Queued; + RunState?: RunState; + Mentioned?: Mentioned; + SessionCopy?: SessionCopy; + CommandRow?: CommandRow; +} +/** + * An image sent with a prompt. + */ +export interface Image { + /** + * For example `image/png`. + */ + mime: string; + /** + * The bytes, base64-encoded. + */ + data: string; +} +/** + * The answer to one command. `data` is present when `success` is true, `error` when it is not. + */ +export interface Response { + type: 'response'; +} +/** + * What a tool returned. + */ +export interface ToolOutput { + /** + * `text` and `image` blocks. + */ + content: unknown[]; + is_error: boolean; + /** + * Structured data for display (diffs, exit codes); the model never sees it. + */ + details?: { + [k: string]: unknown; + }; +} +/** + * One agent of the roster. + */ +export interface Member { + id: string; + /** + * The agent definition it runs as; `lead` for the main agent. + */ + def: string; + parent?: string | null; + depth: number; + /** + * `queued`, `running`, `waiting for approval`, `idle`, `done`, `failed` or `stopped`. + */ + state: string; + elapsed_ms: number; + tokens: number; + cost_usd?: number | null; + /** + * What a running agent is doing, in a few words. + */ + activity?: string | null; +} +/** + * A question from an agent. Expects what `expects` says: a list of the chosen options + * (`select`, `multiselect`), a string (`text`), or `true` or `false` (`confirm`). With + * `allow_freeform`, a string that is none of the options is an answer the user typed. + */ +export interface Question { + kind: 'ask'; +} +/** + * A question from an agent: an `ask` request, or one of the questions of a `form`. + */ +export interface Question1 { + question: string; + /** + * A word or two naming the question among the others of a form. + */ + header?: string | null; + /** + * What the user needs to know to answer, to be shown with the question. + */ + context?: string | null; + /** + * Code the question is about, to be shown with it as it is written. + */ + code?: string | null; + /** + * A unified diff the question is about, to be shown with it. + */ + diff?: string | null; + /** + * Always sent; a client reads a request without it with [`AskKind::of`]. + */ + expects?: AskKind | null; + /** + * The choices of a `select` or `multiselect`; empty otherwise. + */ + options?: string[]; + /** + * Whether `expects` is `multiselect`. + */ + multi?: boolean; + /** + * The answer the agent would give: one of `options`, or `yes` or `no` for a `confirm`. + */ + recommended?: string | null; + allow_freeform?: boolean; +} +/** + * The answer to one command. `data` is present when `success` is true, `error` when it is not. + */ +export interface Response1 { + /** + * The `id` of the command; `null` for a line that was not a command. + */ + id?: { + [k: string]: unknown; + }; + success: boolean; + data?: { + [k: string]: unknown; + }; + error?: string | null; +} +/** + * The session as `get_state` and the session commands report it. + */ +export interface State { + session_id: string; + /** + * The session file. + */ + session_file?: string; + /** + * The session's name, once it has one. + */ + name?: string | null; + cwd: string; + /** + * The permission mode. + */ + mode: string; + /** + * Whether the lead is working. + */ + busy: boolean; + /** + * The lead's request number within the current prompt; 0 before the first. + */ + turn: number; + /** + * The model that answered most recently. + */ + model?: string | null; + /** + * The virtual model (`virtual/`) that picked `model` for that request, when the + * chain names one. + */ + via?: string | null; + /** + * The virtual models extensions define, as `virtual/`; `set_model` takes them. + */ + virtual_models?: string[]; + /** + * The lead's model chain as given, e.g. `["@default"]`. + */ + chain: string[]; + thinking: string; + /** + * The service tier, when one is on. + */ + tier?: string | null; + context_tokens: number; + context_window: number; + usage: Usage; + /** + * How many model requests the lead has made. + */ + requests?: number; + /** + * The roster. + */ + agents: Member[]; + /** + * The checked-out git branch of the project. + */ + branch?: string | null; + /** + * Whether coordinator mode is on. + */ + coordinator?: boolean; + /** + * The primary agent the lead is (`build`, `plan`, ...). + */ + agent?: string; + /** + * The primary agents `set_agent` takes, in the order a client steps through them. + */ + primary_agents?: PrimaryAgent[]; + /** + * The open goal, in a few words. + */ + goal?: string | null; + /** + * The lead's task list. + */ + todo?: Todo[]; + /** + * The model each role (`default`, `smol`, ...) resolves to first. + */ + roles?: { + [k: string]: string; + }; + /** + * Where the session's last run stopped, when the end of a process cut it short and + * `continue_run` can go on with it. + */ + interrupted?: string | null; +} +/** + * Totals of the lead. + */ +export interface Usage { + input?: number; + output?: number; + cache_read?: number; + cache_write?: number; + reasoning?: number; + /** + * Absent when no price is known for the model. + */ + cost_usd?: number | null; +} +/** + * A primary agent: a persona the lead can be. + */ +export interface PrimaryAgent { + name: string; + description: string; + /** + * `#rrggbb`, when the definition gives the agent a colour. + */ + color?: string | null; +} +/** + * One item of the lead's task list. + */ +export interface Todo { + text: string; + /** + * `pending`, `in_progress` or `done`. + */ + status: string; +} +/** + * Token and cost totals. + */ +export interface Usage1 { + input?: number; + output?: number; + cache_read?: number; + cache_write?: number; + reasoning?: number; + /** + * Absent when no price is known for the model. + */ + cost_usd?: number | null; +} +/** + * The data of `set_model`: the usable models the chain resolves to. + */ +export interface Models { + models: string[]; +} +/** + * One saved session. + */ +export interface SessionRow { + id: string; + /** + * The session file. + */ + path: string; + name?: string | null; + /** + * When it was created and when its last entry was written, RFC 3339. + */ + created: string; + updated: string; + /** + * The first message you sent. + */ + first_prompt?: string | null; + messages: number; + prompts: number; + pinned: boolean; + usage: Usage1; + /** + * With a `query`: the lines that matched. + */ + matches?: string[]; +} +/** + * One message of a branch. + */ +export interface MessageRow { + entry_id: string; + timestamp: string; + /** + * `role` (`user`, `assistant`, `tool`), `content` blocks and, for replies, `meta`. + */ + message: { + [k: string]: unknown; + }; +} +/** + * One entry of the session file. + */ +export interface TreeRow { + id: string; + parent_id?: string | null; + timestamp: string; + /** + * `message`, `checkpoint`, `model_change`, `compaction`, `label`, ... + */ + kind: string; + /** + * For a message: `user`, `assistant` or `tool`. + */ + role?: string | null; + /** + * For a message: the start of its text. For a `label` or a `session_info`: the label or + * the name. + */ + text?: string | null; + /** + * For a `label`: the entry it labels. For a `checkpoint`: the entry it was taken after. + */ + target_id?: string | null; + /** + * Whether the entry is on the branch that ends at the current leaf, or, for an entry of a + * run's journal (`run_started`, ...), hangs from that branch. + */ + current: boolean; +} +/** + * One model of `list_models`. + */ +export interface ModelRow { + /** + * `provider/id`. + */ + model: string; + provider: string; + id: string; + /** + * What the model is called in lists, when that is more than its id. + */ + name?: string | null; + context_window: number; + max_output: number; + vision: boolean; + reasoning: boolean; + /** + * The thinking levels the model takes; empty for every level when `reasoning` is set. + */ + thinking_levels?: string[]; + /** + * USD per million tokens. + */ + cost?: ModelCost | null; + /** + * Its provider has a credential, or needs none. + */ + usable: boolean; + /** + * Its provider is used through a subscription sign-in: it is not paid by the token. + */ + login?: boolean; +} +export interface ModelCost { + input: number; + output: number; +} +/** + * One provider of `list_providers`. + */ +export interface ProviderRow { + id: string; + name: string; + /** + * It has a credential, or needs none. + */ + usable: boolean; + /** + * The credential in use is a subscription sign-in. + */ + login: boolean; + /** + * Where the credential comes from (`OPENAI_API_KEY`, `auth.json (login)`), when there is one. + */ + source?: string | null; + /** + * The environment variables a key is read from. + */ + env?: string[]; + /** + * It can be signed in to with an account. + */ + oauth: boolean; + /** + * How many models it has: as it listed them this session, else as the catalogue knows them. + */ + models: number; +} +/** + * The data of `list_roles`, `set_role`, `save_preset` and `apply_preset`. + */ +export interface Roles { + roles: RoleRow[]; + /** + * The names of the saved presets. + */ + presets: string[]; + /** + * Whether `set_role` may write the project's config (the project is trusted). + */ + project: boolean; +} +/** + * One model role. + */ +export interface RoleRow { + role: string; + /** + * As configured, e.g. `["anthropic/claude-opus-5-5:high", "@slow"]`. + */ + chain: string[]; + source: RoleSource; + /** + * The built-in value the role falls back to when nothing sets it. + */ + builtin?: string[]; + /** + * The usable models the chain resolves to, in order, as `provider/id[:level]`. + */ + resolved: string[]; + /** + * The thinking level of the first model, when the chain names one with the model. + */ + thinking?: string | null; +} +/** + * The usage windows of one provider account. + */ +export interface AccountUsage { + provider: string; + account: string; + windows: Window[]; + /** + * Unix seconds until which the account is out of allowance for every model. + */ + blocked_until?: number | null; + /** + * Every block of the account, those for the models of one scope included. + */ + blocks?: UsageBlock[]; +} +/** + * One usage window of an account, as the provider last reported it. + */ +export interface Window { + /** + * `5h`, `7d`, `7d-fable`, `overage`. + */ + name: string; + /** + * The share that is used, 0.0 to 1.0. + */ + used: number; + /** + * Unix seconds. + */ + resets_at?: number | null; + /** + * `allowed`, `allowed_warning`, `rejected`, or whatever else the provider said. + */ + status: string; + /** + * What the window counts when that is not every request: a model family such as `Fable`. + */ + scope?: string | null; +} +/** + * An account that takes no requests until a time. + */ +export interface UsageBlock { + /** + * Unix seconds until which the account is left alone. + */ + until: number; + /** + * Unix seconds at which the provider last refused. + */ + since?: number; + /** + * The window that ran out, by name, when the provider named one. + */ + window?: string | null; + /** + * The models it holds for, as the scope of that window; absent for every model. + */ + scope?: string | null; +} +/** + * The data of `shell`. + */ +export interface ShellResult { + output: string; + /** + * `exit code: 0`, `killed`, or why the command could not start. + */ + status: string; +} +/** + * The data of `export`. + */ +export interface Exported { + path: string; +} +/** + * The data of `btw`. + */ +export interface BtwAnswer { + answer: string; + /** + * The model that answered. + */ + model: string; + /** + * Tools the model tried to use anyway; those calls were dropped. + */ + dropped_tools?: string[]; +} +/** + * The data of `attach`. + */ +export interface Attached { + /** + * The id of the background session, as `azazel ps` lists it. + */ + host: string; + /** + * The process that runs it. + */ + pid: number; + session_id: string; + /** + * The session file. + */ + session_file: string; + /** + * How many clients are attached, this one counted. + */ + clients?: number; + snapshot?: Snapshot; +} +/** + * Where the session stands at this moment. + */ +export interface Snapshot { + /** + * Whether the lead is working. + */ + busy?: boolean; + /** + * The last messages of the conversation, oldest first. + */ + tail?: MessageRow[]; + /** + * The replies being written, one per agent that is writing one. + */ + streaming?: Streaming[]; + /** + * The tool calls that are running. + */ + tools?: RunningTool[]; + /** + * What clients sent the lead that it has not taken up yet, oldest first. + */ + queue?: Queued[]; + /** + * The ids of the requests that wait for an answer; the requests follow as frames. + */ + pending?: string[]; +} +/** + * A reply in the making. + */ +export interface Streaming { + agent: string; + /** + * The text so far. + */ + text: string; + /** + * The thinking so far. + */ + thinking?: string; +} +/** + * A tool call that has started and not ended. + */ +export interface RunningTool { + agent: string; + call_id: string; + name: string; + input: unknown; + /** + * For how long it has run. + */ + elapsed_ms: number; +} +/** + * Input the lead has not taken up yet. `kind` is `prompt`, `steer` or `follow_up`. + */ +export interface Queued { + kind: string; + text: string; +} +/** + * A background session at the moment a client attaches: what a client needs to show the work + * in progress before the frames that follow. + */ +export interface Snapshot1 { + /** + * Whether the lead is working. + */ + busy?: boolean; + /** + * The last messages of the conversation, oldest first. + */ + tail?: MessageRow[]; + /** + * The replies being written, one per agent that is writing one. + */ + streaming?: Streaming[]; + /** + * The tool calls that are running. + */ + tools?: RunningTool[]; + /** + * What clients sent the lead that it has not taken up yet, oldest first. + */ + queue?: Queued[]; + /** + * The ids of the requests that wait for an answer; the requests follow as frames. + */ + pending?: string[]; +} +/** + * The data of a `prompt` that carries a `request_id`, and of `continue_run`: where a run + * stands. + */ +export interface RunState { + /** + * The `request_id` of the prompt that started the run, when it had one. + */ + request_id?: string | null; + /** + * The run as the session file names it; absent until the lead has taken the prompt up. + */ + run_id?: string | null; + /** + * `queued` (the lead has not taken it up yet), `running` or `ended`. + */ + state: string; + /** + * Whether this answers a prompt that had been sent before: nothing was started. + */ + duplicate?: boolean; + /** + * How an ended run ended: a stop reason of `idle`, or `failed`. + */ + stop?: string | null; + /** + * The last thing the lead said in the run. + */ + text?: string | null; +} +/** + * The data of `agent_mention`. + */ +export interface Mentioned { + /** + * The agent the text went to. + */ + agent: string; + /** + * Whether the agent was started for it. + */ + started: boolean; +} +/** + * The data of `get_session`: the session file's first line and its entries, as they are + * stored, and the entry the conversation continues from. + */ +export interface SessionCopy { + /** + * The session file. + */ + path: string; + header: unknown; + entries: unknown[]; + leaf?: string | null; +} +/** + * One command of `list_commands`. + */ +export interface CommandRow { + name: string; + description: string; +} diff --git a/web/src/lib/rpc/client.ts b/web/src/lib/rpc/client.ts new file mode 100644 index 00000000..f4238029 --- /dev/null +++ b/web/src/lib/rpc/client.ts @@ -0,0 +1,229 @@ +// The WebSocket side of the page. One client is one connection to one session: it keeps command ids +// and the table of commands waiting for their response, attaches with the position of the last frame +// it saw (`since`) and, when the socket drops, comes back with backoff. +import type { AnyFrame, AttachedRemote, Command } from '$lib/protocol'; + +export type Status = + | 'connecting' + | 'open' + | 'reconnecting' + | 'ended' // the session ended (1000) + | 'unauthorized' // 4401: pair again + | 'missing' // 4404: no such session + | 'closed'; // closed by the page + +export interface SocketLike { + onopen: ((ev?: unknown) => void) | null; + onmessage: ((ev: { data: unknown }) => void) | null; + onclose: ((ev: { code: number; reason?: string }) => void) | null; + onerror: ((ev?: unknown) => void) | null; + send(data: string): void; + close(code?: number, reason?: string): void; +} +export type SocketFactory = (url: string) => SocketLike; + +export interface Timers { + setTimeout(fn: () => void, ms: number): unknown; + clearTimeout(handle: unknown): void; +} + +export interface ClientOptions { + url: string; + /** `at` of the last frame the page has seen; asked again on every connect. */ + since: () => number | null; + onFrame: (frame: AnyFrame) => void; + /** Called after `attach` succeeded. `resync` is true when the page must rebuild from the snapshot. */ + onAttached: (attached: AttachedRemote, resync: boolean) => void; + onStatus: (status: Status, detail?: string) => void; + factory?: SocketFactory; + timers?: Timers; + /** Milliseconds before reconnect attempt `n` (0-based). */ + backoff?: (n: number) => number; + /** Reconnects after a 4408 do not wait. */ + random?: () => number; +} + +export class CommandError extends Error {} + +export function backoffMs(n: number, random: () => number = Math.random): number { + const base = Math.min(15_000, 500 * 2 ** n); + return Math.round(base * (0.75 + random() * 0.5)); +} + +const defaultFactory: SocketFactory = (url) => new WebSocket(url) as unknown as SocketLike; +const defaultTimers: Timers = { + setTimeout: (fn, ms) => setTimeout(fn, ms), + clearTimeout: (h) => clearTimeout(h as ReturnType) +}; + +interface Pending { + resolve: (data: unknown) => void; + reject: (err: Error) => void; +} + +export class RpcClient { + status: Status = 'connecting'; + private socket: SocketLike | null = null; + private nextId = 1; + private pending = new Map(); + private attempts = 0; + private timer: unknown = null; + private stopped = false; + private ready = false; + private readonly o: ClientOptions; + + constructor(options: ClientOptions) { + this.o = options; + } + + private get timers() { + return this.o.timers ?? defaultTimers; + } + + private set(status: Status, detail?: string) { + this.status = status; + this.o.onStatus(status, detail); + } + + connect() { + if (this.stopped) return; + this.clearTimer(); + this.ready = false; + this.set(this.attempts === 0 ? 'connecting' : 'reconnecting'); + const socket = (this.o.factory ?? defaultFactory)(this.o.url); + this.socket = socket; + socket.onmessage = (ev) => this.onMessage(socket, ev.data); + socket.onclose = (ev) => this.onClose(socket, ev.code, ev.reason); + socket.onerror = () => {}; + } + + /** Reconnect now if the connection is down (the page became visible again, or the network came back). */ + nudge() { + if (this.stopped || this.ready) return; + if (this.status === 'reconnecting' || this.status === 'connecting') { + if (this.timer !== null) this.connect(); + } + } + + /** Sends a command and resolves with the response's `data`. */ + send(command: Command): Promise { + const socket = this.socket; + if (!socket || !this.ready) return Promise.reject(new CommandError('Not connected')); + return new Promise((resolve, reject) => { + const id = this.nextId++; + this.pending.set(id, { resolve: resolve as (d: unknown) => void, reject }); + try { + socket.send(JSON.stringify({ ...command, id })); + } catch (e) { + this.pending.delete(id); + reject(new CommandError(String(e))); + } + }); + } + + /** Drops a socket that may be dead (a phone woke up) and connects again at once. */ + reset() { + if (this.stopped) return; + const s = this.socket; + this.socket = null; + this.ready = false; + this.failPending('Connection reset'); + s?.close(4000, 'reset'); + this.clearTimer(); + this.connect(); + } + + close() { + this.stopped = true; + this.clearTimer(); + this.failPending('Closed'); + const s = this.socket; + this.socket = null; + this.ready = false; + s?.close(1000, 'page closed'); + this.set('closed'); + } + + private clearTimer() { + if (this.timer !== null) this.timers.clearTimeout(this.timer); + this.timer = null; + } + + private failPending(why: string) { + for (const p of this.pending.values()) p.reject(new CommandError(why)); + this.pending.clear(); + } + + private rawSend(socket: SocketLike, command: object): number { + const id = this.nextId++; + socket.send(JSON.stringify({ ...command, id })); + return id; + } + + private onMessage(socket: SocketLike, data: unknown) { + if (socket !== this.socket || typeof data !== 'string') return; + let frame: AnyFrame & { id?: number; success?: boolean; error?: string; data?: unknown }; + try { + frame = JSON.parse(data); + } catch { + return; + } + if (frame.type === 'hello') { + this.attach(socket); + return; + } + if (frame.type === 'response') { + const p = typeof frame.id === 'number' ? this.pending.get(frame.id) : undefined; + if (!p) return; + this.pending.delete(frame.id as number); + if (frame.success) p.resolve(frame.data); + else p.reject(new CommandError(frame.error ?? 'The command failed')); + return; + } + this.o.onFrame(frame); + } + + private attach(socket: SocketLike) { + const since = this.o.since(); + const id = this.nextId++; + this.pending.set(id, { + resolve: (data) => { + if (socket !== this.socket) return; + const attached = data as AttachedRemote; + // A host that does not know `since` answers without a cursor: rebuild from the snapshot. + const resync = since === null || attached.gap === true || attached.cursor === undefined; + this.ready = true; + this.attempts = 0; + this.set('open'); + this.o.onAttached(attached, resync); + }, + reject: (err) => { + if (socket !== this.socket) return; + this.set('closed', err.message); + } + }); + // The snapshot gives the state at attach time, so nothing needs replaying; `since` closes the + // gap of a reconnect without it. + const cmd: Record = { type: 'attach', replay: 'none', id }; + if (since !== null) cmd.since = since; + socket.send(JSON.stringify(cmd)); + } + + private onClose(socket: SocketLike, code: number, reason?: string) { + if (socket !== this.socket) return; + this.socket = null; + this.ready = false; + this.failPending('Connection lost'); + if (this.stopped) return; + if (code === 4401) return this.set('unauthorized', reason); + if (code === 4404) return this.set('missing', reason); + if (code === 1000) return this.set('ended', reason); + if (code === 1003 || code === 1009) return this.set('closed', reason); + // 4408: the host closed us for being slow; resume at once. Anything else: back off. + const delay = + code === 4408 ? 0 : (this.o.backoff ?? ((n) => backoffMs(n, this.o.random)))(this.attempts); + this.attempts++; + this.set('reconnecting', reason); + this.timer = this.timers.setTimeout(() => this.connect(), delay); + } +} diff --git a/web/src/lib/session/reduce.ts b/web/src/lib/session/reduce.ts new file mode 100644 index 00000000..857a4ac1 --- /dev/null +++ b/web/src/lib/session/reduce.ts @@ -0,0 +1,601 @@ +// A pure reducer: protocol frames in, a model of the conversation out. Nothing here touches the +// DOM or the network, so it runs the same in the page, in the tests and over recorded logs. +import type { AnyFrame, Block, Member, Row, SnapshotRemote, State } from '$lib/protocol'; + +export type ToolStatus = 'pending' | 'running' | 'done' | 'error'; + +export interface UserItem { + kind: 'user'; + id: string; + agent: string; + text: string; + via: 'prompt' | 'steer' | 'follow_up'; + images: number; +} +export interface TextBlock { + index: number; + type: 'text' | 'thinking'; + text: string; +} +export interface AssistantItem { + kind: 'assistant'; + id: string; + agent: string; + blocks: TextBlock[]; + streaming: boolean; + model?: string; + tokens?: { input: number; output: number }; +} +export interface ToolItem { + kind: 'tool'; + id: string; + agent: string; + callId: string; + name: string; + input: unknown; + argsText: string; + status: ToolStatus; + live: string; + output: string; + diff?: string; + durationMs?: number; + imageCount: number; +} +export interface NoticeItem { + kind: 'notice'; + id: string; + agent: string; + level: 'info' | 'warn' | 'error'; + text: string; +} +export type Item = UserItem | AssistantItem | ToolItem | NoticeItem; + +/** A request that waits for an answer: an approval, or a question from `ask_user` and friends. */ +export type OpenRequest = + | { + kind: 'approval'; + id: string; + agent: string; + frame: Extract; + } + | { kind: 'ui'; id: string; agent: string; frame: Extract }; + +export interface Toast { + id: string; + level: 'info' | 'warn' | 'error'; + text: string; +} + +export interface AgentRun { + busy: boolean; + stop?: string; +} + +export interface Model { + seq: number; + items: Item[]; + /** Message item currently being written, per agent. */ + open: Record; + runs: Record; + roster: Member[]; + rosterAt: number; + requests: OpenRequest[]; + queue: { kind: string; text: string }[]; + toasts: Toast[]; + /** `at` of the last frame seen; what `attach` sends as `since` after a drop. */ + lastAt: number | null; + history: { earliest: string | null; more: boolean }; + state: State | null; + turn: number; +} + +export function emptyModel(): Model { + return { + seq: 0, + items: [], + open: {}, + runs: {}, + roster: [], + rosterAt: 0, + requests: [], + queue: [], + toasts: [], + lastAt: null, + history: { earliest: null, more: false }, + state: null, + turn: 0 + }; +} + +export function leadBusy(m: Model): boolean { + return m.runs['lead']?.busy ?? m.state?.busy ?? false; +} + +const textOf = (blocks: Block[] | undefined): string => + (blocks ?? []) + .filter((b): b is Extract => b.type === 'text') + .map((b) => b.text) + .join('\n'); + +function toolOutput(output: unknown): { + text: string; + images: number; + diff?: string; + isError: boolean; +} { + const o = (output ?? {}) as { + content?: Block[]; + is_error?: boolean; + details?: { diff?: unknown }; + }; + const diff = typeof o.details?.diff === 'string' ? o.details.diff : undefined; + return { + text: textOf(o.content), + images: (o.content ?? []).filter((b) => b.type === 'image').length, + diff, + isError: !!o.is_error + }; +} + +function next(m: Model, prefix: string): [Model, string] { + const seq = m.seq + 1; + return [{ ...m, seq }, `${prefix}${seq}`]; +} + +function patchItem(m: Model, id: string, fn: (i: T) => T): Model { + const at = m.items.findIndex((i) => i.id === id); + if (at < 0) return m; + const items = m.items.slice(); + items[at] = fn(items[at] as T); + return { ...m, items }; +} + +function findTool(m: Model, agent: string, callId: string): ToolItem | undefined { + for (let i = m.items.length - 1; i >= 0; i--) { + const it = m.items[i]; + if (it.kind === 'tool' && it.callId === callId && it.agent === agent) return it; + } + return undefined; +} + +function newTool(id: string, agent: string, callId: string, name: string): ToolItem { + return { + kind: 'tool', + id, + agent, + callId, + name, + input: undefined, + argsText: '', + status: 'pending', + live: '', + output: '', + imageCount: 0 + }; +} + +function upsertTool( + m: Model, + agent: string, + callId: string, + name: string, + fn: (t: ToolItem) => ToolItem +): Model { + const existing = findTool(m, agent, callId); + if (existing) return patchItem(m, existing.id, fn); + const [m2, id] = next(m, 't'); + return { ...m2, items: [...m2.items, fn(newTool(id, agent, callId, name))] }; +} + +function ensureOpen(m: Model, agent: string): [Model, string] { + const open = m.open[agent]; + if (open && m.items.some((i) => i.id === open)) return [m, open]; + const [m2, id] = next(m, 'a'); + const item: AssistantItem = { kind: 'assistant', id, agent, blocks: [], streaming: true }; + return [{ ...m2, items: [...m2.items, item], open: { ...m2.open, [agent]: id } }, id]; +} + +function setBlock( + item: AssistantItem, + index: number, + type: 'text' | 'thinking', + fn: (t: string) => string +): AssistantItem { + const blocks = item.blocks.slice(); + const at = blocks.findIndex((b) => b.index === index && b.type === type); + if (at >= 0) blocks[at] = { ...blocks[at], text: fn(blocks[at].text) }; + else blocks.push({ index, type, text: fn('') }); + return { ...item, blocks }; +} + +function stream(m: Model, agent: string, ev: Record): Model { + switch (ev.type) { + case 'text_delta': + case 'thinking_delta': { + const [m2, id] = ensureOpen(m, agent); + const type = ev.type === 'text_delta' ? 'text' : 'thinking'; + return patchItem(m2, id, (it) => + setBlock(it, ev.index as number, type, (t) => t + (ev.delta as string)) + ); + } + case 'tool_call_start': { + const [m2] = ensureOpen(m, agent); + return upsertTool(m2, agent, ev.id as string, ev.name as string, (t) => ({ + ...t, + name: ev.name as string + })); + } + case 'tool_call_delta': { + // The delta names no call, only an index; the call started last at that index is the one. + return m; + } + case 'block_end': { + const block = ev.block as Block; + if (block.type === 'tool_call') { + return upsertTool(m, agent, block.id, block.name, (t) => ({ + ...t, + name: block.name, + input: block.input + })); + } + if (block.type === 'text' || block.type === 'thinking') { + const [m2, id] = ensureOpen(m, agent); + return patchItem(m2, id, (it) => + setBlock(it, ev.index as number, block.type as 'text' | 'thinking', () => block.text) + ); + } + return m; + } + default: + return m; + } +} + +function messageEnd( + m: Model, + agent: string, + message: { + content?: Block[]; + meta?: { model?: string; usage?: { input: number; output: number } }; + } +): Model { + const open = m.open[agent]; + const content = message.content ?? []; + const blocks: TextBlock[] = content.flatMap((b, index): TextBlock[] => + (b.type === 'text' || b.type === 'thinking') && b.text.trim() + ? [{ index, type: b.type, text: b.text }] + : [] + ); + let out: Model = m; + if (open) { + out = blocks.length + ? patchItem(m, open, (it) => ({ + ...it, + blocks, + streaming: false, + model: message.meta?.model, + tokens: message.meta?.usage + ? { input: message.meta.usage.input, output: message.meta.usage.output } + : undefined + })) + : { ...m, items: m.items.filter((i) => i.id !== open) }; + } else if (blocks.length) { + const [m2, id] = next(m, 'a'); + out = { + ...m2, + items: [ + ...m2.items, + { kind: 'assistant', id, agent, blocks, streaming: false, model: message.meta?.model } + ] + }; + } + for (const b of content) { + if (b.type === 'tool_call') { + out = upsertTool(out, agent, b.id, b.name, (t) => ({ ...t, name: b.name, input: b.input })); + } + } + const rest = { ...out.open }; + delete rest[agent]; + return { ...out, open: rest }; +} + +function addNotice(m: Model, agent: string, level: NoticeItem['level'], text: string): Model { + const [m2, id] = next(m, 'n'); + return { ...m2, items: [...m2.items, { kind: 'notice', id, agent, level, text }] }; +} + +function closeStreaming(m: Model, agent: string): Model { + const open = m.open[agent]; + if (!open) return m; + const rest = { ...m.open }; + delete rest[agent]; + return patchItem({ ...m, open: rest }, open, (it) => ({ + ...it, + streaming: false + })); +} + +function setRun(m: Model, agent: string, run: AgentRun): Model { + return { ...m, runs: { ...m.runs, [agent]: run } }; +} + +/** Applies one frame. Unknown frame types change nothing. */ +export function reduce(m: Model, frame: AnyFrame): Model { + const at = typeof frame.at === 'number' ? frame.at : null; + const base: Model = + at !== null && (m.lastAt === null || at > m.lastAt) ? { ...m, lastAt: at } : m; + const f = frame as Record & { type: string }; + const agent = (f.agent as string | undefined) ?? 'lead'; + switch (f.type) { + case 'agent_start': + return setRun(base, agent, { busy: true }); + case 'turn_start': + return agent === 'lead' ? { ...base, turn: f.turn as number } : base; + case 'message_start': { + const [m2, id] = next(base, 'a'); + const item: AssistantItem = { kind: 'assistant', id, agent, blocks: [], streaming: true }; + return { ...m2, items: [...m2.items, item], open: { ...m2.open, [agent]: id } }; + } + case 'stream': + return stream(base, agent, f.event as Record); + case 'message_end': + return messageEnd(base, agent, f.message as Parameters[2]); + case 'tool_start': + return upsertTool(base, agent, f.call_id as string, f.name as string, (t) => ({ + ...t, + name: f.name as string, + input: f.input, + status: 'running' + })); + case 'tool_update': + return upsertTool(base, agent, f.call_id as string, '', (t) => ({ + ...t, + status: t.status === 'pending' ? 'running' : t.status, + live: t.live ? `${t.live}\n${f.text as string}` : (f.text as string) + })); + case 'tool_end': { + const o = toolOutput(f.output); + return upsertTool(base, agent, f.call_id as string, '', (t) => ({ + ...t, + status: o.isError ? 'error' : 'done', + output: o.text, + diff: o.diff ?? t.diff, + imageCount: o.images, + durationMs: f.duration_ms as number + })); + } + case 'idle': + return setRun(closeStreaming(base, agent), agent, { busy: false, stop: f.stop as string }); + case 'failed': + return addNotice( + setRun(closeStreaming(base, agent), agent, { busy: false, stop: 'error' }), + agent, + 'error', + f.error as string + ); + case 'retry': + return addNotice( + base, + agent, + 'warn', + `Retrying ${f.model as string} (attempt ${f.attempt as number})` + ); + case 'fallback': + return addNotice( + base, + agent, + 'warn', + `Model fell back from ${f.from as string} to ${f.to as string}` + ); + case 'account': + return addNotice( + base, + agent, + 'warn', + `${f.provider as string} account switched: ${f.limit as string}` + ); + case 'tier_dropped': + return addNotice( + base, + agent, + 'info', + `${f.model as string} does not take the ${f.tier as string} tier` + ); + case 'rule': + return addNotice( + base, + agent, + 'info', + `Stream rule “${f.name as string}” matched; asking again` + ); + case 'compaction': + return addNotice( + base, + agent, + 'info', + `Context compacted: ${f.tokens_before as number} → ${f.tokens_after as number} tokens` + ); + case 'roster': + return { ...base, roster: f.members as Member[], rosterAt: Date.now() }; + case 'approval_request': { + const frame = frame0(f) as Extract; + const id = frame.request_id; + if (base.requests.some((r) => r.id === id)) return base; + return { + ...base, + requests: [...base.requests, { kind: 'approval', id, agent: frame.agent, frame }] + }; + } + case 'ui_request': { + const frame = frame0(f) as Extract; + if ((frame as { kind: string }).kind === 'notify') { + const n = frame as unknown as { request_id: string; level: string; text: string }; + const level = n.level === 'warn' || n.level === 'error' ? n.level : 'info'; + return { ...base, toasts: [...base.toasts, { id: n.request_id, level, text: n.text }] }; + } + if (base.requests.some((r) => r.id === frame.request_id)) return base; + return { + ...base, + requests: [...base.requests, { kind: 'ui', id: frame.request_id, agent: 'lead', frame }] + }; + } + case 'request_closed': + return { ...base, requests: base.requests.filter((r) => r.id !== f.request_id) }; + case 'user_input': { + const [m2, id] = next(base, 'u'); + const via = (['prompt', 'steer', 'follow_up'] as const).find((v) => v === f.kind) ?? 'prompt'; + const agentId = (f.agent as string | null | undefined) ?? 'lead'; + return { + ...m2, + items: [ + ...m2.items, + { kind: 'user', id, agent: agentId, text: f.text as string, via, images: 0 } + ], + queue: m2.queue.filter((q) => q.text !== f.text) + }; + } + default: + return base; + } +} + +const frame0 = (f: unknown) => f as AnyFrame; + +/** What the page itself sent: the host does not echo a client's own input back to it. */ +export function addLocalUser( + m: Model, + text: string, + via: UserItem['via'], + images: number, + agent = 'lead' +): Model { + const [m2, id] = next(m, 'u'); + return { ...m2, items: [...m2.items, { kind: 'user', id, agent, text, via, images }] }; +} + +export function takeToasts(m: Model): [Model, Toast[]] { + return m.toasts.length ? [{ ...m, toasts: [] }, m.toasts] : [m, []]; +} + +/** Turns stored messages (`get_messages`, the snapshot tail) into items. */ +export function rowsToItems(rows: Row[], agent = 'lead', prefix = 'h'): Item[] { + const items: Item[] = []; + const tools = new Map(); + for (const row of rows) { + const msg = row.message; + if (!msg) continue; + const id = `${prefix}${row.entry_id}`; + if (msg.role === 'user') { + const text = textOf(msg.content); + const images = msg.content.filter((b) => b.type === 'image').length; + if (text || images) items.push({ kind: 'user', id, agent, text, via: 'prompt', images }); + } else if (msg.role === 'assistant') { + const blocks: TextBlock[] = msg.content.flatMap((b, index): TextBlock[] => + (b.type === 'text' || b.type === 'thinking') && b.text.trim() + ? [{ index, type: b.type, text: b.text }] + : [] + ); + if (blocks.length) { + items.push({ + kind: 'assistant', + id, + agent, + blocks, + streaming: false, + model: msg.meta?.model, + tokens: msg.meta?.usage + ? { input: msg.meta.usage.input, output: msg.meta.usage.output } + : undefined + }); + } + for (const b of msg.content) { + if (b.type !== 'tool_call') continue; + const t: ToolItem = { + ...newTool(`${id}:${b.id}`, agent, b.id, b.name), + input: b.input, + status: 'running' + }; + tools.set(b.id, t); + items.push(t); + } + } else if (msg.role === 'tool') { + for (const b of msg.content) { + if (b.type !== 'tool_result') continue; + const t = tools.get(b.call_id); + if (!t) continue; + t.output = textOf(b.content); + t.imageCount = b.content.filter((c) => c.type === 'image').length; + t.status = b.is_error ? 'error' : 'done'; + } + } + } + return items; +} + +/** A history tool call whose result never came is not running: the session moved on. */ +function settle(items: Item[], stillRunning: Set): Item[] { + return items.map((i) => + i.kind === 'tool' && i.status === 'running' && !stillRunning.has(i.callId) + ? { ...i, status: 'done' } + : i + ); +} + +/** Rebuilds the model from what `attach` reports: the tail, the replies being written, the tools running. */ +export function applySnapshot(m: Model, snap: SnapshotRemote | undefined, tailLimit = 20): Model { + const tail = ((snap?.tail ?? []) as unknown as Row[]) ?? []; + const running = new Set((snap?.tools ?? []).map((t) => t.call_id)); + let items = settle(rowsToItems(tail), running); + let seq = m.seq; + const open: Record = {}; + for (const s of snap?.streaming ?? []) { + seq++; + const id = `a${seq}`; + const blocks: TextBlock[] = []; + if (s.thinking) blocks.push({ index: 0, type: 'thinking', text: s.thinking }); + if (s.text) blocks.push({ index: 1, type: 'text', text: s.text }); + items.push({ kind: 'assistant', id, agent: s.agent, blocks, streaming: true }); + open[s.agent] = id; + } + for (const t of snap?.tools ?? []) { + seq++; + items.push({ + ...newTool(`t${seq}`, t.agent, t.call_id, t.name), + input: t.input, + status: 'running', + durationMs: t.elapsed_ms + }); + } + items = items.slice(); + return { + ...m, + seq, + items, + open, + runs: { ...m.runs, lead: { busy: !!snap?.busy } }, + queue: (snap?.queue ?? []).map((q) => ({ kind: q.kind, text: q.text })), + requests: [], + history: { earliest: tail[0]?.entry_id ?? null, more: tail.length >= tailLimit } + }; +} + +/** Puts older rows in front of the transcript. */ +export function prependRows(m: Model, rows: Row[], limit: number): Model { + if (!rows.length) return { ...m, history: { ...m.history, more: false } }; + const older = rowsToItems(rows, 'lead', 'p'); + return { + ...m, + items: [...settle(older, new Set()), ...m.items], + history: { earliest: rows[0].entry_id, more: rows.length >= limit } + }; +} + +export function withState(m: Model, state: State): Model { + const runs = { ...m.runs, lead: { ...(m.runs['lead'] ?? {}), busy: state.busy } }; + // `get_state` carries the roster too; frames sent before attach are not replayed, so it seeds the hub. + return { ...m, state, runs, roster: state.agents?.length ? state.agents : m.roster }; +} + +export function itemsFor(m: Model, agent: string): Item[] { + return m.items.filter((i) => i.agent === agent); +} diff --git a/web/src/lib/session/session.svelte.ts b/web/src/lib/session/session.svelte.ts new file mode 100644 index 00000000..9520addf --- /dev/null +++ b/web/src/lib/session/session.svelte.ts @@ -0,0 +1,282 @@ +// Runes state around the reducer: one Session is one WebSocket to one azazel session. +import { RpcClient, type SocketFactory, type Status, type Timers } from '$lib/rpc/client'; +import { wsUrl } from '$lib/api'; +import type { + AccountUsage, + AnyFrame, + AttachedRemote, + Command, + CommandRow, + Decision, + Image, + ModelRow, + Roles, + Row, + State +} from '$lib/protocol'; +import { + addLocalUser, + applySnapshot, + emptyModel, + leadBusy, + prependRows, + reduce, + takeToasts, + withState, + type Model, + type Toast +} from './reduce'; + +const PAGE = 20; + +export interface SessionOptions { + id: string; + url?: string; + factory?: SocketFactory; + timers?: Timers; + onToast?: (t: Toast) => void; + /** Apply frames at once instead of once per tick (tests). */ + sync?: boolean; +} + +export class Session { + // Frames are applied to an immutable model; $state.raw keeps Svelte from proxying it deeply. + model = $state.raw(emptyModel()); + status = $state('connecting'); + statusDetail = $state(undefined); + attached = $state.raw(null); + models = $state.raw([]); + usage = $state.raw([]); + roles = $state.raw(null); + commands = $state.raw([]); + files = $state.raw(null); + loadingEarlier = $state(false); + + readonly id: string; + private client: RpcClient; + private queue: AnyFrame[] = []; + private tick: ReturnType | null = null; + private stateTimer: ReturnType | null = null; + private readonly o: SessionOptions; + + constructor(o: SessionOptions) { + this.o = o; + this.id = o.id; + this.client = new RpcClient({ + url: o.url ?? wsUrl(o.id), + since: () => this.model.lastAt, + factory: o.factory, + timers: o.timers, + onFrame: (f) => this.push(f), + onStatus: (s, d) => { + this.status = s; + this.statusDetail = d; + }, + onAttached: (a, resync) => void this.onAttached(a, resync) + }); + } + + get busy() { + return leadBusy(this.model); + } + get state(): State | null { + return this.model.state; + } + + start() { + this.client.connect(); + } + stop() { + if (this.tick) clearTimeout(this.tick); + if (this.stateTimer) clearTimeout(this.stateTimer); + this.client.close(); + } + nudge() { + this.client.nudge(); + } + /** The page became visible: a phone may have suspended the socket. Check it, or replace it. */ + async resume() { + if (this.status !== 'open') return this.client.nudge(); + const alive = await Promise.race([ + this.refreshState().then( + () => true, + () => false + ), + new Promise((r) => setTimeout(() => r(false), 4000)) + ]); + if (!alive) this.client.reset(); + } + + /** Applies every queued frame now. */ + flush() { + if (this.tick) clearTimeout(this.tick); + this.tick = null; + if (!this.queue.length) return; + let m = this.model; + let sawEnd = false; + for (const f of this.queue) { + m = reduce(m, f); + if (f.type === 'idle' || f.type === 'failed' || f.type === 'compaction') sawEnd = true; + } + this.queue = []; + const [m2, toasts] = takeToasts(m); + this.model = m2; + for (const t of toasts) this.o.onToast?.(t); + if (sawEnd) this.refreshStateSoon(); + } + + private push(f: AnyFrame) { + this.queue.push(f); + if (this.o.sync) return this.flush(); + this.tick ??= setTimeout(() => this.flush(), 33); + } + + private async onAttached(a: AttachedRemote, resync: boolean) { + this.attached = a; + // A reconnect that resumes from `since` keeps the transcript; anything else rebuilds it. + if (resync) + this.model = applySnapshot( + { ...this.model, lastAt: a.cursor ? a.cursor : this.model.lastAt }, + a.snapshot, + PAGE + ); + await Promise.allSettled([this.refreshState(), this.refreshModels(), this.refreshUsage()]); + } + + // --- queries --------------------------------------------------------------------------- + + async refreshState() { + const state = await this.client.send({ type: 'get_state' }); + this.model = withState(this.model, state); + } + private refreshStateSoon() { + if (this.stateTimer) return; + this.stateTimer = setTimeout(() => { + this.stateTimer = null; + void this.refreshState().catch(() => {}); + }, 400); + } + async refreshModels() { + if (this.models.length) return; + this.models = await this.client.send({ type: 'list_models' }); + } + async refreshUsage() { + this.usage = await this.client.send({ type: 'get_usage' }); + } + async refreshRoles() { + this.roles = await this.client.send({ type: 'list_roles' }); + } + async loadCommands() { + if (!this.commands.length) + this.commands = await this.client.send({ type: 'list_commands' }); + } + async loadFiles() { + if (this.files) return; + this.files = await this.client.send({ type: 'list_files' }); + } + + async loadEarlier() { + const h = this.model.history; + if (this.loadingEarlier || !h.more || !h.earliest) return; + this.loadingEarlier = true; + try { + const rows = await this.client.send({ + type: 'get_messages', + before: h.earliest, + limit: PAGE + } as unknown as Command); + this.model = prependRows(this.model, rows, PAGE); + } finally { + this.loadingEarlier = false; + } + } + + async agentHistory(agent: string): Promise { + return this.client.send({ + type: 'get_agent_messages', + agent, + limit: 40 + } as unknown as Command); + } + + // --- commands -------------------------------------------------------------------------- + + send(c: Command) { + return this.client.send(c); + } + + async prompt(text: string, images: Image[] = []) { + const via = this.busy ? 'steer' : 'prompt'; + await this.client.send( + this.busy ? { type: 'steer', text, images } : { type: 'prompt', text, images } + ); + this.model = addLocalUser( + { ...this.model, runs: { ...this.model.runs, lead: { busy: true } } }, + text, + via, + images.length + ); + } + async followUp(text: string) { + await this.client.send({ type: 'follow_up', text }); + this.model = addLocalUser(this.model, text, 'follow_up', 0); + } + /** `@name text`. False when `name` is neither an agent nor a definition: the caller sends a prompt. */ + async mention(name: string, text: string): Promise { + const r = await this.client.send<{ agent: string } | null>({ + type: 'agent_mention', + name, + text + }); + if (r === null) return false; + this.model = addLocalUser(this.model, `@${name} ${text}`, 'prompt', 0); + return true; + } + abort() { + return this.client.send({ type: 'abort' }); + } + + async approve(requestId: string, decision: Decision, feedback?: string) { + await this.client.send({ + type: 'approval_response', + request_id: requestId, + decision, + feedback + }); + this.closeRequest(requestId); + } + async answer(requestId: string, value: unknown) { + await this.client.send({ + type: 'ui_response', + request_id: requestId, + value + } as unknown as Command); + this.closeRequest(requestId); + } + private closeRequest(id: string) { + this.model = { ...this.model, requests: this.model.requests.filter((r) => r.id !== id) }; + } + + async setModel(model: string) { + await this.client.send({ type: 'set_model', chain: [model] }); + await this.refreshState(); + } + async setMode(mode: string) { + await this.client.send({ type: 'set_mode', mode }); + await this.refreshState(); + } + async setThinking(level: string) { + await this.client.send({ type: 'set_thinking', level }); + await this.refreshState(); + } + async setAgent(agent: string) { + await this.client.send({ type: 'set_agent', agent }); + await this.refreshState(); + } + agentSend(to: string, message: string) { + return this.client.send({ type: 'agent_send', to, message }); + } + agentStop(agent: string) { + return this.client.send({ type: 'agent_stop', agent }); + } +} diff --git a/web/src/lib/sessions.svelte.ts b/web/src/lib/sessions.svelte.ts new file mode 100644 index 00000000..d85bd8ce --- /dev/null +++ b/web/src/lib/sessions.svelte.ts @@ -0,0 +1,44 @@ +import { api } from '$lib/api'; +import type { SessionInfo } from '$lib/protocol'; + +class Sessions { + list = $state.raw([]); + loaded = $state(false); + error = $state(null); + private timer: ReturnType | null = null; + private users = 0; + + async refresh() { + try { + this.list = await api.sessions(); + this.error = null; + } catch (e) { + this.error = e instanceof Error ? e.message : String(e); + } finally { + this.loaded = true; + } + } + /** Polls while at least one component wants the list and the page is visible. */ + watch() { + this.users++; + void this.refresh(); + this.timer ??= setInterval(() => { + if (document.visibilityState === 'visible') void this.refresh(); + }, 5000); + return () => { + if (--this.users === 0 && this.timer) { + clearInterval(this.timer); + this.timer = null; + } + }; + } +} +export const sessions = new Sessions(); + +/** The states the list shows, in the words of the page. */ +export const STATE_LABEL: Record = { + working: 'Working', + 'waiting for you': 'Needs you', + idle: 'Idle', + interrupted: 'Interrupted' +}; diff --git a/web/src/lib/toasts.svelte.ts b/web/src/lib/toasts.svelte.ts new file mode 100644 index 00000000..dacdbdaa --- /dev/null +++ b/web/src/lib/toasts.svelte.ts @@ -0,0 +1,18 @@ +export interface ToastItem { + id: number; + level: 'info' | 'warn' | 'error' | 'success'; + text: string; +} +class Toasts { + items = $state([]); + private n = 0; + push(text: string, level: ToastItem['level'] = 'info', ms = 5000) { + const id = ++this.n; + this.items = [...this.items.slice(-3), { id, level, text }]; + setTimeout(() => this.dismiss(id), level === 'error' ? ms * 2 : ms); + } + dismiss(id: number) { + this.items = this.items.filter((t) => t.id !== id); + } +} +export const toasts = new Toasts(); diff --git a/web/src/lib/tools.ts b/web/src/lib/tools.ts new file mode 100644 index 00000000..7affb9c0 --- /dev/null +++ b/web/src/lib/tools.ts @@ -0,0 +1,79 @@ +// Display helpers for tool calls: a one-line summary, an icon name, and a diff for edits. +const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined); + +export function summarize(name: string, input: unknown): string { + const i = (input ?? {}) as Record; + switch (name) { + case 'read': + case 'write': + case 'edit': + case 'ls': + return str(i.path) ?? ''; + case 'shell': + return str(i.command)?.split('\n')[0] ?? ''; + case 'grep': + case 'glob': + return [str(i.pattern), str(i.path)].filter(Boolean).join(' in '); + case 'task': { + const a = Array.isArray(i.agents) ? i.agents.length : 0; + return a ? `${a} agent${a > 1 ? 's' : ''}` : ''; + } + case 'web_fetch': + return str(i.url) ?? ''; + case 'web_search': + return str(i.query) ?? ''; + default: { + for (const v of Object.values(i)) if (typeof v === 'string' && v) return v.split('\n')[0]; + return ''; + } + } +} + +/** A unified-diff-shaped preview of what a `write` or `edit` is about to do. */ +export function previewDiff(name: string, input: unknown): string | undefined { + const i = (input ?? {}) as Record; + if (name === 'write' && typeof i.content === 'string') { + const lines = i.content.replace(/\n$/, '').split('\n'); + return [ + `--- /dev/null`, + `+++ b/${String(i.path ?? '')}`, + `@@ -0,0 +1,${lines.length} @@`, + ...lines.map((l) => `+${l}`) + ].join('\n'); + } + if (name === 'edit' && Array.isArray(i.edits)) { + const out = [`--- a/${String(i.path ?? '')}`, `+++ b/${String(i.path ?? '')}`]; + for (const e of i.edits as { old?: string; new?: string }[]) { + out.push('@@ @@'); + for (const l of String(e.old ?? '') + .replace(/\n$/, '') + .split('\n')) + out.push(`-${l}`); + for (const l of String(e.new ?? '') + .replace(/\n$/, '') + .split('\n')) + out.push(`+${l}`); + } + return out.join('\n'); + } + return undefined; +} + +export function prettyInput(input: unknown, max = 1600): string { + const s = typeof input === 'string' ? input : JSON.stringify(input, null, 2); + return s.length > max ? `${s.slice(0, max)}\n… ${s.length - max} more characters` : s; +} + +export type DiffLine = { kind: 'add' | 'del' | 'ctx' | 'hunk' | 'meta'; text: string }; +export function parseDiff(diff: string): DiffLine[] { + return diff + .replace(/\n$/, '') + .split('\n') + .map((text): DiffLine => { + if (text.startsWith('+++') || text.startsWith('---')) return { kind: 'meta', text }; + if (text.startsWith('@@')) return { kind: 'hunk', text }; + if (text.startsWith('+')) return { kind: 'add', text: text.slice(1) }; + if (text.startsWith('-')) return { kind: 'del', text: text.slice(1) }; + return { kind: 'ctx', text: text.startsWith(' ') ? text.slice(1) : text }; + }); +} diff --git a/web/src/lib/utils.ts b/web/src/lib/utils.ts new file mode 100644 index 00000000..8fe05d12 --- /dev/null +++ b/web/src/lib/utils.ts @@ -0,0 +1,14 @@ +import { clsx, type ClassValue } from 'clsx'; +import { twMerge } from 'tailwind-merge'; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} + +// Types the shadcn-svelte components import. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type WithoutChild = T extends { child?: any } ? Omit : T; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type WithoutChildren = T extends { children?: any } ? Omit : T; +export type WithoutChildrenOrChild = WithoutChildren>; +export type WithElementRef = T & { ref?: U | null }; diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte new file mode 100644 index 00000000..f4d5a7da --- /dev/null +++ b/web/src/routes/+layout.svelte @@ -0,0 +1,127 @@ + + +azazel + +{#if app.auth === 'ok'} +
+ +
{@render children()}
+
+{:else if app.auth === 'checking' || app.auth === 'pairing'} +
+
+ +

+ {app.auth === 'pairing' ? 'Pairing this device…' : 'Connecting…'} +

+
+
+{:else} +
+
+ + {#if app.auth === 'needs-link'} +
+

+ {app.error ? 'That link did not work' : 'This device is not paired'} +

+

+ {app.error ?? 'Open the pairing link or scan the QR code that azazel printed.'} +

+
+
+

On the machine that runs azazel:

+ azazel remote +

+ Press l there for a new + control link. A link works once and expires after a few minutes. +

+
+ {:else} +
+

Cannot reach azazel

+ +
+ + {/if} +
+
+{/if} + +
+ {#each toasts.items as t (t.id)} +
+ {t.text} + +
+ {/each} +
diff --git a/web/src/routes/+layout.ts b/web/src/routes/+layout.ts new file mode 100644 index 00000000..83addb7e --- /dev/null +++ b/web/src/routes/+layout.ts @@ -0,0 +1,2 @@ +export const ssr = false; +export const prerender = false; diff --git a/web/src/routes/+page.svelte b/web/src/routes/+page.svelte new file mode 100644 index 00000000..24660eeb --- /dev/null +++ b/web/src/routes/+page.svelte @@ -0,0 +1,60 @@ + + + +
+
+ +
+ + + +
+
+
+

Sessions on this machine

+ +
+
+ + + + (pairing = false)} /> diff --git a/web/src/routes/s/[id]/+layout.svelte b/web/src/routes/s/[id]/+layout.svelte new file mode 100644 index 00000000..56067ce3 --- /dev/null +++ b/web/src/routes/s/[id]/+layout.svelte @@ -0,0 +1,193 @@ + + +{waiting ? '(!) ' : ''}{title} · azazel + +
+
+
+
+ { + if (viewport.wide) { + e.preventDefault(); + menu = true; + } + }}> +
+

+ + {title} + {#if agentId}/ {agentId}{/if} +

+

+ {session.state?.cwd ?? info?.cwd ?? ''}{session.state?.branch + ? ` · ${session.state.branch}` + : ''} +

+
+ +
+
+
+ + {#if session.status === 'reconnecting' || session.status === 'connecting'} +
+ + {session.status === 'connecting' ? 'Connecting…' : 'Connection lost. Reconnecting…'} +
+ {:else if session.status === 'ended'} +
+ This session has ended. Back to the list +
+ {:else if session.status === 'missing'} + + {:else if session.status === 'unauthorized'} + + {/if} + + {@render children()} +
+ + +
+ + (panel = null)} +> +
+ {#each ['agents', 'usage'] as t (t)} + + {/each} +
+ {#if panel === 'usage'}{:else}{/if} +
+ + (menu = false)}> + (menu = false)} /> + diff --git a/web/src/routes/s/[id]/+page.svelte b/web/src/routes/s/[id]/+page.svelte new file mode 100644 index 00000000..3343e66c --- /dev/null +++ b/web/src/routes/s/[id]/+page.svelte @@ -0,0 +1,45 @@ + + + session.loadEarlier().catch(() => {})} +/> + +{#if request} + {#key request.id} + {#if request.kind === 'approval'} + session.approve(request.id, d, fb)} + /> + {:else} + session.answer(request.id, v)} + /> + {/if} + {/key} + {#if more > 0}

+ {more} more request{more > 1 ? 's' : ''} waiting +

{/if} +{/if} + + diff --git a/web/src/routes/s/[id]/agents/[agent]/+page.svelte b/web/src/routes/s/[id]/agents/[agent]/+page.svelte new file mode 100644 index 00000000..4ede15e4 --- /dev/null +++ b/web/src/routes/s/[id]/agents/[agent]/+page.svelte @@ -0,0 +1,103 @@ + + +
+ Lead +
+
+ {agent}{member?.state ?? 'gone'} +
+ {#if member?.activity}

+ {member.activity} +

{/if} +
+
+ + + +{#if app.canControl} +
(e.preventDefault(), send())} + > +
+ + +
+ +{/if} diff --git a/web/static/favicon.svg b/web/static/favicon.svg new file mode 100644 index 00000000..3e2b1f94 --- /dev/null +++ b/web/static/favicon.svg @@ -0,0 +1 @@ + diff --git a/web/svelte.config.js b/web/svelte.config.js new file mode 100644 index 00000000..d98d8a6d --- /dev/null +++ b/web/svelte.config.js @@ -0,0 +1,12 @@ +import adapter from '@sveltejs/adapter-static'; +import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; + +/** @type {import('@sveltejs/kit').Config} */ +export default { + preprocess: vitePreprocess(), + kit: { + adapter: adapter({ pages: 'build', assets: 'build', fallback: 'index.html', strict: false }), + // The page is served from the server's root for every route, so asset URLs must be absolute. + paths: { relative: false } + } +}; diff --git a/web/tests/unit/answers.test.ts b/web/tests/unit/answers.test.ts new file mode 100644 index 00000000..1c067190 --- /dev/null +++ b/web/tests/unit/answers.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'vitest'; +import { answerOf, emptyDraft } from '$lib/answers'; +import { pairSecret, wsUrl } from '$lib/api'; +import { fit } from '$lib/images'; + +describe('ui_response values', () => { + it('starts on the recommended option and sends what each kind expects', () => { + const sel = { + expects: 'select' as const, + options: ['sqlite', 'postgres'], + recommended: 'postgres', + allow_freeform: false + }; + expect(answerOf(sel, emptyDraft(sel))).toEqual(['postgres']); + const conf = { expects: 'confirm' as const, options: [], recommended: 'yes' }; + expect(answerOf(conf, emptyDraft(conf))).toBe(true); + const text = { expects: 'text' as const, options: [] }; + expect(answerOf(text, emptyDraft(text))).toBeNull(); + expect(answerOf(text, { ...emptyDraft(text), text: ' hi ' })).toBe(' hi '); + }); + + it('lets a typed answer replace a single choice or join a multiselect', () => { + const one = { expects: 'select' as const, options: ['a', 'b'], allow_freeform: true }; + expect(answerOf(one, { chosen: ['a'], text: 'mine', confirm: null })).toEqual(['mine']); + const many = { expects: 'multiselect' as const, options: ['a', 'b'], allow_freeform: true }; + expect(answerOf(many, { chosen: ['a', 'b'], text: 'c', confirm: null })).toEqual([ + 'a', + 'b', + 'c' + ]); + }); +}); + +describe('pairing and urls', () => { + it('reads only a well-formed secret from the fragment', () => { + expect(pairSecret('#pair=abc_DEF-123')).toBe('abc_DEF-123'); + expect(pairSecret('#pair=')).toBeNull(); + expect(pairSecret('#pair=a b')).toBeNull(); + expect(pairSecret('#other')).toBeNull(); + }); + it('picks wss on https', () => { + expect(wsUrl('a b', { protocol: 'https:', host: 'h.ts.net' })).toBe( + 'wss://h.ts.net/api/ws/a%20b' + ); + expect(wsUrl('x', { protocol: 'http:', host: '127.0.0.1:7420' })).toBe( + 'ws://127.0.0.1:7420/api/ws/x' + ); + }); + it('fits images inside 2048 without upscaling', () => { + expect(fit(4096, 2048)).toEqual({ w: 2048, h: 1024 }); + expect(fit(800, 600)).toEqual({ w: 800, h: 600 }); + }); +}); diff --git a/web/tests/unit/client.test.ts b/web/tests/unit/client.test.ts new file mode 100644 index 00000000..67886142 --- /dev/null +++ b/web/tests/unit/client.test.ts @@ -0,0 +1,172 @@ +import { describe, expect, it } from 'vitest'; +import { backoffMs, RpcClient, type SocketLike, type Status, type Timers } from '$lib/rpc/client'; +import type { AnyFrame } from '$lib/protocol'; + +class FakeSocket implements SocketLike { + onopen = null; + onmessage: SocketLike['onmessage'] = null; + onclose: SocketLike['onclose'] = null; + onerror = null; + sent: Record[] = []; + closed = false; + send(d: string) { + this.sent.push(JSON.parse(d)); + } + close() { + this.closed = true; + } + recv(o: object) { + this.onmessage?.({ data: JSON.stringify(o) }); + } + drop(code = 1006) { + this.onclose?.({ code }); + } +} + +function harness(since: () => number | null = () => null) { + const sockets: FakeSocket[] = []; + const timeouts: { fn: () => void; ms: number }[] = []; + const timers: Timers = { + setTimeout: (fn, ms) => (timeouts.push({ fn, ms }), timeouts.length), + clearTimeout: () => {} + }; + const statuses: Status[] = []; + const frames: AnyFrame[] = []; + const attached: { resync: boolean; gap?: boolean }[] = []; + const client = new RpcClient({ + url: 'ws://x/api/ws/s1', + since, + factory: () => { + const s = new FakeSocket(); + sockets.push(s); + return s; + }, + timers, + backoff: (n) => 100 * 2 ** n, + onFrame: (f) => frames.push(f), + onAttached: (a, resync) => attached.push({ resync, gap: a.gap }), + onStatus: (s) => statuses.push(s) + }); + const hello = (s: FakeSocket) => s.recv({ type: 'hello', protocol: 1, version: 'x' }); + const accept = (s: FakeSocket, data: object = { cursor: 5 }) => { + const attach = s.sent.at(-1)!; + s.recv({ + type: 'response', + id: attach.id, + success: true, + data: { host: 'h', pid: 1, session_id: 's', session_file: 'f', ...data } + }); + }; + return { client, sockets, timeouts, statuses, frames, attached, hello, accept }; +} + +describe('reconnect', () => { + it('attaches after hello and routes responses to the command that asked', async () => { + const h = harness(); + h.client.connect(); + h.hello(h.sockets[0]); + expect(h.sockets[0].sent[0]).toMatchObject({ type: 'attach' }); + h.accept(h.sockets[0]); + expect(h.client.status).toBe('open'); + + const p = h.client.send({ type: 'get_state' }); + const cmd = h.sockets[0].sent.at(-1)!; + h.sockets[0].recv({ type: 'response', id: cmd.id, success: true, data: { busy: false } }); + await expect(p).resolves.toEqual({ busy: false }); + + const bad = h.client.send({ type: 'abort' }); + h.sockets[0].recv({ + type: 'response', + id: h.sockets[0].sent.at(-1)!.id, + success: false, + error: 'A view link cannot send `abort`.' + }); + await expect(bad).rejects.toThrow('view link'); + }); + + it('comes back after a drop with backoff and asks only for what it missed', () => { + let seen: number | null = null; + const h = harness(() => seen); + h.client.connect(); + h.hello(h.sockets[0]); + h.accept(h.sockets[0]); + expect(h.attached[0].resync).toBe(true); // first connect builds from the snapshot + + h.sockets[0].recv({ type: 'idle', agent: 'lead', stop: 'stop', at: 17 }); + seen = 17; + h.sockets[0].drop(); + expect(h.client.status).toBe('reconnecting'); + expect(h.timeouts.at(-1)!.ms).toBe(100); + h.timeouts.at(-1)!.fn(); + h.hello(h.sockets[1]); + expect(h.sockets[1].sent[0]).toMatchObject({ type: 'attach', since: 17 }); + h.accept(h.sockets[1], { cursor: 20 }); + expect(h.attached[1].resync).toBe(false); + + // Success resets the ladder; failures without success climb it. + h.sockets[1].drop(); + expect(h.timeouts.at(-1)!.ms).toBe(100); + h.timeouts.at(-1)!.fn(); + h.sockets[2].drop(); + expect(h.timeouts.at(-1)!.ms).toBe(200); + }); + + it('rebuilds from the snapshot when the host says the cursor is unknown', () => { + const h = harness(() => 99); + h.client.connect(); + h.hello(h.sockets[0]); + h.accept(h.sockets[0], { cursor: 3, gap: true }); + expect(h.attached[0]).toEqual({ resync: true, gap: true }); + }); + + it('fails commands in flight when the socket drops', async () => { + const h = harness(); + h.client.connect(); + h.hello(h.sockets[0]); + h.accept(h.sockets[0]); + const p = h.client.send({ type: 'get_state' }); + h.sockets[0].drop(); + await expect(p).rejects.toThrow('Connection lost'); + await expect(h.client.send({ type: 'get_state' })).rejects.toThrow('Not connected'); + }); + + it('does not retry when signed out or the session is gone, and resumes at once after 4408', () => { + const h = harness(); + h.client.connect(); + h.sockets[0].drop(4401); + expect(h.client.status).toBe('unauthorized'); + expect(h.timeouts).toHaveLength(0); + + const g = harness(); + g.client.connect(); + g.sockets[0].drop(4404); + expect(g.client.status).toBe('missing'); + + const s = harness(); + s.client.connect(); + s.sockets[0].drop(4408); + expect(s.timeouts.at(-1)!.ms).toBe(0); + }); + + it('ignores late messages from a socket it replaced and stays closed once closed', () => { + const h = harness(); + h.client.connect(); + h.hello(h.sockets[0]); + h.accept(h.sockets[0]); + h.client.reset(); + expect(h.sockets).toHaveLength(2); + h.sockets[0].recv({ type: 'idle', agent: 'lead', stop: 'stop' }); + expect(h.frames).toHaveLength(0); + h.client.close(); + h.sockets[1].drop(); + expect(h.timeouts).toHaveLength(0); + expect(h.client.status).toBe('closed'); + }); + + it('backoff grows, is capped and is jittered', () => { + expect(backoffMs(0, () => 0.5)).toBe(500); + expect(backoffMs(3, () => 0.5)).toBe(4000); + expect(backoffMs(20, () => 0.5)).toBe(15000); + expect(backoffMs(2, () => 0)).toBeLessThan(backoffMs(2, () => 1)); + }); +}); diff --git a/web/tests/unit/markdown.test.ts b/web/tests/unit/markdown.test.ts new file mode 100644 index 00000000..c9cbea30 --- /dev/null +++ b/web/tests/unit/markdown.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest'; +import { renderBlocks, renderMarkdown } from '$lib/markdown'; + +const attack = [ + '', + '', + '[click](javascript:window.pwned=3)', + 'link', + '', + '', + '![x](https://evil.example/track.png)', + '
overlay
', + '', + '
', + '```html\n\n```' +].join('\n\n'); + +describe('model markdown is untrusted', () => { + it('removes scripts, event handlers, javascript: links, frames, forms and tracking images', () => { + const html = renderMarkdown(attack); + const doc = new DOMParser().parseFromString(html, 'text/html'); + expect( + doc.querySelectorAll('script, iframe, svg, style, form, img, [onerror], [onload], [onclick]') + ).toHaveLength(0); + for (const a of doc.querySelectorAll('a')) + expect(a.getAttribute('href') ?? '').not.toMatch(/^javascript:/i); + expect((window as unknown as { pwned?: number }).pwned).toBeUndefined(); + }); + + it('does not let the model borrow the page’s own classes', () => { + const doc = new DOMParser().parseFromString( + renderMarkdown('
x
'), + 'text/html' + ); + expect(doc.querySelector('.fixed, .inset-0, .z-50')).toBeNull(); + }); + + it('shows a code block’s HTML as text', () => { + const html = renderMarkdown('```html\n\n```'); + expect(html).toContain('<script>'); + expect(html).not.toContain(' { + const html = renderMarkdown( + '## Title\n\n- **bold** item\n\n[docs](https://example.com)\n\n| a | b |\n|---|---|\n| 1 | 2 |' + ); + const doc = new DOMParser().parseFromString(html, 'text/html'); + const a = doc.querySelector('a')!; + expect(a.getAttribute('rel')).toContain('noopener'); + expect(a.getAttribute('target')).toBe('_blank'); + expect(doc.querySelector('h2')?.textContent).toBe('Title'); + expect(doc.querySelector('strong')?.textContent).toBe('bold'); + expect(doc.querySelector('table')).not.toBeNull(); + }); + + it('sanitises every block while a reply is still streaming', () => { + const parts = renderBlocks( + 'First paragraph.\n\n\n\nStill typing { + const a = renderBlocks('One.\n\nTwo.', false); + const b = renderBlocks('One.\n\nTwo.\n\nThree', false); + expect(b[0]).toBe(a[0]); + expect(b).toHaveLength(3); + }); +}); diff --git a/web/tests/unit/reduce.test.ts b/web/tests/unit/reduce.test.ts new file mode 100644 index 00000000..89c99c10 --- /dev/null +++ b/web/tests/unit/reduce.test.ts @@ -0,0 +1,134 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import type { AnyFrame } from '$lib/protocol'; +import { + applySnapshot, + emptyModel, + leadBusy, + reduce, + type AssistantItem, + type ToolItem +} from '$lib/session/reduce'; + +const load = (name: string): AnyFrame[] => + readFileSync(resolve(process.cwd(), 'fixtures', `${name}.jsonl`), 'utf8') + .split('\n') + .filter(Boolean) + .map((l) => JSON.parse(l)); +const run = (frames: AnyFrame[]) => frames.reduce(reduce, emptyModel()); + +describe('frame reducer over recorded runs', () => { + it('builds a tool card with its diff from a write that needed approval', () => { + const frames = load('write_read'); + const beforeAnswer = run( + frames.slice( + 0, + frames.findIndex((f) => f.type === 'tool_end') + ) + ); + expect(beforeAnswer.requests).toHaveLength(1); + expect(beforeAnswer.requests[0].kind).toBe('approval'); + + const m = run(frames); + const write = m.items.find((i): i is ToolItem => i.kind === 'tool' && i.name === 'write'); + expect(write?.status).toBe('done'); + expect(write?.diff).toContain('+hello from azazel'); + expect(leadBusy(m)).toBe(false); + const last = m.items.filter((i): i is AssistantItem => i.kind === 'assistant').at(-1); + expect(last?.streaming).toBe(false); + }); + + it('keeps thinking, text and a markdown reply apart, and shows live shell output', () => { + const m = run(load('showcase')); + const assistants = m.items.filter((i): i is AssistantItem => i.kind === 'assistant'); + expect(assistants[0].blocks.map((b) => b.type)).toEqual(['thinking', 'text']); + expect(assistants.at(-1)?.blocks[0].text).toContain('## What changed'); + const shell = m.items.find((i): i is ToolItem => i.kind === 'tool' && i.name === 'shell'); + expect(shell?.live).toContain('2 passed'); + expect(shell?.status).toBe('done'); + expect(m.toasts).toEqual([]); + }); + + it('follows a roster of sub-agents to their final states and keeps their frames apart', () => { + const m = run(load('team_goal')); + expect(m.roster.map((r) => [r.id, r.state])).toContainEqual(['scout-1', 'done']); + expect(new Set(m.items.map((i) => i.agent)).has('scout-1')).toBe(true); + expect(m.items.filter((i) => i.agent === 'lead').every((i) => i.agent === 'lead')).toBe(true); + }); + + it('turns notify requests into toasts and every other ui_request into an open request', () => { + const m = run(load('forms')); + expect(m.requests.map((r) => r.kind)).toEqual(['ui', 'ui']); + expect(m.toasts).toHaveLength(1); + const closed = reduce(m, { type: 'request_closed', request_id: m.requests[0].id }); + expect(closed.requests).toHaveLength(m.requests.length - 1); + }); + + it('ignores a request it already has and frames it does not know', () => { + const frames = load('write_read'); + const req = frames.find((f) => f.type === 'approval_request')!; + const m = reduce(reduce(emptyModel(), req), req); + expect(m.requests).toHaveLength(1); + const same = reduce(m, { type: 'from_the_future' } as unknown as AnyFrame); + expect(same.items).toBe(m.items); + }); + + it('remembers the position of the last frame for resuming', () => { + let m = reduce(emptyModel(), { type: 'agent_start', agent: 'lead', at: 10 }); + m = reduce(m, { type: 'idle', agent: 'lead', stop: 'stop', at: 42 }); + m = reduce(m, { type: 'roster', members: [], at: 7 }); + expect(m.lastAt).toBe(42); + }); + + it('rebuilds a half-written reply and running tools from an attach snapshot', () => { + const m = applySnapshot(emptyModel(), { + busy: true, + tail: [ + { + entry_id: 'e1', + timestamp: '', + message: { role: 'user', content: [{ type: 'text', text: 'go' }] } + }, + { + entry_id: 'e2', + timestamp: '', + message: { + role: 'assistant', + content: [ + { type: 'text', text: 'On it.' }, + { type: 'tool_call', id: 'c1', name: 'read', input: { path: 'a' } } + ] + } + }, + { + entry_id: 'e3', + timestamp: '', + message: { + role: 'tool', + content: [ + { type: 'tool_result', call_id: 'c1', content: [{ type: 'text', text: 'file' }] } + ] + } + } + ] as never, + streaming: [{ agent: 'lead', text: 'Half a sen' }], + tools: [ + { agent: 'lead', call_id: 'c9', name: 'shell', input: { command: 'ls' }, elapsed_ms: 1200 } + ], + queue: [{ kind: 'steer', text: 'wait' }] + }); + expect(leadBusy(m)).toBe(true); + expect(m.items.map((i) => i.kind)).toEqual(['user', 'assistant', 'tool', 'assistant', 'tool']); + const read = m.items.find((i): i is ToolItem => i.kind === 'tool' && i.callId === 'c1'); + expect(read).toMatchObject({ status: 'done', output: 'file' }); + // A delta that arrives next lands in the reply the snapshot opened. + const next = reduce(m, { + type: 'stream', + agent: 'lead', + event: { type: 'text_delta', index: 1, delta: 'tence' } + }); + const open = next.items.filter((i): i is AssistantItem => i.kind === 'assistant').at(-1); + expect(open?.blocks[0].text).toBe('Half a sentence'); + }); +}); diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 00000000..a8f10c8e --- /dev/null +++ b/web/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "./.svelte-kit/tsconfig.json", + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "moduleResolution": "bundler" + } +} diff --git a/web/vite.config.ts b/web/vite.config.ts new file mode 100644 index 00000000..5ec90ba0 --- /dev/null +++ b/web/vite.config.ts @@ -0,0 +1,29 @@ +import { sveltekit } from '@sveltejs/kit/vite'; +import tailwindcss from '@tailwindcss/vite'; +import { defineConfig } from 'vitest/config'; + +// The azazel server stays strict about Origin and Host, so the dev proxy rewrites them. +const target = process.env.AZAZEL_REMOTE ?? 'http://127.0.0.1:7420'; + +export default defineConfig({ + plugins: [tailwindcss(), sveltekit()], + server: { + proxy: { + '/api': { + target, + ws: true, + changeOrigin: true, + configure(proxy) { + proxy.on('proxyReqWs', (req) => req.setHeader('Origin', target)); + proxy.on('proxyReq', (req) => req.setHeader('Origin', target)); + } + } + } + }, + test: { + include: ['tests/unit/**/*.test.ts'], + environment: 'jsdom', + alias: { $lib: new URL('./src/lib', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1') } + }, + resolve: process.env.VITEST ? { conditions: ['browser'] } : undefined +}); From 450265473426e3dbf7a39bc8f1a0482c5171639b Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:20:56 +0000 Subject: [PATCH 05/27] azazel-remote: server crate (auth, policy, limits, assets, QR, HTTP, WebSocket) --- Cargo.lock | 31 +++ Cargo.toml | 7 + crates/azazel-remote/Cargo.toml | 37 +++ crates/azazel-remote/build.rs | 96 ++++++++ crates/azazel-remote/src/assets.rs | 69 ++++++ crates/azazel-remote/src/auth.rs | 273 ++++++++++++++++++++++ crates/azazel-remote/src/http.rs | 338 ++++++++++++++++++++++++++++ crates/azazel-remote/src/lib.rs | 99 ++++++++ crates/azazel-remote/src/limits.rs | 192 ++++++++++++++++ crates/azazel-remote/src/policy.rs | 224 ++++++++++++++++++ crates/azazel-remote/src/qr.rs | 55 +++++ crates/azazel-remote/src/server.rs | 256 +++++++++++++++++++++ crates/azazel-remote/src/testing.rs | 27 +++ crates/azazel-remote/src/ws.rs | 129 +++++++++++ docs/remote.md | 7 +- 15 files changed, 1837 insertions(+), 3 deletions(-) create mode 100644 crates/azazel-remote/Cargo.toml create mode 100644 crates/azazel-remote/build.rs create mode 100644 crates/azazel-remote/src/assets.rs create mode 100644 crates/azazel-remote/src/auth.rs create mode 100644 crates/azazel-remote/src/http.rs create mode 100644 crates/azazel-remote/src/lib.rs create mode 100644 crates/azazel-remote/src/limits.rs create mode 100644 crates/azazel-remote/src/policy.rs create mode 100644 crates/azazel-remote/src/qr.rs create mode 100644 crates/azazel-remote/src/server.rs create mode 100644 crates/azazel-remote/src/testing.rs create mode 100644 crates/azazel-remote/src/ws.rs diff --git a/Cargo.lock b/Cargo.lock index a08798fe..f08dfc6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1173,6 +1173,31 @@ dependencies = [ "serde_json", ] +[[package]] +name = "azazel-remote" +version = "0.10.5" +dependencies = [ + "async-trait", + "azazel-protocol", + "base64 0.23.1", + "bytes", + "flate2", + "futures", + "http-body-util", + "hyper", + "hyper-util", + "jiff", + "qrcodegen", + "rand 0.10.3", + "serde", + "serde_json", + "sha2 0.11.1", + "tokio", + "tokio-tungstenite", + "tokio-util", + "tracing", +] + [[package]] name = "azazel-repomap" version = "0.10.5" @@ -5466,6 +5491,12 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qrcodegen" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4339fc7a1021c9c1621d87f5e3505f2805c8c105420ba2f2a4df86814590c142" + [[package]] name = "quantette" version = "0.6.0" diff --git a/Cargo.toml b/Cargo.toml index 8e681edc..8c82e28b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,7 @@ azazel-tui = { path = "crates/azazel-tui" } azazel-cli = { path = "crates/azazel-cli" } azazel-protocol = { path = "crates/azazel-protocol" } azazel-client = { path = "crates/azazel-client" } +azazel-remote = { path = "crates/azazel-remote" } # Async runtime and streams tokio = { version = "1.54", features = [ @@ -75,6 +76,12 @@ reqwest = { version = "0.13", default-features = false, features = [ ] } rustls = { version = "0.23", default-features = false, features = ["ring", "std"] } tokio-tungstenite = { version = "0.30", features = ["connect"] } +# The remote server (`azazel remote`): hyper's server half, no router. The QR code of a pairing +# link is drawn by `qrcodegen`, which has no dependencies. +hyper = { version = "1", default-features = false, features = ["server", "http1"] } +hyper-util = { version = "0.1", default-features = false, features = ["tokio"] } +http-body-util = "0.1" +qrcodegen = "1.8" # Serialisation serde = { version = "1", features = ["derive"] } diff --git a/crates/azazel-remote/Cargo.toml b/crates/azazel-remote/Cargo.toml new file mode 100644 index 00000000..ea99ddc6 --- /dev/null +++ b/crates/azazel-remote/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "azazel-remote" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +publish.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +async-trait.workspace = true +azazel-protocol.workspace = true +base64.workspace = true +bytes.workspace = true +flate2.workspace = true +futures.workspace = true +http-body-util.workspace = true +hyper.workspace = true +hyper-util.workspace = true +jiff.workspace = true +qrcodegen.workspace = true +rand.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +tokio.workspace = true +tokio-tungstenite.workspace = true +tokio-util.workspace = true +tracing.workspace = true + +[build-dependencies] +flate2.workspace = true +sha2.workspace = true + +[dev-dependencies] diff --git a/crates/azazel-remote/build.rs b/crates/azazel-remote/build.rs new file mode 100644 index 00000000..a267d6db --- /dev/null +++ b/crates/azazel-remote/build.rs @@ -0,0 +1,96 @@ +//! Embeds the web page. `web/build/` (made by `bun --cwd web run build`) is gzipped file by file into +//! `OUT_DIR/assets.rs`; without it, a one-page placeholder stands in, so that Rust builds and tests +//! need no Node. + +use std::fmt::Write as _; +use std::io::Write as _; +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +const PLACEHOLDER: &str = "\n\n\n\n\ +\nazazel remote\n\ +\n\n\n\ +

azazel remote

\n

The web page was not built into this binary.

\n\ +

Build it with bun --cwd web run build, then build azazel again.

\n\n\n"; + +fn main() { + let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default()); + let build = manifest.join("../../web/build"); + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=AZAZEL_WEB_BUILD"); + let build = std::env::var_os("AZAZEL_WEB_BUILD") + .map(PathBuf::from) + .unwrap_or(build); + let mut files: Vec<(String, Vec)> = Vec::new(); + if build.join("index.html").is_file() { + // Only a directory that exists is watched: a missing one would make every build run this + // script again. + println!("cargo:rerun-if-changed={}", build.display()); + walk(&build, &build, &mut files); + files.sort(); + } else { + files.push(("index.html".to_string(), PLACEHOLDER.as_bytes().to_vec())); + } + let out = PathBuf::from(std::env::var("OUT_DIR").unwrap_or_default()); + let mut source = String::from("pub static ASSETS: &[Asset] = &[\n"); + for (index, (path, bytes)) in files.iter().enumerate() { + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best()); + gz.write_all(bytes).expect("gzip in memory"); + let gz = gz.finish().expect("gzip in memory"); + let name = format!("asset{index}.gz"); + std::fs::write(out.join(&name), gz).expect("write an asset"); + let digest = Sha256::digest(bytes); + let mut etag = String::new(); + for byte in &digest[..8] { + write!(etag, "{byte:02x}").expect("write to a string"); + } + writeln!( + source, + " Asset {{ path: {path:?}, mime: {:?}, gz: include_bytes!(concat!(env!(\"OUT_DIR\"), \"/{name}\")), etag: \"\\\"{etag}\\\"\" }},", + mime(path) + ) + .expect("write to a string"); + } + source.push_str("];\n"); + std::fs::write(out.join("assets.rs"), source).expect("write assets.rs"); +} + +fn walk(root: &Path, dir: &Path, files: &mut Vec<(String, Vec)>) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + walk(root, &path, files); + } else if let (Ok(relative), Ok(bytes)) = (path.strip_prefix(root), std::fs::read(&path)) { + let relative = relative + .components() + .map(|part| part.as_os_str().to_string_lossy().into_owned()) + .collect::>() + .join("/"); + files.push((relative, bytes)); + } + } +} + +fn mime(path: &str) -> &'static str { + match path.rsplit_once('.').map(|(_, extension)| extension) { + Some("html") => "text/html; charset=utf-8", + Some("js" | "mjs") => "text/javascript; charset=utf-8", + Some("css") => "text/css; charset=utf-8", + Some("json" | "map") => "application/json", + Some("webmanifest") => "application/manifest+json", + Some("svg") => "image/svg+xml", + Some("png") => "image/png", + Some("jpg" | "jpeg") => "image/jpeg", + Some("gif") => "image/gif", + Some("webp") => "image/webp", + Some("ico") => "image/x-icon", + Some("woff") => "font/woff", + Some("woff2") => "font/woff2", + Some("wasm") => "application/wasm", + Some("txt") => "text/plain; charset=utf-8", + _ => "application/octet-stream", + } +} diff --git a/crates/azazel-remote/src/assets.rs b/crates/azazel-remote/src/assets.rs new file mode 100644 index 00000000..377a2d4f --- /dev/null +++ b/crates/azazel-remote/src/assets.rs @@ -0,0 +1,69 @@ +//! The web page, embedded by `build.rs`: each file gzipped, served as it is to a browser that +//! accepts gzip and inflated for one that does not. + +use std::io::Read; + +pub(crate) struct Asset { + pub path: &'static str, + pub mime: &'static str, + pub gz: &'static [u8], + pub etag: &'static str, +} + +include!(concat!(env!("OUT_DIR"), "/assets.rs")); + +/// The asset a request path names. A path that names no file gets `index.html`, so that the page +/// can route by itself; a missing file of the build output (`/_app/…`) or with an extension is +/// not a page and gets nothing. +pub(crate) fn find(path: &str) -> Option<&'static Asset> { + let wanted = path.trim_start_matches('/'); + let wanted = if wanted.is_empty() { "index.html" } else { wanted }; + if let Some(asset) = ASSETS.iter().find(|asset| asset.path == wanted) { + return Some(asset); + } + let last = wanted.rsplit('/').next().unwrap_or_default(); + if wanted.starts_with("_app/") || last.contains('.') { + return None; + } + ASSETS.iter().find(|asset| asset.path == "index.html") +} + +/// How long a browser may keep a file: the build names the files under `_app/immutable/` by what +/// they hold, so they never change; everything else is checked each time. +pub(crate) fn cache_control(asset: &Asset) -> &'static str { + if asset.path.starts_with("_app/immutable/") { + "public, max-age=31536000, immutable" + } else { + "no-cache" + } +} + +pub(crate) fn inflate(asset: &Asset) -> Vec { + let mut out = Vec::new(); + // The bytes were made by the build script from a file it read; they are a valid gzip stream. + if flate2::read::GzDecoder::new(asset.gz).read_to_end(&mut out).is_err() { + out.clear(); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_root_and_unknown_pages_are_the_index_and_unknown_files_are_not() { + assert_eq!(find("/").map(|a| a.path), Some("index.html")); + assert_eq!(find("/s/abc123").map(|a| a.path), Some("index.html")); + assert!(find("/_app/immutable/missing.js").is_none()); + assert!(find("/missing.png").is_none()); + } + + #[test] + fn an_asset_inflates_to_what_was_embedded() { + let index = find("/").unwrap(); + let text = String::from_utf8(inflate(index)).unwrap(); + assert!(text.contains(", + devices: HashMap, + per_address: HashMap, + all: Option, + in_a_row: u32, +} + +pub(crate) struct Auth { + clock: Arc, + inner: Mutex, + link_ttl: Duration, + device_ttl: Duration, +} + +fn hash(secret: &str) -> String { + URL_SAFE_NO_PAD.encode(Sha256::digest(secret.as_bytes())) +} + +fn random() -> String { + URL_SAFE_NO_PAD.encode(rand::random::<[u8; 32]>()) +} + +impl Auth { + pub fn new(clock: Arc, link_ttl: Duration, device_ttl: Duration) -> Auth { + Auth { + clock, + inner: Mutex::new(Inner::default()), + link_ttl, + device_ttl, + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { + self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + pub fn now(&self) -> SystemTime { + self.clock.now() + } + + /// A new single-use secret and when it stops working. + pub fn mint_link(&self, access: Access) -> (String, SystemTime) { + let secret = random(); + let expires = self.clock.now() + self.link_ttl; + self.lock() + .links + .insert(hash(&secret), PendingLink { access, expires }); + (secret, expires) + } + + /// Turns a pairing secret into a device and its token. + pub fn pair(&self, secret: &str, from: IpAddr) -> Result<(String, Device), PairError> { + let now = self.clock.now(); + let at = since_epoch(now); + let mut inner = self.lock(); + inner.links.retain(|_, link| link.expires > now); + let all = inner.all.get_or_insert_with(|| Window::new(MINUTE, IN_ALL)); + let all_open = all.open(at); + let address_open = inner + .per_address + .entry(from) + .or_insert_with(|| Window::new(MINUTE, PER_ADDRESS)) + .open(at); + if !all_open || !address_open { + return Err(PairError::TooMany); + } + let Some(link) = inner.links.remove(&hash(secret)) else { + if let Some(all) = inner.all.as_mut() { + all.record(at); + } + if let Some(window) = inner.per_address.get_mut(&from) { + window.record(at); + } + inner.in_a_row += 1; + if inner.in_a_row >= VOID_AFTER { + inner.links.clear(); + } + return Err(PairError::Invalid); + }; + inner.in_a_row = 0; + inner.per_address.retain(|_, window| !window.is_idle(at)); + let token = random(); + let digest = hash(&token); + let device = Device { + id: digest.chars().take(10).collect(), + access: link.access, + expires: now + self.device_ttl, + cancel: CancellationToken::new(), + }; + inner.devices.insert(digest, device.clone()); + Ok((token, device)) + } + + /// The device a token belongs to, while it is signed in. + pub fn device(&self, token: &str) -> Option { + let now = self.clock.now(); + let digest = hash(token); + let mut inner = self.lock(); + let device = inner.devices.get(&digest)?; + if device.expires <= now { + device.cancel.cancel(); + inner.devices.remove(&digest); + return None; + } + Some(device.clone()) + } + + pub fn sign_out(&self, token: &str) { + if let Some(device) = self.lock().devices.remove(&hash(token)) { + device.cancel.cancel(); + } + } + + /// Signs every device out and voids every link. + pub fn revoke_all(&self) { + let mut inner = self.lock(); + for device in inner.devices.values() { + device.cancel.cancel(); + } + inner.devices.clear(); + inner.links.clear(); + inner.in_a_row = 0; + } +} + +#[cfg(test)] +mod tests { + use std::net::Ipv4Addr; + + use super::*; + use crate::testing::FakeClock; + + const ME: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST); + + fn auth() -> (Auth, Arc) { + let clock = Arc::new(FakeClock::default()); + let auth = Auth::new( + clock.clone(), + Duration::from_secs(15 * 60), + Duration::from_secs(24 * 3600), + ); + (auth, clock) + } + + #[test] + fn a_link_pairs_one_device_once() { + let (auth, _) = auth(); + let (secret, _) = auth.mint_link(Access::Control); + let (token, device) = auth.pair(&secret, ME).unwrap(); + assert_eq!(device.access, Access::Control); + assert_eq!(auth.device(&token).unwrap().id, device.id); + assert_eq!(auth.pair(&secret, ME).unwrap_err(), PairError::Invalid); + } + + #[test] + fn a_link_expires_and_so_does_a_device() { + let (auth, clock) = auth(); + let (stale, _) = auth.mint_link(Access::View); + clock.advance(Duration::from_secs(15 * 60)); + assert_eq!(auth.pair(&stale, ME).unwrap_err(), PairError::Invalid); + let (secret, _) = auth.mint_link(Access::View); + let (token, device) = auth.pair(&secret, ME).unwrap(); + clock.advance(Duration::from_secs(24 * 3600 - 1)); + assert!(auth.device(&token).is_some()); + clock.advance(Duration::from_secs(1)); + assert!(auth.device(&token).is_none()); + assert!(device.cancel.is_cancelled()); + } + + #[test] + fn revoking_signs_every_device_out_and_voids_the_links() { + let (auth, _) = auth(); + let (secret, _) = auth.mint_link(Access::Control); + let (token, device) = auth.pair(&secret, ME).unwrap(); + let (open, _) = auth.mint_link(Access::View); + auth.revoke_all(); + assert!(auth.device(&token).is_none() && device.cancel.is_cancelled()); + assert_eq!(auth.pair(&open, ME).unwrap_err(), PairError::Invalid); + } + + #[test] + fn five_failures_a_minute_stop_an_address_even_with_the_right_secret() { + let (auth, clock) = auth(); + let (secret, _) = auth.mint_link(Access::Control); + for _ in 0..5 { + assert_eq!(auth.pair("wrong", ME).unwrap_err(), PairError::Invalid); + } + assert_eq!(auth.pair(&secret, ME).unwrap_err(), PairError::TooMany); + let elsewhere = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)); + assert!(auth.pair(&secret, elsewhere).is_ok()); + clock.advance(MINUTE); + assert_eq!(auth.pair("wrong", ME).unwrap_err(), PairError::Invalid); + } + + #[test] + fn twenty_failures_a_minute_from_anywhere_stop_everyone() { + let (auth, _) = auth(); + for n in 0..20u8 { + let from = IpAddr::V4(Ipv4Addr::new(10, 0, 1, n)); + assert_eq!(auth.pair("wrong", from).unwrap_err(), PairError::Invalid); + } + let (secret, _) = auth.mint_link(Access::Control); + let late = IpAddr::V4(Ipv4Addr::new(10, 0, 2, 1)); + assert_eq!(auth.pair(&secret, late).unwrap_err(), PairError::TooMany); + } + + #[test] + fn ten_failures_in_a_row_void_the_links_that_were_open() { + let (auth, clock) = auth(); + let (secret, _) = auth.mint_link(Access::Control); + for n in 0..10u8 { + // Spread out, so that no rate limit is what stops the pairing. + clock.advance(Duration::from_secs(30)); + let from = IpAddr::V4(Ipv4Addr::new(10, 0, 3, n)); + assert_eq!(auth.pair("wrong", from).unwrap_err(), PairError::Invalid); + } + clock.advance(MINUTE); + assert_eq!(auth.pair(&secret, ME).unwrap_err(), PairError::Invalid); + let (fresh, _) = auth.mint_link(Access::Control); + assert!(auth.pair(&fresh, ME).is_ok()); + } +} diff --git a/crates/azazel-remote/src/http.rs b/crates/azazel-remote/src/http.rs new file mode 100644 index 00000000..cda8dc4e --- /dev/null +++ b/crates/azazel-remote/src/http.rs @@ -0,0 +1,338 @@ +//! The routes: the page, the API, and the upgrade to a WebSocket. + +use std::net::IpAddr; +use std::sync::Arc; + +use bytes::Bytes; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::body::Incoming; +use hyper::header::{ + ACCEPT_ENCODING, CACHE_CONTROL, CONNECTION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, COOKIE, ETAG, + HOST, IF_NONE_MATCH, ORIGIN, RETRY_AFTER, SET_COOKIE, UPGRADE, VARY, +}; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use serde::Deserialize; +use serde_json::{Value, json}; +use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::tungstenite::handshake::derive_accept_key; +use tokio_tungstenite::tungstenite::protocol::{Role, WebSocketConfig}; + +use crate::assets; +use crate::auth::{Device, PairError}; +use crate::server::{Shared, rfc3339}; +use crate::{Access, ws}; + +pub(crate) type Res = Response>; + +const BODY_LIMIT: usize = 64 * 1024; +pub(crate) const MESSAGE_LIMIT: usize = 12 * 1024 * 1024; +const COOKIE_NAME: &str = "azazel_device"; +const CSP: &str = "default-src 'self'; connect-src 'self'; img-src 'self' data: blob:; \ +style-src 'self' 'unsafe-inline'; frame-ancestors 'none'"; + +fn value(text: &str) -> hyper::header::HeaderValue { + hyper::header::HeaderValue::from_str(text).unwrap_or_else(|_| hyper::header::HeaderValue::from_static("")) +} + +pub(crate) async fn handle(shared: Arc, peer: IpAddr, req: Request) -> Res { + let is_api = req.uri().path() == "/api" || req.uri().path().starts_with("/api/"); + let mut res = route(&shared, peer, req).await; + let headers = res.headers_mut(); + headers.insert("x-content-type-options", value("nosniff")); + headers.insert("referrer-policy", value("no-referrer")); + headers.insert("content-security-policy", value(CSP)); + if is_api { + headers.insert(CACHE_CONTROL, value("no-store")); + } + res +} + +fn reply(status: u16, content_type: &str, body: impl Into) -> Res { + let mut res = Response::new(Full::new(body.into())); + *res.status_mut() = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + res.headers_mut().insert(CONTENT_TYPE, value(content_type)); + res +} + +fn json_reply(status: u16, body: Value) -> Res { + reply(status, "application/json", body.to_string()) +} + +fn error(status: u16, message: &str) -> Res { + json_reply(status, json!({ "error": message })) +} + +fn header<'a>(req: &'a Request, name: impl hyper::header::AsHeaderName) -> Option<&'a str> { + req.headers().get(name).and_then(|v| v.to_str().ok()) +} + +/// The device token a request carries, and whether it came in a cookie. +fn token(req: &Request) -> Option<(String, bool)> { + if let Some(bearer) = header(req, "authorization").and_then(|v| v.strip_prefix("Bearer ")) { + return Some((bearer.trim().to_string(), false)); + } + let cookies = header(req, COOKIE)?; + cookies.split(';').find_map(|part| { + let (name, content) = part.trim().split_once('=')?; + (name == COOKIE_NAME && !content.is_empty()).then(|| (content.to_string(), true)) + }) +} + +/// The device a request is signed in as, if any. A cookie is sent by the browser on its own, so a +/// request that rides on one must also say where it came from. +fn authenticate( + shared: &Shared, + req: &Request, + needs_origin: bool, +) -> Result, Res> { + let Some((token, cookie)) = token(req) else { + return Ok(None); + }; + if cookie && needs_origin && header(req, ORIGIN).is_none() { + return Err(error( + 403, + "a request signed in by cookie must say where it comes from (`Origin`)", + )); + } + Ok(shared.auth.device(&token).map(|device| (token, device))) +} + +fn signed_in(shared: &Shared, req: &Request, needs_origin: bool) -> Result<(String, Device), Res> { + authenticate(shared, req, needs_origin)?.ok_or_else(|| { + error( + 401, + "not signed in: open the pairing link again, or ask for a new one", + ) + }) +} + +async fn route(shared: &Arc, peer: IpAddr, mut req: Request) -> Res { + if !shared.host_ok(header(&req, HOST).unwrap_or_default()) { + return error(421, "this server does not answer to that address"); + } + let path = req.uri().path().to_string(); + if !(path == "/api" || path.starts_with("/api/")) { + return page(&req); + } + if let Some(origin) = header(&req, ORIGIN) + && !shared.origin_ok(origin) + { + return error(403, "that origin is not one of this server's pages"); + } + if req.method() == Method::POST && header(&req, "x-azazel") != Some("1") { + return error(403, "a POST needs the header `X-Azazel: 1`"); + } + match (req.method().clone(), path.as_str()) { + (Method::POST, "/api/pair") => pair(shared, peer, req).await, + (Method::GET, "/api/me") => match signed_in(shared, &req, false) { + Ok((_, device)) => json_reply( + 200, + json!({ + "access": device.access, + "expires": rfc3339(device.expires), + "allow_bypass": shared.allow_bypass, + "protocol": azazel_protocol::PROTOCOL, + "version": env!("CARGO_PKG_VERSION"), + }), + ), + Err(res) => res, + }, + (Method::GET, "/api/sessions") => match signed_in(shared, &req, false) { + Ok(_) => { + let mut sessions = shared.sessions.list().await; + sessions.sort_by(|a, b| b.started.cmp(&a.started)); + json_reply(200, json!({ "sessions": sessions })) + } + Err(res) => res, + }, + (Method::POST, "/api/links") => links(shared, req).await, + (Method::POST, "/api/logout") => match signed_in(shared, &req, true) { + Ok((token, _)) => { + shared.auth.sign_out(&token); + let mut res = reply(204, "application/json", Bytes::new()); + res.headers_mut().insert( + SET_COOKIE, + value(&format!( + "{COOKIE_NAME}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0" + )), + ); + res + } + Err(res) => res, + }, + (Method::GET, p) if p.starts_with("/api/ws/") => socket(shared, &mut req, &p["/api/ws/".len()..]), + (_, "/api/pair" | "/api/me" | "/api/sessions" | "/api/links" | "/api/logout") => { + error(405, "that route does not take this method") + } + (_, p) if p.starts_with("/api/ws/") => error(405, "that route does not take this method"), + _ => error(404, "no such route"), + } +} + +/// The web page, or the file of the build the path names. +fn page(req: &Request) -> Res { + let head = req.method() == Method::HEAD; + if !head && req.method() != Method::GET { + return error(405, "the page is read with GET"); + } + let Some(asset) = assets::find(req.uri().path()) else { + return reply(404, "text/plain; charset=utf-8", "not found"); + }; + let etag = asset.etag; + let mut res = if header(req, IF_NONE_MATCH) == Some(etag) { + reply(304, asset.mime, Bytes::new()) + } else { + let gzip = header(req, ACCEPT_ENCODING) + .is_some_and(|accepted| accepted.split(',').any(|part| part.trim().starts_with("gzip"))); + let (body, encoded) = if gzip { + (Bytes::from_static(asset.gz), true) + } else { + (Bytes::from(assets::inflate(asset)), false) + }; + let length = body.len(); + let mut res = reply(200, asset.mime, if head { Bytes::new() } else { body }); + if encoded { + res.headers_mut().insert(CONTENT_ENCODING, value("gzip")); + } + if head { + res.headers_mut().insert(CONTENT_LENGTH, length.into()); + } + res + }; + let headers = res.headers_mut(); + headers.insert(VARY, value("Accept-Encoding")); + headers.insert(CACHE_CONTROL, value(assets::cache_control(asset))); + headers.insert(ETAG, value(etag)); + res +} + +async fn body(req: Request) -> Result { + Limited::new(req.into_body(), BODY_LIMIT) + .collect() + .await + .map(|collected| collected.to_bytes()) + .map_err(|_| error(413, "the request is too large")) +} + +#[derive(Deserialize)] +struct PairBody { + secret: String, + #[serde(default)] + bearer: bool, +} + +async fn pair(shared: &Arc, peer: IpAddr, req: Request) -> Res { + let host = header(&req, HOST).unwrap_or_default().to_ascii_lowercase(); + let secure = shared.is_https_host(&host); + let bytes = match body(req).await { + Ok(bytes) => bytes, + Err(res) => return res, + }; + let Ok(pair) = serde_json::from_slice::(&bytes) else { + return error(400, "send {\"secret\": \"…\"}"); + }; + match shared.auth.pair(&pair.secret, peer) { + Ok((token, device)) => { + let seconds = device + .expires + .duration_since(shared.auth.now()) + .map(|left| left.as_secs()) + .unwrap_or_default(); + let mut answer = json!({ + "access": device.access, + "expires": rfc3339(device.expires), + "allow_bypass": shared.allow_bypass, + }); + if pair.bearer { + answer["token"] = Value::String(token); + return json_reply(200, answer); + } + let mut res = json_reply(200, answer); + let secure = if secure { "; Secure" } else { "" }; + res.headers_mut().insert( + SET_COOKIE, + value(&format!( + "{COOKIE_NAME}={token}; HttpOnly; SameSite=Strict; Path=/; Max-Age={seconds}{secure}" + )), + ); + res + } + Err(PairError::Invalid) => error( + 401, + "that link does not work: it was used, it expired, or it is wrong", + ), + Err(PairError::TooMany) => { + let mut res = error(429, "too many attempts: wait a minute"); + res.headers_mut().insert(RETRY_AFTER, value("60")); + res + } + } +} + +#[derive(Deserialize)] +struct LinkBody { + access: Access, +} + +async fn links(shared: &Arc, req: Request) -> Res { + let device = match signed_in(shared, &req, true) { + Ok((_, device)) => device, + Err(res) => return res, + }; + let origin = header(&req, ORIGIN).map(str::to_string); + let bytes = match body(req).await { + Ok(bytes) => bytes, + Err(res) => return res, + }; + let Ok(wanted) = serde_json::from_slice::(&bytes) else { + return error(400, "send {\"access\": \"view\"} or {\"access\": \"control\"}"); + }; + if wanted.access == Access::Control && device.access != Access::Control { + return error(403, "a view device can make view links only"); + } + // The page that asked is the page the link should open, whichever way it was reached. + let origin = origin.unwrap_or_else(|| shared.origin()); + json_reply( + 200, + serde_json::to_value(shared.link(wanted.access, &origin)).unwrap_or_default(), + ) +} + +fn socket(shared: &Arc, req: &mut Request, id: &str) -> Res { + let device = match authenticate(shared, req, true) { + Ok(device) => device.map(|(_, device)| device), + Err(res) => return res, + }; + let wants = |name: &str, wanted: &str| { + header(req, name).is_some_and(|v| v.split(',').any(|part| part.trim().eq_ignore_ascii_case(wanted))) + }; + let Some(key) = header(req, "sec-websocket-key").map(str::to_string) else { + return error(400, "this route is a WebSocket"); + }; + if !wants("upgrade", "websocket") + || !wants("connection", "upgrade") + || header(req, "sec-websocket-version") != Some("13") + { + return error(400, "this route is a WebSocket (version 13)"); + } + let accept = derive_accept_key(key.as_bytes()); + let upgraded = hyper::upgrade::on(&mut *req); + let (shared, id) = (shared.clone(), id.to_string()); + tokio::spawn(async move { + let Ok(upgraded) = upgraded.await else { return }; + let config = WebSocketConfig::default() + .max_message_size(Some(MESSAGE_LIMIT)) + .max_frame_size(Some(MESSAGE_LIMIT)); + let socket = + WebSocketStream::from_raw_socket(TokioIo::new(upgraded), Role::Server, Some(config)).await; + ws::run(shared, socket, device, id).await; + }); + let mut res = Response::new(Full::default()); + *res.status_mut() = StatusCode::SWITCHING_PROTOCOLS; + let headers = res.headers_mut(); + headers.insert(UPGRADE, value("websocket")); + headers.insert(CONNECTION, value("Upgrade")); + headers.insert("sec-websocket-accept", value(&accept)); + res +} diff --git a/crates/azazel-remote/src/lib.rs b/crates/azazel-remote/src/lib.rs new file mode 100644 index 00000000..0b865941 --- /dev/null +++ b/crates/azazel-remote/src/lib.rs @@ -0,0 +1,99 @@ +//! The server behind `azazel remote`: serves the web page and carries the RPC protocol of a session +//! over a WebSocket, to browsers that were paired with a link. +//! +//! It knows nothing of the application. Sessions reach it through [`Sessions`]; what it adds is +//! the part that must be right whoever uses it: who may connect ([`auth`]), what they may send +//! ([`policy`]), and the limits. + +mod assets; +mod auth; +mod http; +mod limits; +mod policy; +mod qr; +mod server; +#[cfg(test)] +mod testing; +mod ws; + +use std::net::IpAddr; +use std::time::Duration; + +use async_trait::async_trait; +use serde::{Deserialize, Serialize}; +use tokio::sync::mpsc; + +pub use limits::{Clock, SystemClock}; +pub use policy::{check, policy}; +pub use qr::{qr_matrix, qr_svg}; +pub use server::Server; + +/// What a paired device may do. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Access { + /// Watch only. + View, + /// Watch, answer and steer. + Control, +} + +/// Where a session lives. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Kind { + /// The session of a terminal UI that shares itself. + Terminal, + /// A background session. + Background, +} + +/// One session, as the list shows it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct SessionInfo { + pub id: String, + pub name: Option, + pub kind: Kind, + pub state: String, + pub cwd: String, + pub cost_usd: Option, + pub mode: Option, + /// RFC 3339. + pub started: String, +} + +/// A connection to one session: the lines it sends (`hello` first) and a way to send it lines. +pub struct Conn { + pub frames: mpsc::Receiver, + pub commands: mpsc::Sender, +} + +/// The sessions a server can reach. +#[async_trait] +pub trait Sessions: Send + Sync + 'static { + async fn list(&self) -> Vec; + /// Connects to a session. The error says why it cannot be reached (it may have ended). + async fn open(&self, id: &str) -> Result; +} + +pub struct Options { + pub bind: IpAddr, + /// Tried first; when it is taken the next nine are. 0 lets the system choose. + pub port: u16, + /// The address of a tunnel or proxy in front of the server: the origin of links, and an + /// origin and host the server accepts. + pub public_url: Option, + pub link_ttl: Duration, + pub device_ttl: Duration, + pub redact: bool, + pub allow_bypass: bool, +} + +/// A pairing link. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Link { + pub url: String, + pub access: Access, + /// RFC 3339. + pub expires: String, +} diff --git a/crates/azazel-remote/src/limits.rs b/crates/azazel-remote/src/limits.rs new file mode 100644 index 00000000..b231d5f7 --- /dev/null +++ b/crates/azazel-remote/src/limits.rs @@ -0,0 +1,192 @@ +//! Counting: the clock the rest of the crate asks for the time, a window of recent events, a +//! token bucket for commands, and the number of open sockets. + +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +/// Where the crate takes the time from, so that a test controls it. +pub trait Clock: Send + Sync + 'static { + fn now(&self) -> SystemTime; +} + +#[derive(Debug, Default)] +pub struct SystemClock; + +impl Clock for SystemClock { + fn now(&self) -> SystemTime { + SystemTime::now() + } +} + +/// Time as the span since the epoch, which windows and buckets count in. +pub(crate) fn since_epoch(time: SystemTime) -> Duration { + time.duration_since(UNIX_EPOCH).unwrap_or_default() +} + +/// At most `max` events within `span`. +#[derive(Debug)] +pub(crate) struct Window { + span: Duration, + max: usize, + hits: VecDeque, +} + +impl Window { + pub fn new(span: Duration, max: usize) -> Window { + Window { + span, + max, + hits: VecDeque::new(), + } + } + + fn trim(&mut self, now: Duration) { + while self + .hits + .front() + .is_some_and(|hit| now.saturating_sub(*hit) >= self.span) + { + self.hits.pop_front(); + } + } + + /// Whether another event may happen now. + pub fn open(&mut self, now: Duration) -> bool { + self.trim(now); + self.hits.len() < self.max + } + + pub fn record(&mut self, now: Duration) { + self.trim(now); + self.hits.push_back(now); + } + + pub fn is_idle(&mut self, now: Duration) -> bool { + self.trim(now); + self.hits.is_empty() + } +} + +/// `rate` events a second, with room for `burst` at once. +#[derive(Debug)] +pub(crate) struct Bucket { + rate: f64, + burst: f64, + tokens: f64, + at: Duration, +} + +impl Bucket { + pub fn new(rate: f64, burst: f64, now: Duration) -> Bucket { + Bucket { + rate, + burst, + tokens: burst, + at: now, + } + } + + /// Takes one token, or says there is none. + pub fn take(&mut self, now: Duration) -> bool { + let passed = now.saturating_sub(self.at).as_secs_f64(); + self.at = now; + self.tokens = (self.tokens + passed * self.rate).min(self.burst); + if self.tokens >= 1.0 { + self.tokens -= 1.0; + true + } else { + false + } + } +} + +/// How many WebSockets are open, in all and per device. +#[derive(Debug, Default)] +pub(crate) struct Connections { + per_device: HashMap, + total: usize, +} + +pub(crate) const PER_DEVICE: usize = 4; +pub(crate) const IN_ALL: usize = 16; + +/// Holds one place among the open sockets until it is dropped. +pub(crate) struct Permit { + connections: Arc>, + device: String, +} + +impl Connections { + pub fn acquire(connections: &Arc>, device: &str) -> Option { + let mut inner = connections.lock().unwrap_or_else(|e| e.into_inner()); + let count = inner.per_device.get(device).copied().unwrap_or(0); + if count >= PER_DEVICE || inner.total >= IN_ALL { + return None; + } + inner.per_device.insert(device.to_string(), count + 1); + inner.total += 1; + Some(Permit { + connections: connections.clone(), + device: device.to_string(), + }) + } +} + +impl Drop for Permit { + fn drop(&mut self) { + let mut inner = self.connections.lock().unwrap_or_else(|e| e.into_inner()); + inner.total = inner.total.saturating_sub(1); + if let Some(count) = inner.per_device.get_mut(&self.device) { + *count -= 1; + if *count == 0 { + inner.per_device.remove(&self.device); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn secs(n: u64) -> Duration { + Duration::from_secs(n) + } + + #[test] + fn a_window_forgets_events_older_than_its_span() { + let mut window = Window::new(secs(60), 2); + window.record(secs(0)); + window.record(secs(10)); + assert!(!window.open(secs(30))); + assert!(window.open(secs(60))); + assert!(window.is_idle(secs(71))); + } + + #[test] + fn a_bucket_allows_a_burst_then_the_rate() { + let mut bucket = Bucket::new(20.0, 40.0, secs(0)); + assert_eq!((0..40).filter(|_| bucket.take(secs(0))).count(), 40); + assert!(!bucket.take(secs(0))); + // A tenth of a second brings two tokens. + let later = Duration::from_millis(100); + assert!(bucket.take(later) && bucket.take(later) && !bucket.take(later)); + } + + #[test] + fn sockets_are_counted_per_device_and_in_all() { + let connections = Arc::new(Mutex::new(Connections::default())); + let held: Vec<_> = (0..PER_DEVICE) + .map(|_| Connections::acquire(&connections, "a").expect("room")) + .collect(); + assert!(Connections::acquire(&connections, "a").is_none()); + let others: Vec<_> = (0..IN_ALL - PER_DEVICE) + .map(|n| Connections::acquire(&connections, &format!("d{}", n / PER_DEVICE)).expect("room")) + .collect(); + assert!(Connections::acquire(&connections, "z").is_none()); + drop(held); + assert!(Connections::acquire(&connections, "z").is_some()); + drop(others); + } +} diff --git a/crates/azazel-remote/src/policy.rs b/crates/azazel-remote/src/policy.rs new file mode 100644 index 00000000..93b3a16a --- /dev/null +++ b/crates/azazel-remote/src/policy.rs @@ -0,0 +1,224 @@ +//! What each access level may send. The server checks every command before it reaches the +//! session; a refusal is an error response with the command's id. +//! +//! The check reads the command as JSON, by its `type`, so that a command the protocol gains later +//! is refused to a viewer until it is listed here. + +use azazel_protocol::Command; +use serde_json::Value; + +use crate::Access; + +/// The commands a viewer may send: they read, and change nothing. +const VIEW: &[&str] = &[ + "attach", + "get_state", + "get_messages", + "get_agent_messages", + "get_tree", + "get_usage", + "list_models", + "list_roles", + "list_commands", +]; + +/// The slash commands a browser may run: they only report. +const COMMANDS: &[&str] = &["cost", "context", "session", "tools", "todo", "rules", "doctor"]; + +/// Whether a device with `access` may send `command`. +pub fn policy(access: Access, command: &Command, allow_bypass: bool) -> Result<(), String> { + let value = serde_json::to_value(command).map_err(|e| e.to_string())?; + check(access, &value, allow_bypass) +} + +/// [`policy`] for a command as the JSON object a client sent. +pub fn check(access: Access, command: &Value, allow_bypass: bool) -> Result<(), String> { + let Some(kind) = command.get("type").and_then(Value::as_str) else { + return Err("a command has a `type`".to_string()); + }; + if access == Access::View { + return match VIEW.contains(&kind) { + true => Ok(()), + false => Err(format!("this is a view link: `{kind}` needs a control link")), + }; + } + let given = |member: &str| command.get(member).is_some_and(|value| !value.is_null()); + let text = |member: &str| command.get(member).and_then(Value::as_str).unwrap_or_default(); + let refused = |why: &str| Err(format!("`{kind}` is not available from a browser: {why}")); + match kind { + "shell" => refused("it would run a command on this machine"), + "export" if given("path") => refused("it would write a file on this machine"), + "resume_session" if given("path") => refused("it would read a file on this machine"), + "save_preset" => refused("it would change the configuration"), + "set_role" if !matches!(text("save"), "" | "session") => { + refused("it would change the configuration; use `save: session`") + } + "set_mode" if text("mode").eq_ignore_ascii_case("bypass") && !allow_bypass => { + refused("`bypass` is off; set `remote.allow_bypass` to allow it") + } + "run_command" => { + let name = text("name").trim_start_matches('/').to_ascii_lowercase(); + if COMMANDS.contains(&name.as_str()) || name.starts_with("skill:") { + Ok(()) + } else { + refused(&format!( + "the command `{name}` is not on the list a browser may run" + )) + } + } + _ => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + /// Every command the protocol knows, from its schema. + fn every_type() -> Vec { + let schema: Value = serde_json::from_str(include_str!("../../../docs/rpc.schema.json")).unwrap(); + schema["$defs"]["Request"]["oneOf"] + .as_array() + .unwrap() + .iter() + .map(|variant| { + variant["properties"]["type"]["const"] + .as_str() + .unwrap() + .to_string() + }) + .collect() + } + + #[test] + fn a_viewer_may_only_read() { + let types = every_type(); + assert!(types.len() > 40); + let mut allowed: Vec<&str> = types + .iter() + .map(String::as_str) + .filter(|kind| check(Access::View, &json!({ "type": kind }), false).is_ok()) + .collect(); + allowed.sort_unstable(); + let mut expected: Vec<&str> = VIEW + .iter() + .copied() + // Lane A adds `get_agent_messages` to the protocol; before that it is not in the schema. + .filter(|kind| types.iter().any(|known| known == kind)) + .collect(); + expected.sort_unstable(); + assert_eq!(allowed, expected); + assert!(!allowed.contains(&"prompt") && !allowed.contains(&"approval_response")); + } + + #[test] + fn a_controller_may_send_everything_but_what_reaches_the_machine() { + let refused: Vec = every_type() + .into_iter() + .filter(|kind| check(Access::Control, &json!({ "type": kind }), false).is_err()) + // `run_command` without a name is refused as an unknown command. + .collect(); + assert_eq!(refused, ["shell", "save_preset", "run_command"]); + } + + #[test] + fn what_a_command_carries_decides_for_the_commands_that_are_sometimes_fine() { + let control = |command: Value, bypass: bool| check(Access::Control, &command, bypass); + assert!(control(json!({ "type": "export" }), false).is_ok()); + assert!(control(json!({ "type": "export", "format": "html", "path": null }), false).is_ok()); + assert!(control(json!({ "type": "export", "path": "/tmp/a.html" }), false).is_err()); + assert!(control(json!({ "type": "resume_session", "session_id": "abc" }), false).is_ok()); + assert!(control(json!({ "type": "resume_session", "path": "x.jsonl" }), false).is_err()); + assert!( + control( + json!({ "type": "set_role", "role": "default", "save": "session" }), + false + ) + .is_ok() + ); + assert!(control(json!({ "type": "set_role", "role": "default" }), false).is_ok()); + assert!( + control( + json!({ "type": "set_role", "role": "default", "save": "home" }), + false + ) + .is_err() + ); + assert!( + control( + json!({ "type": "set_role", "role": "default", "save": "project" }), + false + ) + .is_err() + ); + assert!(control(json!({ "type": "set_mode", "mode": "auto" }), false).is_ok()); + assert!(control(json!({ "type": "set_mode", "mode": "Bypass" }), false).is_err()); + assert!(control(json!({ "type": "set_mode", "mode": "bypass" }), true).is_ok()); + } + + #[test] + fn a_browser_runs_the_slash_commands_that_only_report() { + let run = |name: &str| { + check( + Access::Control, + &json!({ "type": "run_command", "name": name }), + false, + ) + }; + for name in [ + "cost", + "context", + "session", + "tools", + "todo", + "rules", + "doctor", + "/cost", + "skill:review", + ] { + assert!(run(name).is_ok(), "{name}"); + } + for name in [ + "trust", + "add-dir", + "hooks", + "forget-approvals", + "login", + "skill", + "", + ] { + assert!(run(name).is_err(), "{name}"); + } + } + + #[test] + fn a_message_without_a_type_is_not_a_command() { + assert!(check(Access::Control, &json!({ "text": "hi" }), false).is_err()); + assert!(check(Access::View, &json!("prompt"), false).is_err()); + } + + #[test] + fn the_typed_form_gives_the_same_answer() { + let prompt = Command::Prompt { + text: "hi".into(), + images: Vec::new(), + request_id: None, + }; + assert!(policy(Access::View, &prompt, false).is_err()); + assert!(policy(Access::Control, &prompt, false).is_ok()); + assert!( + policy( + Access::Control, + &Command::Shell { + command: "ls".into(), + share: true + }, + false + ) + .is_err() + ); + assert!(policy(Access::View, &Command::GetState, false).is_ok()); + } +} diff --git a/crates/azazel-remote/src/qr.rs b/crates/azazel-remote/src/qr.rs new file mode 100644 index 00000000..3761c31b --- /dev/null +++ b/crates/azazel-remote/src/qr.rs @@ -0,0 +1,55 @@ +//! QR codes for pairing links. + +use qrcodegen::{QrCode, QrCodeEcc}; + +/// The modules of the code for `text`, `true` for a dark one, without the quiet zone. +pub fn qr_matrix(text: &str) -> Vec> { + // A link is far below the capacity of the largest code; the fallback keeps the signature total. + let Ok(code) = QrCode::encode_text(text, QrCodeEcc::Medium) else { + return Vec::new(); + }; + (0..code.size()) + .map(|y| (0..code.size()).map(|x| code.get_module(x, y)).collect()) + .collect() +} + +/// The code as an SVG image with a four-module quiet zone, in black on white. +pub fn qr_svg(text: &str) -> String { + let matrix = qr_matrix(text); + let size = matrix.len() + 8; + let mut path = String::new(); + for (y, row) in matrix.iter().enumerate() { + for (x, dark) in row.iter().enumerate() { + if *dark { + path.push_str(&format!("M{},{}h1v1h-1z", x + 4, y + 4)); + } + } + } + format!( + "\ +" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_matrix_is_square_with_the_finder_patterns_in_three_corners() { + let matrix = qr_matrix("https://example.com/#pair=abc"); + let size = matrix.len(); + assert!(size >= 21 && matrix.iter().all(|row| row.len() == size)); + for (x, y) in [(0, 0), (size - 7, 0), (0, size - 7)] { + assert!(matrix[y][x] && matrix[y + 6][x + 6] && !matrix[y + 1][x + 1]); + } + } + + #[test] + fn the_svg_draws_every_dark_module() { + let svg = qr_svg("hello"); + let dark: usize = qr_matrix("hello").iter().flatten().filter(|d| **d).count(); + assert_eq!(svg.matches('M').count(), dark); + assert!(svg.starts_with(" Result { + let bad = || format!("`{url}` is not an address such as https://remote.example.com"); + let (scheme, rest) = url.trim().split_once("://").ok_or_else(bad)?; + let scheme = scheme.to_ascii_lowercase(); + let https = match scheme.as_str() { + "https" => true, + "http" => false, + _ => return Err(bad()), + }; + let host = rest + .split(['/', '?', '#']) + .next() + .unwrap_or_default() + .to_ascii_lowercase(); + if host.is_empty() || host.contains('@') || host.contains(char::is_whitespace) { + return Err(bad()); + } + Ok(Public { + origin: format!("{scheme}://{host}"), + host, + https, + }) +} + +/// What the handlers of requests and sockets share. +pub(crate) struct Shared { + pub auth: Auth, + pub sessions: Arc, + pub allow_bypass: bool, + pub port: u16, + pub bind: IpAddr, + pub public: RwLock>, + pub connections: Arc>, + pub cancel: CancellationToken, +} + +impl Shared { + /// The hosts this machine is reached by directly. + fn local_hosts(&self) -> Vec { + let mut hosts = vec![ + format!("127.0.0.1:{}", self.port), + format!("localhost:{}", self.port), + format!("[::1]:{}", self.port), + ]; + if !self.bind.is_unspecified() { + hosts.push(SocketAddr::new(self.bind, self.port).to_string()); + } + hosts + } + + fn public(&self) -> Option { + self.public.read().unwrap_or_else(|e| e.into_inner()).clone() + } + + /// Whether a `Host` header names this server. Anything else may be a page of another site + /// that was made to resolve to this machine. + pub fn host_ok(&self, host: &str) -> bool { + let host = host.trim().to_ascii_lowercase(); + self.local_hosts().contains(&host) || self.public().is_some_and(|public| public.host == host) + } + + /// Whether a request to `host` came through an https address (the cookie is then `Secure`). + pub fn is_https_host(&self, host: &str) -> bool { + self.public() + .is_some_and(|public| public.https && public.host == host) + } + + /// Whether an `Origin` header is one of this server's own pages. + pub fn origin_ok(&self, origin: &str) -> bool { + let origin = origin.trim().to_ascii_lowercase(); + self.local_hosts() + .iter() + .any(|host| origin == format!("http://{host}")) + || self.public().is_some_and(|public| public.origin == origin) + } + + /// Where the page of this server is: the tunnel when there is one. + pub fn origin(&self) -> String { + match self.public() { + Some(public) => public.origin, + None => format!("http://{}", SocketAddr::new(self.bind, self.port)), + } + } + + pub fn link(&self, access: Access, origin: &str) -> Link { + let (secret, expires) = self.auth.mint_link(access); + Link { + url: format!("{origin}/#pair={secret}"), + access, + expires: rfc3339(expires), + } + } +} + +pub(crate) fn rfc3339(time: SystemTime) -> String { + jiff::Timestamp::try_from(time) + .map(|timestamp| timestamp.to_string()) + .unwrap_or_default() +} + +pub struct Server { + shared: Arc, + addr: SocketAddr, + task: JoinHandle<()>, +} + +impl Server { + /// Binds the port of `options` (or the next nine when it is taken) and starts serving. + pub async fn start(options: Options, sessions: Arc) -> io::Result { + Server::start_with_clock(options, sessions, Arc::new(SystemClock)).await + } + + pub(crate) async fn start_with_clock( + options: Options, + sessions: Arc, + clock: Arc, + ) -> io::Result { + let public = match options.public_url.as_deref().filter(|url| !url.trim().is_empty()) { + Some(url) => Some(parse_public(url).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?), + None => None, + }; + let tries = if options.port == 0 { 1 } else { PORT_TRIES }; + let mut last = None; + let mut bound = None; + for step in 0..tries { + let Some(port) = options.port.checked_add(step) else { + break; + }; + match TcpListener::bind((options.bind, port)).await { + Ok(listener) => { + bound = Some(listener); + break; + } + Err(e) if e.kind() == io::ErrorKind::AddrInUse => last = Some(e), + Err(e) => return Err(e), + } + } + let Some(listener) = bound else { + return Err(last.unwrap_or_else(|| io::Error::other("no port to listen on"))); + }; + let addr = listener.local_addr()?; + let shared = Arc::new(Shared { + auth: Auth::new(clock, options.link_ttl, options.device_ttl), + sessions, + allow_bypass: options.allow_bypass, + port: addr.port(), + bind: options.bind, + public: RwLock::new(public), + connections: Arc::new(Mutex::new(Connections::default())), + cancel: CancellationToken::new(), + }); + let task = tokio::spawn(accept(listener, shared.clone())); + Ok(Server { shared, addr, task }) + } + + /// The port it listens on, which is not the one asked for when that was taken or 0. + pub fn port(&self) -> u16 { + self.addr.port() + } + + /// The addresses it can be reached at: the local one, and the public one when set. + pub fn urls(&self) -> Vec { + let mut urls = vec![format!("http://{}", self.addr)]; + if let Some(public) = self.shared.public() { + urls.push(public.origin); + } + urls + } + + /// Accepts the address of a tunnel or proxy that now leads here: links point to it, and its + /// host and origin are accepted from now on. + pub fn set_public_url(&self, url: &str) -> Result<(), String> { + let public = parse_public(url)?; + *self.shared.public.write().unwrap_or_else(|e| e.into_inner()) = Some(public); + Ok(()) + } + + /// A new single-use link, for the public address when there is one. + pub fn link(&self, access: Access) -> Link { + self.shared.link(access, &self.shared.origin()) + } + + /// Signs every device out and voids every link. + pub fn revoke_all(&self) { + self.shared.auth.revoke_all(); + } + + /// Stops accepting, closes every socket and waits until that is done. + pub async fn shutdown(self) { + self.shared.cancel.cancel(); + let _ = self.task.await; + } +} + +async fn accept(listener: TcpListener, shared: Arc) { + loop { + let accepted = tokio::select! { + _ = shared.cancel.cancelled() => return, + accepted = listener.accept() => accepted, + }; + let Ok((stream, peer)) = accepted else { + // A connection that was reset before it was accepted, or no file handles left: try again. + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + continue; + }; + let shared = shared.clone(); + tokio::spawn(async move { + let cancel = shared.cancel.clone(); + let peer = peer.ip(); + let service = service_fn(move |req| { + let shared = shared.clone(); + async move { Ok::<_, std::convert::Infallible>(crate::http::handle(shared, peer, req).await) } + }); + let connection = http1::Builder::new() + .timer(TokioTimer::new()) + .header_read_timeout(std::time::Duration::from_secs(10)) + .serve_connection(TokioIo::new(stream), service) + .with_upgrades(); + tokio::select! { + _ = cancel.cancelled() => {} + _ = connection => {} + } + }); + } +} diff --git a/crates/azazel-remote/src/testing.rs b/crates/azazel-remote/src/testing.rs new file mode 100644 index 00000000..e7dfd0d5 --- /dev/null +++ b/crates/azazel-remote/src/testing.rs @@ -0,0 +1,27 @@ +//! Stand-ins for the tests of this crate. + +use std::sync::Mutex; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::limits::Clock; + +/// A clock the test moves by hand. +pub(crate) struct FakeClock(Mutex); + +impl Default for FakeClock { + fn default() -> FakeClock { + FakeClock(Mutex::new(UNIX_EPOCH + Duration::from_secs(1_800_000_000))) + } +} + +impl FakeClock { + pub fn advance(&self, by: Duration) { + *self.0.lock().unwrap_or_else(|e| e.into_inner()) += by; + } +} + +impl Clock for FakeClock { + fn now(&self) -> SystemTime { + *self.0.lock().unwrap_or_else(|e| e.into_inner()) + } +} diff --git a/crates/azazel-remote/src/ws.rs b/crates/azazel-remote/src/ws.rs new file mode 100644 index 00000000..bc758ca7 --- /dev/null +++ b/crates/azazel-remote/src/ws.rs @@ -0,0 +1,129 @@ +//! One WebSocket: the session's lines go out as text messages, the client's messages go in as +//! lines, after the policy has seen them. + +use std::sync::Arc; +use std::time::Duration; + +use azazel_protocol::{Frame, Response}; +use futures::{SinkExt, StreamExt}; +use serde_json::Value; +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::protocol::CloseFrame; +use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; + +use crate::auth::Device; +use crate::limits::{Bucket, Connections, since_epoch}; +use crate::policy; +use crate::server::Shared; + +/// Frames that may wait for a client that reads slowly; a client that lets this many pile up is +/// cut off and resumes with `since`. +pub(crate) const QUEUE: usize = 4096; +/// How long one message may take to reach the client. +const SEND_LIMIT: Duration = Duration::from_secs(30); + +async fn close(socket: &mut WebSocketStream, code: u16, reason: &str) { + let reason: String = reason.chars().take(100).collect(); + let frame = CloseFrame { + code: CloseCode::from(code), + reason: reason.into(), + }; + let _ = tokio::time::timeout(Duration::from_secs(5), socket.close(Some(frame))).await; +} + +/// A refusal the client reads like any other response. +fn refusal(id: Value, why: impl Into) -> Message { + let line = serde_json::to_string(&Frame::Response(Response::err(id, why))).unwrap_or_default(); + Message::text(line) +} + +pub(crate) async fn run( + shared: Arc, + mut socket: WebSocketStream, + device: Option, + id: String, +) where + S: AsyncRead + AsyncWrite + Unpin, +{ + let Some(device) = device else { + return close(&mut socket, 4401, "not signed in").await; + }; + let Some(_place) = Connections::acquire(&shared.connections, &device.id) else { + return close(&mut socket, 4409, "too many connections").await; + }; + let mut conn = match shared.sessions.open(&id).await { + Ok(conn) => conn, + Err(why) => return close(&mut socket, 4404, &why).await, + }; + let mut bucket = Bucket::new(20.0, 40.0, since_epoch(shared.auth.now())); + let left = device + .expires + .duration_since(shared.auth.now()) + .unwrap_or_default(); + let expiry = tokio::time::sleep(left); + tokio::pin!(expiry); + loop { + tokio::select! { + _ = device.cancel.cancelled() => return close(&mut socket, 4401, "signed out").await, + _ = &mut expiry => return close(&mut socket, 4401, "the device has expired").await, + _ = shared.cancel.cancelled() => return close(&mut socket, 1001, "the server stopped").await, + line = conn.frames.recv() => { + let Some(line) = line else { + return close(&mut socket, 1000, "the session ended").await; + }; + if conn.frames.len() >= QUEUE { + return close(&mut socket, 4408, "too slow: reconnect and attach with `since`").await; + } + match tokio::time::timeout(SEND_LIMIT, socket.send(Message::text(line))).await { + Ok(Ok(())) => {} + _ => return, + } + } + message = socket.next() => { + let message = match message { + None | Some(Ok(Message::Close(_))) => return, + Some(Err(tokio_tungstenite::tungstenite::Error::Capacity(_))) => { + return close(&mut socket, 1009, "the message is too large").await; + } + Some(Err(_)) => return, + Some(Ok(message)) => message, + }; + let text = match message { + Message::Text(text) => text, + Message::Binary(_) => return close(&mut socket, 1003, "send text").await, + // Pings are answered by the socket itself. + _ => continue, + }; + let Ok(value) = serde_json::from_str::(text.as_str()) else { + if socket.send(refusal(Value::Null, "not JSON: a message is one command as a JSON object")).await.is_err() { + return; + } + continue; + }; + let id = value.get("id").cloned().unwrap_or(Value::Null); + let verdict = if !value.is_object() { + Err("a command is a JSON object".to_string()) + } else if !bucket.take(since_epoch(shared.auth.now())) { + Err("too many commands at once: slow down".to_string()) + } else { + policy::check(device.access, &value, shared.allow_bypass) + }; + match verdict { + Ok(()) => { + // One line: the session reads its commands line by line. + if conn.commands.send(value.to_string()).await.is_err() { + return close(&mut socket, 1000, "the session ended").await; + } + } + Err(why) => { + if socket.send(refusal(id, why)).await.is_err() { + return; + } + } + } + } + } + } +} diff --git a/docs/remote.md b/docs/remote.md index 9ac77114..8abb230e 100644 --- a/docs/remote.md +++ b/docs/remote.md @@ -115,9 +115,10 @@ Signs this device out and clears the cookie. Answer `204`. Its WebSockets close ### The WebSocket -`GET /api/ws/{id}` with the usual upgrade headers (`Upgrade: websocket`, `Sec-WebSocket-Version: 13`, a key). It -needs a device. A failed check before the upgrade is the plain HTTP answer (`401`, `403`, `421`, `429`); a failure -after it is a close code. +`GET /api/ws/{id}` with the usual upgrade headers (`Upgrade: websocket`, `Sec-WebSocket-Version: 13`, a key). A +request with a wrong `Host` or `Origin` gets the plain HTTP answer (`421`, `403`) and no upgrade. Everything else is +accepted and, when it fails, closed with a code, because a browser cannot read the status of a refused upgrade: no +device is `4401`, an unknown session `4404`, too many sockets `4409`. Once upgraded: From c67973c33d5ee703c034bad00620369dac31c43a Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:23:31 +0000 Subject: [PATCH 06/27] azazel-remote: integration tests over real sockets --- crates/azazel-remote/Cargo.toml | 3 + crates/azazel-remote/tests/it/common.rs | 196 +++++++++++++++++ crates/azazel-remote/tests/it/http.rs | 274 ++++++++++++++++++++++++ crates/azazel-remote/tests/it/main.rs | 6 + crates/azazel-remote/tests/it/socket.rs | 159 ++++++++++++++ 5 files changed, 638 insertions(+) create mode 100644 crates/azazel-remote/tests/it/common.rs create mode 100644 crates/azazel-remote/tests/it/http.rs create mode 100644 crates/azazel-remote/tests/it/main.rs create mode 100644 crates/azazel-remote/tests/it/socket.rs diff --git a/crates/azazel-remote/Cargo.toml b/crates/azazel-remote/Cargo.toml index ea99ddc6..284d6dd1 100644 --- a/crates/azazel-remote/Cargo.toml +++ b/crates/azazel-remote/Cargo.toml @@ -35,3 +35,6 @@ flate2.workspace = true sha2.workspace = true [dev-dependencies] +futures.workspace = true +tokio = { workspace = true, features = ["test-util"] } +tokio-tungstenite.workspace = true diff --git a/crates/azazel-remote/tests/it/common.rs b/crates/azazel-remote/tests/it/common.rs new file mode 100644 index 00000000..82916cdf --- /dev/null +++ b/crates/azazel-remote/tests/it/common.rs @@ -0,0 +1,196 @@ +use std::collections::HashMap; +use std::net::{IpAddr, Ipv4Addr}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use async_trait::async_trait; +use azazel_remote::{Access, Conn, Kind, Options, Server, SessionInfo, Sessions}; +use futures::{SinkExt, StreamExt}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::sync::mpsc; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::protocol::Message; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; + +pub const WAIT: Duration = Duration::from_secs(10); + +/// One session, `s1`: what it is sent comes out of `sent`, and `push` makes it say something. +pub struct Fake { + sent: mpsc::UnboundedSender, + open: Mutex>>, +} + +impl Fake { + pub fn new() -> (Arc, mpsc::UnboundedReceiver) { + let (sent, received) = mpsc::unbounded_channel(); + let fake = Arc::new(Fake { + sent, + open: Mutex::new(Vec::new()), + }); + (fake, received) + } + + pub async fn push(&self, line: &str) { + let open: Vec<_> = self.open.lock().unwrap().clone(); + for frames in open { + let _ = frames.send(line.to_string()).await; + } + } +} + +#[async_trait] +impl Sessions for Fake { + async fn list(&self) -> Vec { + vec![SessionInfo { + id: "s1".into(), + name: Some("build".into()), + kind: Kind::Background, + state: "idle".into(), + cwd: "/work".into(), + cost_usd: Some(0.5), + mode: Some("manual".into()), + started: "2026-11-15T10:00:00Z".into(), + }] + } + + async fn open(&self, id: &str) -> Result { + if id != "s1" { + return Err(format!("no session {id}")); + } + let (frames_tx, frames) = mpsc::channel(64); + let (commands, mut commands_rx) = mpsc::channel::(64); + frames_tx + .send(r#"{"type":"hello","protocol":1,"version":"test"}"#.into()) + .await + .unwrap(); + self.open.lock().unwrap().push(frames_tx); + let sent = self.sent.clone(); + tokio::spawn(async move { + while let Some(line) = commands_rx.recv().await { + let _ = sent.send(line); + } + }); + Ok(Conn { frames, commands }) + } +} + +pub fn options() -> Options { + Options { + bind: IpAddr::V4(Ipv4Addr::LOCALHOST), + port: 0, + public_url: None, + link_ttl: Duration::from_secs(900), + device_ttl: Duration::from_secs(3600), + redact: true, + allow_bypass: false, + } +} + +pub async fn server() -> (Server, Arc, mpsc::UnboundedReceiver) { + let (fake, received) = Fake::new(); + let server = Server::start(options(), fake.clone()).await.unwrap(); + (server, fake, received) +} + +/// The secret of a link. +pub fn secret(url: &str) -> String { + url.split_once("#pair=").unwrap().1.to_string() +} + +pub struct Answer { + pub status: u16, + pub headers: HashMap, + pub body: Vec, +} + +impl Answer { + pub fn text(&self) -> String { + String::from_utf8_lossy(&self.body).into_owned() + } + + pub fn json(&self) -> serde_json::Value { + serde_json::from_slice(&self.body).unwrap() + } +} + +/// One HTTP/1.1 request on a connection of its own. `Host` is the server's unless given. +pub async fn request(port: u16, method: &str, path: &str, headers: &[(&str, &str)], body: &str) -> Answer { + let mut head = format!("{method} {path} HTTP/1.1\r\nConnection: close\r\nContent-Length: {}\r\n", body.len()); + if !headers.iter().any(|(name, _)| name.eq_ignore_ascii_case("host")) { + head.push_str(&format!("Host: 127.0.0.1:{port}\r\n")); + } + for (name, value) in headers { + head.push_str(&format!("{name}: {value}\r\n")); + } + head.push_str("\r\n"); + let mut stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + stream.write_all(head.as_bytes()).await.unwrap(); + stream.write_all(body.as_bytes()).await.unwrap(); + let mut raw = Vec::new(); + tokio::time::timeout(WAIT, stream.read_to_end(&mut raw)).await.unwrap().unwrap(); + let split = raw.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); + let head = String::from_utf8_lossy(&raw[..split]).into_owned(); + let mut lines = head.lines(); + let status = lines.next().unwrap().split_whitespace().nth(1).unwrap().parse().unwrap(); + let headers = lines + .filter_map(|line| line.split_once(':')) + .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string())) + .collect(); + Answer { + status, + headers, + body: raw[split + 4..].to_vec(), + } +} + +/// Pairs with a new link and returns the device's bearer token. +pub async fn pair(server: &Server, access: Access) -> String { + let link = server.link(access); + let body = serde_json::json!({ "secret": secret(&link.url), "bearer": true }).to_string(); + let answer = request(server.port(), "POST", "/api/pair", &[("X-Azazel", "1")], &body).await; + assert_eq!(answer.status, 200, "{}", answer.text()); + answer.json()["token"].as_str().unwrap().to_string() +} + +pub type Socket = WebSocketStream>; + +pub async fn connect(port: u16, id: &str, token: Option<&str>) -> Socket { + let mut request = format!("ws://127.0.0.1:{port}/api/ws/{id}").into_client_request().unwrap(); + request.headers_mut().insert("origin", format!("http://127.0.0.1:{port}").parse().unwrap()); + if let Some(token) = token { + request.headers_mut().insert("authorization", format!("Bearer {token}").parse().unwrap()); + } + tokio_tungstenite::connect_async(request).await.unwrap().0 +} + +/// The next text message, as JSON. +pub async fn next_json(socket: &mut Socket) -> serde_json::Value { + loop { + match tokio::time::timeout(WAIT, socket.next()).await.expect("a message") { + Some(Ok(Message::Text(text))) => return serde_json::from_str(text.as_str()).unwrap(), + Some(Ok(Message::Ping(_) | Message::Pong(_))) => {} + other => panic!("expected a text message, got {other:?}"), + } + } +} + +/// The code the server closes with. +pub async fn close_code(socket: &mut Socket) -> u16 { + loop { + match tokio::time::timeout(WAIT, socket.next()).await.expect("a close") { + Some(Ok(Message::Close(Some(frame)))) => return u16::from(frame.code), + Some(Ok(Message::Text(_) | Message::Ping(_) | Message::Pong(_))) => {} + other => panic!("expected a close, got {other:?}"), + } + } +} + +pub async fn send(socket: &mut Socket, value: serde_json::Value) { + socket.send(Message::text(value.to_string())).await.unwrap(); +} + +pub async fn sent(received: &mut mpsc::UnboundedReceiver) -> serde_json::Value { + let line = tokio::time::timeout(WAIT, received.recv()).await.expect("a command").unwrap(); + serde_json::from_str(&line).unwrap() +} diff --git a/crates/azazel-remote/tests/it/http.rs b/crates/azazel-remote/tests/it/http.rs new file mode 100644 index 00000000..e4b4afb8 --- /dev/null +++ b/crates/azazel-remote/tests/it/http.rs @@ -0,0 +1,274 @@ +use std::io::Read; + +use azazel_remote::Access; + +use crate::common::*; + +const GZIP: (&str, &str) = ("Accept-Encoding", "gzip"); + +#[tokio::test] +async fn the_page_is_public_and_comes_gzipped_only_to_a_browser_that_accepts_it() { + let (server, ..) = server().await; + let port = server.port(); + let plain = request(port, "GET", "/", &[], "").await; + assert_eq!(plain.status, 200); + assert!(plain.text().contains("= 40); +} + +#[tokio::test] +async fn revoking_closes_the_sockets_and_the_device_stays_out() { + let (server, ..) = server().await; + let port = server.port(); + let token = pair(&server, Access::Control).await; + let mut socket = connect(port, "s1", Some(&token)).await; + next_json(&mut socket).await; + server.revoke_all(); + assert_eq!(close_code(&mut socket).await, 4401); + let mut again = connect(port, "s1", Some(&token)).await; + assert_eq!(close_code(&mut again).await, 4401); +} + +#[tokio::test] +async fn a_device_has_four_sockets() { + let (server, ..) = server().await; + let port = server.port(); + let token = pair(&server, Access::Control).await; + let mut held = Vec::new(); + for _ in 0..4 { + let mut socket = connect(port, "s1", Some(&token)).await; + next_json(&mut socket).await; + held.push(socket); + } + let mut fifth = connect(port, "s1", Some(&token)).await; + assert_eq!(close_code(&mut fifth).await, 4409); + // Another device is not held up by it. + let other = pair(&server, Access::View).await; + let mut socket = connect(port, "s1", Some(&other)).await; + assert_eq!(next_json(&mut socket).await["type"], "hello"); +} + +#[tokio::test] +async fn stopping_the_server_closes_every_socket() { + let (server, ..) = server().await; + let token = pair(&server, Access::Control).await; + let mut socket = connect(server.port(), "s1", Some(&token)).await; + next_json(&mut socket).await; + let waiting = tokio::spawn(async move { close_code(&mut socket).await }); + server.shutdown().await; + assert_eq!(waiting.await.unwrap(), 1001); +} From 9765b2aea84c114b81a3a102faf4c9e076e9f6a4 Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:38:50 +0000 Subject: [PATCH 07/27] Shared download helpers; remote.access setting --- Cargo.lock | 1 + crates/azazel-cli/Cargo.toml | 6 ++++- crates/azazel-core/src/config.rs | 4 ++++ crates/azazel-core/src/settings.rs | 3 ++- crates/azazel-tools/src/lsp/install.rs | 27 ++------------------- crates/azazel-tools/src/util.rs | 33 ++++++++++++++++++++++++++ xtask/docs-check/Cargo.toml | 2 +- 7 files changed, 48 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f08dfc6e..a5650386 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -973,6 +973,7 @@ dependencies = [ "azazel-media", "azazel-memory", "azazel-protocol", + "azazel-remote", "azazel-repomap", "azazel-team", "azazel-tools", diff --git a/crates/azazel-cli/Cargo.toml b/crates/azazel-cli/Cargo.toml index 144abb44..2b8f6af5 100644 --- a/crates/azazel-cli/Cargo.toml +++ b/crates/azazel-cli/Cargo.toml @@ -67,6 +67,9 @@ images = ["azazel-tui/images"] diagrams = ["images", "dep:mermaid-rs-renderer", "dep:resvg"] # Background sessions (`azazel bg`, `ps`, `logs`, `attach`, `kill`) on local sockets. detach = ["dep:interprocess", "dep:process-wrap", "dep:winsafe"] +# `azazel remote`: a web page and a WebSocket server that follow and steer background sessions from a +# browser or a phone. +remote = ["dep:azazel-remote", "detach"] test-support = ["azazel-ai/test-support"] [dependencies] @@ -82,6 +85,7 @@ azazel-mcp = { workspace = true, optional = true } azazel-memory = { workspace = true, optional = true } azazel-repomap = { workspace = true, optional = true } azazel-lua = { workspace = true, optional = true } +azazel-remote = { workspace = true, optional = true } azazel-browser = { workspace = true, optional = true } azazel-media = { workspace = true, optional = true } agent-client-protocol = { workspace = true, optional = true } @@ -146,7 +150,7 @@ flate2.workspace = true assert_cmd.workspace = true # The package depends on itself so that its tests, and the `azazel` binary they drive, are built # with the scripted mock provider, and so that the opt-in diagram drawing is tested and linted. -azazel-cli = { path = ".", features = ["test-support", "diagrams"] } +azazel-cli = { path = ".", features = ["test-support", "diagrams", "remote"] } agent-client-protocol.workspace = true dunce.workspace = true rmcp.workspace = true diff --git a/crates/azazel-core/src/config.rs b/crates/azazel-core/src/config.rs index 76962b73..227dd90b 100644 --- a/crates/azazel-core/src/config.rs +++ b/crates/azazel-core/src/config.rs @@ -321,6 +321,9 @@ config_table!(RemoteConfig { /// The port `azazel remote` listens on. It is fixed because an installed page belongs to its /// origin, port included; 0 lets the system choose. port: u16 = 7420, + /// How `azazel remote --share` and `/remote` reach the server from another device: a + /// Cloudflare quick tunnel, or Tailscale. + access: RemoteAccess = RemoteAccess::Cloudflare, /// The address of your own tunnel or reverse proxy in front of the server /// (`https://remote.example.com`): the origin of the pairing links, and an origin the server /// accepts. `azazel remote --tunnel` sets it for the run. @@ -649,6 +652,7 @@ config_enum!(AdvisorWhen { Off = "off", Stop = "stop" } default Off); config_enum!(SessionResume { New = "new", Last = "last" } default New); config_enum!(CacheWarming { Off = "off", Idle = "idle" } default Off); config_enum!(TelemetryExporter { Off = "off", Otlp = "otlp", Langsmith = "langsmith" } default Off); +config_enum!(RemoteAccess { Cloudflare = "cloudflare", Tailscale = "tailscale" } default Cloudflare); config_enum!(QueueMode { One = "one", All = "all" } default One); config_enum!(Autocomplete { Words = "words", Off = "off" } default Words); config_enum!(StatusPreset { Default = "default", Minimal = "minimal", Powerline = "powerline", Lean = "lean", Full = "full" } default Default); diff --git a/crates/azazel-core/src/settings.rs b/crates/azazel-core/src/settings.rs index 3b507ea1..ee321035 100644 --- a/crates/azazel-core/src/settings.rs +++ b/crates/azazel-core/src/settings.rs @@ -13,7 +13,7 @@ use toml::{Table, Value}; use crate::config::{ AdvisorWhen, Autocomplete, CacheWarming, CheckReport, Config, DesktopNotify, DestructivePolicy, DiffView, EditorMode, GlyphSetting, ImageMode, Indicator, LspInstall, PatchMode, PermissionMode, ProcessPriority, - QueueMode, ReadGuard, SessionResume, StatusPreset, StatusSeparator, TelemetryExporter, ToolStyle, + QueueMode, ReadGuard, RemoteAccess, SessionResume, StatusPreset, StatusSeparator, TelemetryExporter, ToolStyle, WorktreeTarget, WriteSeverity, }; @@ -511,6 +511,7 @@ settings! { } Advanced / "Remote" { "remote.port": Number, "Port", "The port `azazel remote` listens on; 7420 by default, 0 lets the system choose."; + "remote.access": Choice(RemoteAccess::NAMES), "Way in", "How --share and /remote reach the server from another device: a Cloudflare quick tunnel or Tailscale."; "remote.public_url": Text, "Public address", "The address of your own tunnel or reverse proxy, such as https://remote.example.com; it becomes the link and an accepted origin."; "remote.link_minutes": Number, "Link lifetime", "Minutes a pairing link works."; "remote.device_hours": Number, "Device lifetime", "Hours a paired device stays signed in."; diff --git a/crates/azazel-tools/src/lsp/install.rs b/crates/azazel-tools/src/lsp/install.rs index 9d0a5471..d19eb1cc 100644 --- a/crates/azazel-tools/src/lsp/install.rs +++ b/crates/azazel-tools/src/lsp/install.rs @@ -390,16 +390,7 @@ fn release_asset() -> Option<(String, Archive)> { /// Fetches `url`, unpacks the executable it holds into `dir` and returns its path. async fn download(url: &str, kind: Archive, dir: &Path) -> Result { - let response = azazel_ai::tls::client() - .get(url) - .send() - .await - .and_then(|response| response.error_for_status()) - .map_err(|e| format!("could not download {url}: {e}"))?; - let bytes = response - .bytes() - .await - .map_err(|e| format!("could not download {url}: {e}"))?; + let bytes = crate::util::download(url).await?; unpack(&bytes, kind, dir) } @@ -422,21 +413,7 @@ fn unpack(bytes: &[u8], kind: Archive, dir: &Path) -> Result { .map_err(|e| format!("could not unpack rust-analyzer.exe: {e}"))?; } } - std::fs::create_dir_all(dir).map_err(|e| format!("could not create {}: {e}", dir.display()))?; - let target = dir.join(format!("rust-analyzer{}", std::env::consts::EXE_SUFFIX)); - // Written beside it and moved, so that a download cut short leaves no half program behind. - let partial = dir.join("rust-analyzer.partial"); - let written = std::fs::File::create(&partial).and_then(|mut file| file.write_all(&program)); - written.map_err(|e| format!("could not write {}: {e}", partial.display()))?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&partial, std::fs::Permissions::from_mode(0o755)) - .map_err(|e| format!("could not make {} executable: {e}", partial.display()))?; - } - std::fs::rename(&partial, &target) - .map_err(|e| format!("could not move rust-analyzer into place: {e}"))?; - Ok(target) + crate::util::install_program(&program, dir, "rust-analyzer") } #[cfg(test)] diff --git a/crates/azazel-tools/src/util.rs b/crates/azazel-tools/src/util.rs index 64763681..f82ad792 100644 --- a/crates/azazel-tools/src/util.rs +++ b/crates/azazel-tools/src/util.rs @@ -15,6 +15,39 @@ pub fn parse_input(input: Value) -> Result { serde_json::from_value(input).map_err(|e| ToolOutput::error(format!("invalid arguments: {e}"))) } +/// The bytes at `url`, for a program that is installed from a release. +pub async fn download(url: &str) -> Result, String> { + let response = azazel_ai::tls::client() + .get(url) + .send() + .await + .and_then(|response| response.error_for_status()) + .map_err(|e| format!("could not download {url}: {e}"))?; + let bytes = response + .bytes() + .await + .map_err(|e| format!("could not download {url}: {e}"))?; + Ok(bytes.to_vec()) +} + +/// Writes `program` as the executable `name` (with the platform's suffix) into `dir` and returns +/// its path. It is written beside the target and moved, so that a download cut short leaves no +/// half program behind. +pub fn install_program(program: &[u8], dir: &Path, name: &str) -> Result { + std::fs::create_dir_all(dir).map_err(|e| format!("could not create {}: {e}", dir.display()))?; + let target = dir.join(format!("{name}{}", std::env::consts::EXE_SUFFIX)); + let partial = dir.join(format!("{name}.partial")); + std::fs::write(&partial, program).map_err(|e| format!("could not write {}: {e}", partial.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&partial, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| format!("could not make {} executable: {e}", partial.display()))?; + } + std::fs::rename(&partial, &target).map_err(|e| format!("could not move {name} into place: {e}"))?; + Ok(target) +} + /// `path` as the model wrote it, made absolute against `cwd`: `~/` expands to the home directory /// and `.`/`..` components are folded without touching the filesystem. pub fn resolve_path(cwd: &Path, path: &str) -> PathBuf { diff --git a/xtask/docs-check/Cargo.toml b/xtask/docs-check/Cargo.toml index e3e5d185..6fdfe8f3 100644 --- a/xtask/docs-check/Cargo.toml +++ b/xtask/docs-check/Cargo.toml @@ -15,7 +15,7 @@ workspace = true # registers. [dependencies] anyhow.workspace = true -azazel-cli.workspace = true +azazel-cli = { workspace = true, features = ["remote"] } azazel-core.workspace = true azazel-protocol.workspace = true azazel-tui.workspace = true From 906fdb5e81b2c88f1c5c45c4b9e85265cf8ea673 Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:49:52 +0000 Subject: [PATCH 08/27] azazel remote: command, background sessions, QR, tunnels --- crates/azazel-cli/src/cli.rs | 30 ++ crates/azazel-cli/src/detach.rs | 2 +- crates/azazel-cli/src/lib.rs | 9 + crates/azazel-cli/src/remote/background.rs | 164 +++++++ crates/azazel-cli/src/remote/mod.rs | 226 ++++++++++ crates/azazel-cli/src/remote/qr.rs | 80 ++++ crates/azazel-cli/src/remote/tunnel.rs | 493 +++++++++++++++++++++ crates/azazel-core/src/paths.rs | 4 + crates/azazel-tools/src/lsp/install.rs | 2 +- crates/azazel-tui/src/glyphs.rs | 6 + 10 files changed, 1014 insertions(+), 2 deletions(-) create mode 100644 crates/azazel-cli/src/remote/background.rs create mode 100644 crates/azazel-cli/src/remote/mod.rs create mode 100644 crates/azazel-cli/src/remote/qr.rs create mode 100644 crates/azazel-cli/src/remote/tunnel.rs diff --git a/crates/azazel-cli/src/cli.rs b/crates/azazel-cli/src/cli.rs index 2c2ad72c..29ad954a 100644 --- a/crates/azazel-cli/src/cli.rs +++ b/crates/azazel-cli/src/cli.rs @@ -599,6 +599,9 @@ pub enum Sub { #[arg(value_name = "PROMPT")] prompt: Vec, }, + /// Follow and steer the background sessions from a browser or a phone + #[cfg(feature = "remote")] + Remote(RemoteArgs), /// Run prompts at a time or when something happens: add, list, rm, run #[cfg(feature = "detach")] Schedule { @@ -741,6 +744,33 @@ pub enum RulesAction { }, } +/// The flags of `azazel remote`. +#[cfg(feature = "remote")] +#[derive(Debug, Clone, Default, PartialEq, Eq, clap::Args)] +pub struct RemoteArgs { + /// The port to listen on (7420 unless `[remote] port` says otherwise; 0 lets the system choose) + #[arg(long, value_name = "N")] + pub port: Option, + /// The address of your own tunnel or reverse proxy in front of the server + #[arg(long, value_name = "URL", conflicts_with_all = ["tunnel", "tailscale", "share"])] + pub public_url: Option, + /// Reach it from other devices through a Cloudflare quick tunnel + #[arg(long, conflicts_with_all = ["tailscale", "share"])] + pub tunnel: bool, + /// Reach it from other devices through Tailscale + #[arg(long, conflicts_with = "share")] + pub tailscale: bool, + /// Reach it from other devices the way `[remote] access` says + #[arg(long)] + pub share: bool, + /// Make the first link a view link: it can watch but not steer + #[arg(long)] + pub view: bool, + /// Print the first line as JSON: {"url", "pair", "port"} + #[arg(long)] + pub json: bool, +} + #[derive(Debug, Parser)] #[command(name = "azazel", version, about = "A team of coding agents in your terminal")] pub struct Cli { diff --git a/crates/azazel-cli/src/detach.rs b/crates/azazel-cli/src/detach.rs index 2f4f338c..127fef3c 100644 --- a/crates/azazel-cli/src/detach.rs +++ b/crates/azazel-cli/src/detach.rs @@ -285,7 +285,7 @@ pub async fn bg(paths: &Paths, request_id: Option<&str>) -> u8 { /// on the same session and under the same id. It works as the one before did, in the mode /// asked for now or else the one it was in; with `[session] resume_runs` it goes on with the /// run by itself. Returns the entry of the new process. -async fn revive(cli: &Cli, paths: &Paths, entry: &Entry) -> Result { +pub(crate) async fn revive(cli: &Cli, paths: &Paths, entry: &Entry) -> Result { let home = &paths.home; let mut args: Vec = entry.args.iter().map(OsString::from).collect(); args.extend(["--cwd".into(), entry.cwd.clone().into()]); diff --git a/crates/azazel-cli/src/lib.rs b/crates/azazel-cli/src/lib.rs index f5d04d1c..d4ae014c 100644 --- a/crates/azazel-cli/src/lib.rs +++ b/crates/azazel-cli/src/lib.rs @@ -24,6 +24,8 @@ pub mod history; pub mod hooks; #[cfg(feature = "detach")] pub mod host; +#[cfg(feature = "remote")] +pub mod remote; pub mod init; pub mod inventory; pub mod login; @@ -521,6 +523,13 @@ async fn run(cli: Cli, extensions: Vec>) -> u8 { Some(Sub::Kill { id }) => return detach::kill(&paths, id).await, #[cfg(feature = "detach")] Some(Sub::Attach { id, .. }) => return detach::attach(&cli, paths, id).await, + #[cfg(feature = "remote")] + Some(Sub::Remote(args)) => { + let Some(config) = load_config(&cli, &paths, trusted) else { + return print::EXIT_FAILED; + }; + return remote::run(&paths, &config, args).await; + } #[cfg(feature = "detach")] Some(Sub::Schedule { action }) => { let Some(config) = load_config(&cli, &paths, trusted) else { diff --git a/crates/azazel-cli/src/remote/background.rs b/crates/azazel-cli/src/remote/background.rs new file mode 100644 index 00000000..39535c48 --- /dev/null +++ b/crates/azazel-cli/src/remote/background.rs @@ -0,0 +1,164 @@ +//! The background sessions of this machine, as the sessions a remote server can reach. + +use std::sync::Arc; + +use async_trait::async_trait; +use azazel_core::Paths; +use azazel_remote::{Conn, Kind, SessionInfo, Sessions}; +use clap::Parser; +use serde_json::Value; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt}; +use tokio::sync::mpsc; + +use crate::cli::Cli; +use crate::detach::{revive, socket}; +use crate::running; + +/// Frames that may wait for a browser; the socket closes the browser that lets 4096 pile up. +const QUEUE: usize = 8192; + +pub struct BackgroundSessions { + paths: Paths, + redact: bool, +} + +impl BackgroundSessions { + pub fn new(paths: Paths, redact: bool) -> Arc { + Arc::new(BackgroundSessions { paths, redact }) + } +} + +#[async_trait] +impl Sessions for BackgroundSessions { + async fn list(&self) -> Vec { + let home = self.paths.home.clone(); + let entries = tokio::task::spawn_blocking(move || running::list(&home)) + .await + .unwrap_or_default(); + entries + .into_iter() + .map(|entry| SessionInfo { + id: entry.id, + name: entry.name, + kind: Kind::Background, + state: entry.state, + cwd: entry.cwd.display().to_string(), + cost_usd: entry.cost_usd, + mode: entry.mode, + started: entry.started, + }) + .collect() + } + + async fn open(&self, id: &str) -> Result { + let home = self.paths.home.clone(); + let wanted = id.to_string(); + let found = + tokio::task::spawn_blocking(move || running::list(&home).into_iter().find(|e| e.id == wanted)) + .await + .map_err(|e| e.to_string())?; + let mut entry = found.ok_or_else(|| format!("no background session {id}"))?; + if entry.interrupted() { + // Its process died in the middle of a run: it starts again where it stopped. + let cli = Cli::parse_from(["azazel"]); + entry = revive(&cli, &self.paths, &entry).await?; + } + let (mut reader, mut writer) = socket::connect(&entry.socket) + .await + .map_err(|e| format!("cannot reach the background session {}: {e}", entry.id))?; + let (frames_tx, frames) = mpsc::channel::(QUEUE); + let (commands, mut commands_rx) = mpsc::channel::(64); + let redact = self.redact; + tokio::spawn(async move { + let mut line = String::new(); + loop { + line.clear(); + let read = tokio::select! { + _ = frames_tx.closed() => return, + read = reader.read_line(&mut line) => read, + }; + if !matches!(read, Ok(n) if n > 0) { + return; + } + let text = line.trim_end(); + if text.is_empty() { + continue; + } + let text = if redact { redacted(text) } else { text.to_string() }; + if frames_tx.send(text).await.is_err() { + return; + } + } + }); + tokio::spawn(async move { + while let Some(mut line) = commands_rx.recv().await { + line.push('\n'); + if writer.write_all(line.as_bytes()).await.is_err() || writer.flush().await.is_err() { + return; + } + } + }); + Ok(Conn { frames, commands }) + } +} + +/// Frames that are complete and may carry what a tool read or a model wrote. +const COMPLETE: &[&str] = &[ + "message_end", + "tool_start", + "tool_end", + "approval_request", + "response", +]; + +/// `line` with the secrets in its strings hidden, when it is a complete frame. Deltas are left +/// alone: `message_end` replaces them. +pub(crate) fn redacted(line: &str) -> String { + let Ok(mut frame) = serde_json::from_str::(line) else { + return line.to_string(); + }; + if !frame["type"] + .as_str() + .is_some_and(|kind| COMPLETE.contains(&kind)) + { + return line.to_string(); + } + if !hide(&mut frame) { + return line.to_string(); + } + frame.to_string() +} + +/// Whether anything was hidden. +fn hide(value: &mut Value) -> bool { + match value { + Value::String(text) => match azazel_tui::text::redact(text) { + std::borrow::Cow::Owned(hidden) => { + *text = hidden; + true + } + std::borrow::Cow::Borrowed(_) => false, + }, + Value::Array(items) => items.iter_mut().fold(false, |any, item| hide(item) | any), + Value::Object(members) => members.values_mut().fold(false, |any, item| hide(item) | any), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn complete_frames_lose_their_secrets_and_deltas_and_other_frames_are_left_alone() { + let key = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGH"; + let end = format!(r#"{{"type":"tool_end","agent":"lead","output":{{"text":"KEY={key}"}}}}"#); + let hidden = redacted(&end); + assert!(!hidden.contains(key) && hidden.contains("redacted"), "{hidden}"); + let delta = format!(r#"{{"type":"stream","text":"{key}"}}"#); + assert_eq!(redacted(&delta), delta); + let plain = r#"{"type":"idle"}"#; + assert_eq!(redacted(plain), plain); + assert_eq!(redacted("not json"), "not json"); + } +} diff --git a/crates/azazel-cli/src/remote/mod.rs b/crates/azazel-cli/src/remote/mod.rs new file mode 100644 index 00000000..d3392475 --- /dev/null +++ b/crates/azazel-cli/src/remote/mod.rs @@ -0,0 +1,226 @@ +//! `azazel remote`: serves the background sessions of this machine to a browser. +//! +//! The server itself is the crate `azazel-remote`; this is what ties it to the application: the +//! sessions it can reach, the tunnel to another device, and the terminal it is run from. + +mod background; +mod qr; +mod tunnel; + +use std::io::IsTerminal; +use std::net::{IpAddr, Ipv4Addr}; +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use azazel_core::Paths; +use azazel_core::config::{Config, RemoteAccess}; +use azazel_remote::{Access, Link, Options, Server}; +use azazel_tui::{GlyphLevel, Glyphs}; +use serde_json::json; +use tokio::io::{AsyncBufReadExt, BufReader}; + +use crate::cli::RemoteArgs; +use crate::print::{EXIT_FAILED, EXIT_OK}; +use background::BackgroundSessions; +use tunnel::{Chooser, Tunnel}; + +/// Which way in to take. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Way { + Local, + Cloudflare, + Tailscale, +} + +fn way(args: &RemoteArgs, config: &Config) -> Way { + match (args.tunnel, args.tailscale, args.share) { + (true, ..) => Way::Cloudflare, + (_, true, _) => Way::Tailscale, + (.., true) => match config.remote.access { + RemoteAccess::Cloudflare => Way::Cloudflare, + RemoteAccess::Tailscale => Way::Tailscale, + }, + _ => Way::Local, + } +} + +/// Asks at the terminal when there is one. +struct Terminal; + +#[async_trait] +impl Chooser for Terminal { + async fn choose(&self, prompt: &str, options: &[&str]) -> Option { + if !std::io::stdin().is_terminal() { + return None; + } + eprintln!("{prompt}"); + for (n, option) in options.iter().enumerate() { + eprintln!(" {}) {option}", n + 1); + } + eprint!("> "); + let mut answer = String::new(); + tokio::task::spawn_blocking(move || { + std::io::stdin().read_line(&mut answer).ok()?; + let n: usize = answer.trim().parse().ok()?; + (1..=answer_count()).contains(&n).then_some(n - 1) + }) + .await + .ok() + .flatten() + } +} + +/// The options of the question `Terminal` asks are three. +const fn answer_count() -> usize { + 3 +} + +pub async fn run(paths: &Paths, config: &Config, args: &RemoteArgs) -> u8 { + let remote = &config.remote; + let way = way(args, config); + let public_url = args + .public_url + .clone() + .or_else(|| Some(remote.public_url.clone()).filter(|url| !url.trim().is_empty())); + let options = Options { + bind: IpAddr::V4(Ipv4Addr::LOCALHOST), + port: args.port.unwrap_or(remote.port), + public_url, + link_ttl: Duration::from_secs(remote.link_minutes.max(1) * 60), + device_ttl: Duration::from_secs(remote.device_hours.max(1) * 3600), + redact: remote.redact, + allow_bypass: remote.allow_bypass, + }; + let sessions = BackgroundSessions::new(paths.clone(), remote.redact); + let server = match Server::start(options, sessions).await { + Ok(server) => server, + Err(e) => { + eprintln!("azazel: could not start the server: {e}"); + return EXIT_FAILED; + } + }; + let tunnel = match open_tunnel(paths, way, server.port()).await { + Ok(tunnel) => tunnel, + Err(e) => { + eprintln!("azazel: {e}"); + server.shutdown().await; + return EXIT_FAILED; + } + }; + if let Some(tunnel) = &tunnel + && let Err(e) = server.set_public_url(&tunnel.url) + { + eprintln!("azazel: {e}"); + server.shutdown().await; + return EXIT_FAILED; + } + let first = if args.view { Access::View } else { Access::Control }; + let link = server.link(first); + let glyphs = Glyphs::new(GlyphLevel::detect(config.tui.glyphs.as_str(), |name| { + std::env::var(name).ok() + })); + announce(&server, &link, args.json, glyphs); + let code = wait(&server, glyphs, args.json).await; + server.shutdown().await; + if let Some(tunnel) = tunnel { + tunnel.stop().await; + } + code +} + +async fn open_tunnel(paths: &Paths, way: Way, port: u16) -> Result, String> { + match way { + Way::Local => Ok(None), + Way::Cloudflare => { + let program = tunnel::ensure_cloudflared(paths, Some(&Terminal)).await?; + eprintln!("azazel: starting the Cloudflare tunnel…"); + tunnel::cloudflare(&program, port).await.map(Some) + } + Way::Tailscale => { + eprintln!("azazel: serving the port through Tailscale…"); + tunnel::tailscale(port).await.map(Some) + } + } +} + +/// What a person needs to open the page: the address, the link, and the link as a QR code. With +/// `--json` the first line of standard output is the same as data, and the rest goes to standard +/// error. +fn announce(server: &Server, link: &Link, json: bool, glyphs: Glyphs) { + let urls = server.urls(); + let origin = urls.last().cloned().unwrap_or_default(); + if json { + println!( + "{}", + json!({ "url": origin, "pair": link.url, "port": server.port() }) + ); + } + let mut out = String::new(); + out.push_str(&format!( + "azazel remote is serving the background sessions at {}\n", + urls.join(" and ") + )); + out.push_str(&describe(link, glyphs)); + out.push_str("\nl: a new control link v: a new view link r: sign every device out q: quit\n"); + if json { + eprint!("{out}"); + } else { + print!("{out}"); + } +} + +/// A link as text and as a QR code. +fn describe(link: &Link, glyphs: Glyphs) -> String { + let kind = match link.access { + Access::Control => "control (can answer and steer)", + Access::View => "view (can watch only)", + }; + let mut text = format!( + "\n{kind} link, works once, until {}:\n {}\n\n", + link.expires, link.url + ); + for line in qr::qr_lines(&azazel_remote::qr_matrix(&link.url), glyphs) { + text.push_str(&format!(" {line}\n")); + } + text +} + +/// Serves until `q`, the end of the terminal's input after `q`, or Ctrl+C; the keys make links. +async fn wait(server: &Server, glyphs: Glyphs, json: bool) -> u8 { + let say = |text: String| { + if json { + eprint!("{text}"); + } else { + print!("{text}"); + } + }; + let mut lines = BufReader::new(tokio::io::stdin()).lines(); + let mut input_open = true; + loop { + tokio::select! { + _ = tokio::signal::ctrl_c() => return EXIT_OK, + line = lines.next_line(), if input_open => { + let Ok(Some(line)) = line else { + // No input (a background run, a closed pipe): serve until interrupted. + input_open = false; + continue; + }; + match line.trim() { + "l" => say(describe(&server.link(Access::Control), glyphs)), + "v" => say(describe(&server.link(Access::View), glyphs)), + "r" => { + server.revoke_all(); + say("every device is signed out and every link is void\n".to_string()); + } + "q" => return EXIT_OK, + "" => {} + other => say(format!("`{other}`: l, v, r or q\n")), + } + } + } + } +} + +#[allow(dead_code)] +fn _assert_chooser_is_object_safe(_: Option>) {} diff --git a/crates/azazel-cli/src/remote/qr.rs b/crates/azazel-cli/src/remote/qr.rs new file mode 100644 index 00000000..fc969af0 --- /dev/null +++ b/crates/azazel-cli/src/remote/qr.rs @@ -0,0 +1,80 @@ +//! A QR code as lines of terminal text. + +use azazel_tui::{Glyph, GlyphLevel, Glyphs}; + +/// Modules of quiet zone round the code; scanners need some, and the spec asks for four, which a +/// terminal can spare only in part. +const QUIET: usize = 2; + +/// The code drawn with the symbols of `glyphs`. On a dark terminal the light modules are the ink, +/// the usual way to print a code there. Two rows of modules share a line, except in ASCII, where +/// a module is two characters and a row of its own. +pub(crate) fn qr_lines(matrix: &[Vec], glyphs: Glyphs) -> Vec { + let size = matrix.len(); + if size == 0 { + return Vec::new(); + } + // Dark is true; the ink is what is not dark, and what is off the code is not dark either. + let ink = |x: usize, y: usize| { + let inside = x >= QUIET && y >= QUIET && x < size + QUIET && y < size + QUIET; + !(inside && matrix[y - QUIET][x - QUIET]) + }; + let side = size + 2 * QUIET; + if glyphs.level() == GlyphLevel::Ascii { + let (full, empty) = (glyphs.get(Glyph::QrFull), glyphs.get(Glyph::QrEmpty)); + return (0..side) + .map(|y| (0..side).map(|x| if ink(x, y) { full } else { empty }).collect()) + .collect(); + } + (0..side) + .step_by(2) + .map(|y| { + (0..side) + .map(|x| { + let lower = y + 1 < side && ink(x, y + 1); + // A row that is not there is the quiet zone: ink. + let lower = lower || y + 1 >= side; + glyphs.get(match (ink(x, y), lower) { + (true, true) => Glyph::QrFull, + (true, false) => Glyph::QrUpper, + (false, true) => Glyph::QrLower, + (false, false) => Glyph::QrEmpty, + }) + }) + .collect() + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn code() -> Vec> { + azazel_remote::qr_matrix("https://example.com/#pair=abc") + } + + #[test] + fn two_rows_share_a_line_and_the_quiet_zone_is_ink() { + let matrix = code(); + let lines = qr_lines(&matrix, Glyphs::new(GlyphLevel::Unicode)); + let side = matrix.len() + 4; + assert_eq!(lines.len(), side.div_ceil(2)); + assert!(lines.iter().all(|line| line.chars().count() == side)); + assert!(lines[0].chars().all(|c| c == '█')); + } + + #[test] + fn ascii_draws_a_row_per_line_and_two_characters_per_module() { + let matrix = code(); + let lines = qr_lines(&matrix, Glyphs::new(GlyphLevel::Ascii)); + assert_eq!(lines.len(), matrix.len() + 4); + assert!( + lines + .iter() + .all(|line| line.is_ascii() && line.len() == (matrix.len() + 4) * 2) + ); + // The top-left finder pattern has a dark corner module, which is blank here. + assert_eq!(&lines[2][4..6], " "); + } +} diff --git a/crates/azazel-cli/src/remote/tunnel.rs b/crates/azazel-cli/src/remote/tunnel.rs new file mode 100644 index 00000000..78261024 --- /dev/null +++ b/crates/azazel-cli/src/remote/tunnel.rs @@ -0,0 +1,493 @@ +//! Reaching the server from another device: a Cloudflare quick tunnel, or Tailscale. +//! +//! Both start a program of the user's (`cloudflared`, `tailscale`) that leads to the local port, and +//! learn the public address from it. azazel installs `cloudflared` when asked to; it never +//! installs Tailscale, which needs its system service and a sign-in. + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::Duration; + +use async_trait::async_trait; +use azazel_core::Paths; +use azazel_core::ui::UiBridge; +use serde_json::Value; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::{Child, Command}; +use tokio::sync::mpsc; + +/// How long cloudflared may take to print its address. +const TUNNEL_WAIT: Duration = Duration::from_secs(60); +/// How long one `tailscale` command may take. +const TAILSCALE_WAIT: Duration = Duration::from_secs(30); + +pub(crate) const CLOUDFLARED_DOWNLOADS: &str = + "https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"; +const CLOUDFLARED_RELEASES: &str = "https://github.com/cloudflare/cloudflared/releases/latest/download"; +/// Where the download comes from instead, for tests of the install against a stand-in server. +const BASE_VARIABLE: &str = "AZAZEL_CLOUDFLARED_BASE_URL"; + +/// Asks the person at the terminal one question with a few answers. +#[async_trait] +pub(crate) trait Chooser: Send + Sync { + /// The index of the answer, or `None` when nobody can be asked or they gave none. + async fn choose(&self, prompt: &str, options: &[&str]) -> Option; +} + +/// The terminal UI asks through its own popups. +#[async_trait] +impl Chooser for std::sync::Arc { + async fn choose(&self, prompt: &str, options: &[&str]) -> Option { + let options: Vec = options.iter().map(|o| o.to_string()).collect(); + self.select(prompt, &options).await.ok() + } +} + +/// A tunnel that is up. It is taken down by [`Tunnel::stop`], and when it is dropped. +pub(crate) struct Tunnel { + /// `https://[:port]` + pub url: String, + child: Option, + undo: Option, +} + +/// What stops Tailscale serving the port again. +struct Undo { + program: PathBuf, + https: u16, +} + +impl Undo { + fn run_blocking(&self) { + let _ = std::process::Command::new(&self.program) + .args(["serve", &format!("--https={}", self.https), "off"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } +} + +impl Tunnel { + pub async fn stop(mut self) { + if let Some(mut child) = self.child.take() { + let _ = child.kill().await; + } + if let Some(undo) = self.undo.take() { + let _ = tokio::task::spawn_blocking(move || undo.run_blocking()).await; + } + } +} + +impl Drop for Tunnel { + fn drop(&mut self) { + // The child is killed by `kill_on_drop`; Tailscale's entry is removed by hand. + if let Some(undo) = self.undo.take() { + undo.run_blocking(); + } + } +} + +// ---- Cloudflare ------------------------------------------------------------------------------- + +/// The address a line of cloudflared's output names, `https://.trycloudflare.com`. Its error +/// messages name `api.trycloudflare.com`, which is not a tunnel. +pub(crate) fn parse_trycloudflare(line: &str) -> Option { + let start = line.find("https://")?; + let host: String = line[start + "https://".len()..] + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.')) + .collect::() + .to_ascii_lowercase(); + let name = host.strip_suffix(".trycloudflare.com")?; + (!name.is_empty() && name != "api" && !name.contains('.')).then(|| format!("https://{host}")) +} + +/// The `cloudflared` on `PATH` or in `~/.azazel/remote/`. +pub(crate) fn find_cloudflared(paths: &Paths) -> Option { + let managed = paths + .remote_dir() + .join(format!("cloudflared{}", std::env::consts::EXE_SUFFIX)); + which::which("cloudflared") + .ok() + .or_else(|| managed.is_file().then_some(managed)) +} + +/// What to do about a missing cloudflared, for the person who has to do it. +pub(crate) fn install_help() -> String { + let command = match std::env::consts::OS { + "windows" => "winget install --id Cloudflare.cloudflared", + "macos" => "brew install cloudflared", + _ => { + "install the cloudflared package of your distribution, or download the binary from the page below" + } + }; + format!("install cloudflared: {command}\n more ways: {CLOUDFLARED_DOWNLOADS}") +} + +/// The name of the release file for this platform, and whether it is a gzipped tar archive. +pub(crate) fn release_asset() -> Option<(String, bool)> { + let arch = match std::env::consts::ARCH { + "x86_64" => "amd64", + "aarch64" => "arm64", + _ => return None, + }; + match (std::env::consts::OS, arch) { + ("linux", arch) => Some((format!("cloudflared-linux-{arch}"), false)), + ("macos", arch) => Some((format!("cloudflared-darwin-{arch}.tgz"), true)), + ("windows", "amd64") => Some(("cloudflared-windows-amd64.exe".to_string(), false)), + _ => None, + } +} + +/// The first regular file called `name` in a gzipped tar archive. +pub(crate) fn file_in_tgz(bytes: &[u8], name: &str) -> Result, String> { + let mut tar = Vec::new(); + // Nothing the release holds comes near this; a larger one is not what was asked for. + flate2::read::GzDecoder::new(bytes) + .take(512 * 1024 * 1024) + .read_to_end(&mut tar) + .map_err(|e| format!("the download is not a gzip file: {e}"))?; + let mut at = 0; + while at + 512 <= tar.len() { + let header = &tar[at..at + 512]; + if header.iter().all(|b| *b == 0) { + break; + } + let field = |range: std::ops::Range| { + let bytes = &header[range]; + let end = bytes.iter().position(|b| *b == 0).unwrap_or(bytes.len()); + String::from_utf8_lossy(&bytes[..end]).trim().to_string() + }; + let size = + usize::from_str_radix(&field(124..136), 8).map_err(|_| "the archive is damaged".to_string())?; + let body = at + 512; + if body + size > tar.len() { + return Err("the archive is cut short".to_string()); + } + let entry = field(0..100); + let base = entry.rsplit('/').next().unwrap_or_default(); + if matches!(header[156], b'0' | 0) && base == name { + return Ok(tar[body..body + size].to_vec()); + } + at = body + size.div_ceil(512) * 512; + } + Err(format!("the archive has no {name}")) +} + +/// Downloads cloudflared from `base` into `dir` and returns its path. +pub(crate) async fn install_cloudflared(dir: &Path, base: &str) -> Result { + let (asset, archive) = release_asset().ok_or("this platform has no cloudflared release")?; + let bytes = azazel_tools::util::download(&format!("{}/{asset}", base.trim_end_matches('/'))).await?; + let program = if archive { + file_in_tgz(&bytes, "cloudflared")? + } else { + bytes + }; + azazel_tools::util::install_program(&program, dir, "cloudflared") +} + +/// The cloudflared to run: the one found, or the one installed after asking. `Err` says what to +/// do when there is none. +pub(crate) async fn ensure_cloudflared(paths: &Paths, ask: Option<&dyn Chooser>) -> Result { + if let Some(found) = find_cloudflared(paths) { + return Ok(found); + } + let missing = format!("cloudflared is not installed.\n {}", install_help()); + let Some(ask) = ask else { return Err(missing) }; + let answer = ask + .choose( + "cloudflared is needed for the tunnel and is not installed. Install it into ~/.azazel/remote?", + &["Install it for me", "Show me how", "Cancel"], + ) + .await; + if answer != Some(0) { + return Err(missing); + } + let base = std::env::var(BASE_VARIABLE).unwrap_or_else(|_| CLOUDFLARED_RELEASES.to_string()); + eprintln!("azazel: downloading cloudflared…"); + install_cloudflared(&paths.remote_dir(), &base) + .await + .map_err(|e| format!("{e}\n {}", install_help())) +} + +/// Starts `cloudflared tunnel --url http://127.0.0.1:` and waits for it to say its address. +pub(crate) async fn cloudflare(program: &Path, port: u16) -> Result { + let mut child = Command::new(program) + .args([ + "tunnel", + "--no-autoupdate", + "--url", + &format!("http://127.0.0.1:{port}"), + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err(|e| format!("could not start {}: {e}", program.display()))?; + let (lines_tx, mut lines) = mpsc::unbounded_channel::(); + for stream in [ + child + .stdout + .take() + .map(|s| Box::new(s) as Box), + child + .stderr + .take() + .map(|s| Box::new(s) as Box), + ] + .into_iter() + .flatten() + { + let tx = lines_tx.clone(); + // Read to the end, also after the address: a pipe nobody reads fills up and stops the tunnel. + tokio::spawn(async move { + let mut reader = BufReader::new(stream).lines(); + while let Ok(Some(line)) = reader.next_line().await { + if tx.send(line).is_err() { + // Nobody listens any more; keep draining. + } + } + }); + } + drop(lines_tx); + let mut seen = Vec::new(); + let found = tokio::time::timeout(TUNNEL_WAIT, async { + while let Some(line) = lines.recv().await { + if let Some(url) = parse_trycloudflare(&line) { + return Some(url); + } + seen.push(line); + } + None + }) + .await; + match found { + Ok(Some(url)) => Ok(Tunnel { + url, + child: Some(child), + undo: None, + }), + Ok(None) => Err(format!( + "cloudflared ended without giving an address:\n{}", + tail(&seen) + )), + Err(_) => Err(format!( + "cloudflared did not give an address within {} seconds:\n{}", + TUNNEL_WAIT.as_secs(), + tail(&seen) + )), + } +} + +fn tail(lines: &[String]) -> String { + let start = lines.len().saturating_sub(8); + lines[start..] + .iter() + .map(|line| format!(" {line}")) + .collect::>() + .join("\n") +} + +// ---- Tailscale -------------------------------------------------------------------------------- + +const TAILSCALE_HELP: &str = "Tailscale is not set up on this machine.\n \ +install it from https://tailscale.com/download, sign in with `tailscale up`, and install the \ +Tailscale app on the phone (signed in to the same account)"; + +fn find_tailscale() -> Option { + which::which("tailscale").ok().or_else(|| { + let app = PathBuf::from("/Applications/Tailscale.app/Contents/MacOS/Tailscale"); + app.is_file().then_some(app) + }) +} + +/// Runs a `tailscale` command; its output, or why it failed. +async fn tailscale_output(program: &Path, args: &[&str]) -> Result { + let run = Command::new(program) + .args(args) + .stdin(Stdio::null()) + .kill_on_drop(true) + .output(); + let output = tokio::time::timeout(TAILSCALE_WAIT, run) + .await + .map_err(|_| { + format!( + "`tailscale {}` did not answer within {} seconds", + args.join(" "), + TAILSCALE_WAIT.as_secs() + ) + })? + .map_err(|e| format!("could not run tailscale: {e}"))?; + if output.status.success() { + return Ok(String::from_utf8_lossy(&output.stdout).into_owned()); + } + let said = String::from_utf8_lossy(&output.stderr); + let said = if said.trim().is_empty() { + String::from_utf8_lossy(&output.stdout) + } else { + said + }; + Err(format!("`tailscale {}` failed: {}", args.join(" "), said.trim())) +} + +/// The name of this machine on the tailnet from `tailscale status --json`, when it is signed in. +pub(crate) fn tailnet_name(status: &str) -> Result { + let status: Value = + serde_json::from_str(status).map_err(|e| format!("tailscale's status is not JSON: {e}"))?; + let state = status["BackendState"].as_str().unwrap_or_default(); + if state != "Running" { + return Err(format!( + "Tailscale is not connected (it is `{}`): sign in with `tailscale up`", + if state.is_empty() { "unknown" } else { state } + )); + } + let name = status["Self"]["DNSName"] + .as_str() + .unwrap_or_default() + .trim_end_matches('.'); + if name.is_empty() { + return Err( + "this machine has no name on the tailnet: turn on MagicDNS and HTTPS certificates in the Tailscale admin console" + .to_string(), + ); + } + Ok(name.to_ascii_lowercase()) +} + +/// The first HTTPS port of Tailscale Serve that nothing uses: this must not replace what the user +/// serves already. +pub(crate) fn free_https_port(serve: &str) -> Option { + let used: Vec = serde_json::from_str::(serve) + .ok() + .and_then(|serve| serve["TCP"].as_object().cloned()) + .map(|tcp| tcp.keys().filter_map(|port| port.parse().ok()).collect()) + .unwrap_or_default(); + [443, 8443, 10000].into_iter().find(|port| !used.contains(port)) +} + +/// Serves the port over HTTPS to the tailnet. +pub(crate) async fn tailscale(port: u16) -> Result { + let program = find_tailscale().ok_or(TAILSCALE_HELP)?; + let status = tailscale_output(&program, &["status", "--json"]) + .await + .map_err(|e| format!("{e}\n {TAILSCALE_HELP}"))?; + let name = tailnet_name(&status)?; + // Without a configuration, `serve status` has nothing to say; that is no error. + let serve = tailscale_output(&program, &["serve", "status", "--json"]) + .await + .unwrap_or_default(); + let https = free_https_port(&serve) + .ok_or("Tailscale Serve uses ports 443, 8443 and 10000 already: free one with `tailscale serve --https= off`")?; + let target = format!("http://127.0.0.1:{port}"); + tailscale_output(&program, &["serve", "--bg", &format!("--https={https}"), &target]).await?; + let url = match https { + 443 => format!("https://{name}"), + other => format!("https://{name}:{other}"), + }; + Ok(Tunnel { + url, + child: None, + undo: Some(Undo { program, https }), + }) +} + +#[cfg(test)] +mod tests { + use std::io::Write; + + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + use super::*; + + #[test] + fn the_tunnel_address_is_the_trycloudflare_host_and_not_the_api() { + let said = "2026-11-15T10:00:00Z INF | https://quiet-river-1234.trycloudflare.com |"; + assert_eq!( + parse_trycloudflare(said).unwrap(), + "https://quiet-river-1234.trycloudflare.com" + ); + let failed = "ERR failed to request quick Tunnel: Post \"https://api.trycloudflare.com/tunnel\""; + assert_eq!(parse_trycloudflare(failed), None); + assert_eq!( + parse_trycloudflare("https://evil.example.com/.trycloudflare.com"), + None + ); + assert_eq!(parse_trycloudflare("https://a.b.trycloudflare.com"), None); + assert_eq!(parse_trycloudflare("no address here"), None); + } + + #[test] + fn the_tailnet_name_needs_a_signed_in_machine() { + let up = r#"{"BackendState":"Running","Self":{"DNSName":"Laptop.tail1234.ts.net."}}"#; + assert_eq!(tailnet_name(up).unwrap(), "laptop.tail1234.ts.net"); + let out = r#"{"BackendState":"NeedsLogin","Self":{"DNSName":""}}"#; + assert!(tailnet_name(out).unwrap_err().contains("tailscale up")); + assert!(tailnet_name("nope").is_err()); + } + + #[test] + fn an_https_port_that_the_user_serves_already_is_left_alone() { + assert_eq!(free_https_port(""), Some(443)); + assert_eq!(free_https_port("{}"), Some(443)); + let busy = r#"{"TCP":{"443":{"HTTPS":true},"8443":{"HTTPS":true}}}"#; + assert_eq!(free_https_port(busy), Some(10000)); + let full = r#"{"TCP":{"443":{},"8443":{},"10000":{}}}"#; + assert_eq!(free_https_port(full), None); + } + + fn tgz(name: &str, body: &[u8]) -> Vec { + let mut header = [0u8; 512]; + header[..name.len()].copy_from_slice(name.as_bytes()); + header[124..135].copy_from_slice(format!("{:011o}", body.len()).as_bytes()); + header[156] = b'0'; + let mut tar = header.to_vec(); + tar.extend_from_slice(body); + tar.resize(tar.len() + (512 - body.len() % 512) % 512, 0); + tar.extend_from_slice(&[0u8; 1024]); + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + gz.write_all(&tar).unwrap(); + gz.finish().unwrap() + } + + #[test] + fn the_program_is_found_in_the_archive_of_the_release() { + let archive = tgz("cloudflared", b"#!program"); + assert_eq!(file_in_tgz(&archive, "cloudflared").unwrap(), b"#!program"); + assert!(file_in_tgz(&archive, "other").is_err()); + assert!(file_in_tgz(b"not gzip", "cloudflared").is_err()); + } + + #[tokio::test] + async fn the_release_for_this_platform_is_downloaded_and_installed() { + let Some((asset, archive)) = release_asset() else { + return; + }; + let body = if archive { + tgz("cloudflared", b"the program") + } else { + b"the program".to_vec() + }; + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path(format!("/{asset}"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(body)) + .mount(&server) + .await; + let dir = tempfile::tempdir().unwrap(); + let installed = install_cloudflared(&dir.path().join("remote"), &server.uri()) + .await + .unwrap(); + assert_eq!(std::fs::read(&installed).unwrap(), b"the program"); + assert!(installed.starts_with(dir.path())); + // Nothing half-written is left beside it. + assert_eq!(std::fs::read_dir(installed.parent().unwrap()).unwrap().count(), 1); + + let missing = MockServer::start().await; + let failed = install_cloudflared(&dir.path().join("other"), &missing.uri()).await; + assert!(failed.unwrap_err().contains("could not download")); + } +} diff --git a/crates/azazel-core/src/paths.rs b/crates/azazel-core/src/paths.rs index 6a855e10..8bb27767 100644 --- a/crates/azazel-core/src/paths.rs +++ b/crates/azazel-core/src/paths.rs @@ -67,6 +67,10 @@ impl Paths { pub fn lsp_dir(&self) -> PathBuf { self.home.join("lsp") } + /// Where azazel keeps the programs `azazel remote` needs, such as `cloudflared`. + pub fn remote_dir(&self) -> PathBuf { + self.home.join("remote") + } pub fn logs_dir(&self) -> PathBuf { self.home.join("logs") } diff --git a/crates/azazel-tools/src/lsp/install.rs b/crates/azazel-tools/src/lsp/install.rs index d19eb1cc..deb9604f 100644 --- a/crates/azazel-tools/src/lsp/install.rs +++ b/crates/azazel-tools/src/lsp/install.rs @@ -3,7 +3,7 @@ //! install is asked for, so a plan always names something that exists. use std::collections::{BTreeMap, BTreeSet}; -use std::io::{Cursor, Read, Write}; +use std::io::{Cursor, Read}; use std::path::{Path, PathBuf}; use std::time::Duration; diff --git a/crates/azazel-tui/src/glyphs.rs b/crates/azazel-tui/src/glyphs.rs index bcf82bad..938aa696 100644 --- a/crates/azazel-tui/src/glyphs.rs +++ b/crates/azazel-tui/src/glyphs.rs @@ -212,6 +212,12 @@ glyphs! { Cycle => "⟳", "⟳", "~"; /// Between the steps of a sequence: `smol › default`. Step => "›", "›", ">"; + /// The QR code of a pairing link, two rows of modules to a line of text: both, the upper one, + /// the lower one, or neither. In ASCII a line is one row and a module is two characters. + QrFull => "█", "█", "##"; + QrUpper => "▀", "▀", "##"; + QrLower => "▄", "▄", "##"; + QrEmpty => " ", " ", " "; } /// The characters of a box. From ec6679db719e893ac0c0a99ea8838dffda3af63c Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:54:44 +0000 Subject: [PATCH 09/27] remote: fixtures and tests --- Cargo.lock | 12 + Cargo.toml | 2 + crates/azazel-cli/Cargo.toml | 1 + crates/azazel-cli/tests/it/main.rs | 1 + crates/azazel-cli/tests/it/remote_web.rs | 619 ++++++++++++++++++++ tests/fixtures/fake-cloudflared/Cargo.toml | 10 + tests/fixtures/fake-cloudflared/src/main.rs | 32 + tests/fixtures/fake-tailscale/Cargo.toml | 13 + tests/fixtures/fake-tailscale/src/main.rs | 64 ++ tests/fixtures/scripts/web_session.json | 17 + 10 files changed, 771 insertions(+) create mode 100644 crates/azazel-cli/tests/it/remote_web.rs create mode 100644 tests/fixtures/fake-cloudflared/Cargo.toml create mode 100644 tests/fixtures/fake-cloudflared/src/main.rs create mode 100644 tests/fixtures/fake-tailscale/Cargo.toml create mode 100644 tests/fixtures/fake-tailscale/src/main.rs create mode 100644 tests/fixtures/scripts/web_session.json diff --git a/Cargo.lock b/Cargo.lock index a5650386..2ffc80ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,6 +1009,7 @@ dependencies = [ "sha2 0.11.1", "tempfile", "tokio", + "tokio-tungstenite", "tokio-util", "toml", "toml_edit", @@ -2709,6 +2710,10 @@ version = "0.10.5" name = "fake-check" version = "0.10.5" +[[package]] +name = "fake-cloudflared" +version = "0.10.5" + [[package]] name = "fake-dap" version = "0.10.5" @@ -2749,6 +2754,13 @@ dependencies = [ name = "fake-ssh" version = "0.10.5" +[[package]] +name = "fake-tailscale" +version = "0.10.5" +dependencies = [ + "serde_json", +] + [[package]] name = "fallible-iterator" version = "0.3.0" diff --git a/Cargo.toml b/Cargo.toml index 8c82e28b..66fdc8ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,8 @@ members = [ "tests/fixtures/fake-ssh", "tests/fixtures/fake-sched", "tests/fixtures/fake-az", + "tests/fixtures/fake-cloudflared", + "tests/fixtures/fake-tailscale", "examples/custom-distro", "examples/client-demo", ] diff --git a/crates/azazel-cli/Cargo.toml b/crates/azazel-cli/Cargo.toml index 2b8f6af5..c97fa763 100644 --- a/crates/azazel-cli/Cargo.toml +++ b/crates/azazel-cli/Cargo.toml @@ -155,4 +155,5 @@ agent-client-protocol.workspace = true dunce.workspace = true rmcp.workspace = true tempfile.workspace = true +tokio-tungstenite.workspace = true wiremock.workspace = true diff --git a/crates/azazel-cli/tests/it/main.rs b/crates/azazel-cli/tests/it/main.rs index 42ce806c..a44e9f09 100644 --- a/crates/azazel-cli/tests/it/main.rs +++ b/crates/azazel-cli/tests/it/main.rs @@ -31,6 +31,7 @@ mod print_mode; mod projects; mod read_guard; mod remote; +mod remote_web; mod reports; mod resets; mod restart; diff --git a/crates/azazel-cli/tests/it/remote_web.rs b/crates/azazel-cli/tests/it/remote_web.rs new file mode 100644 index 00000000..b29e7d5f --- /dev/null +++ b/crates/azazel-cli/tests/it/remote_web.rs @@ -0,0 +1,619 @@ +#![cfg(feature = "remote")] + +//! `azazel remote`: the web server in front of background sessions, against the real binary, the +//! scripted provider and stand-ins for `cloudflared` and `tailscale`. The client is a WebSocket +//! client with a Bearer token, as a program would be; pairing goes through an HTTP client. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::LazyLock; +use std::sync::mpsc::Receiver; +use std::time::{Duration, Instant}; + +use futures::{SinkExt, StreamExt}; +use serde_json::{Value, json}; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::protocol::Message; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; + +use crate::common::{fixture_program, lines_of, script_fixture}; + +const LIMIT: Duration = Duration::from_secs(60); + +static CLOUDFLARED: LazyLock = LazyLock::new(|| fixture_program("fake-cloudflared")); +static TAILSCALE: LazyLock = LazyLock::new(|| fixture_program("fake-tailscale")); + +/// A home and a project of its own. Background sessions still running when it goes are stopped. +struct Sandbox { + dir: tempfile::TempDir, +} + +impl Sandbox { + fn new() -> Sandbox { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("project/.git")).unwrap(); + std::fs::create_dir_all(dir.path().join("home")).unwrap(); + std::fs::copy(script_fixture("web_session.json"), dir.path().join("script.json")).unwrap(); + Sandbox { dir } + } + + fn home(&self) -> PathBuf { + self.dir.path().join("home") + } + + fn azazel(&self, args: &[&str]) -> Command { + let mut command = Command::new(assert_cmd::cargo::cargo_bin("azazel")); + command + .env("AZAZEL_HOME", self.home()) + .env("AZAZEL_MOCK_SCRIPT", self.dir.path().join("script.json")) + .args(["--set", "session.auto_name=false", "--no-memory"]) + .args(["--set", "notify.desktop=\"off\""]) + .arg("--cwd") + .arg(self.dir.path().join("project")) + .args(args) + .stdin(Stdio::null()); + command + } + + fn ok(&self, args: &[&str]) -> String { + let output = self.azazel(args).output().unwrap(); + assert!( + output.status.success(), + "{args:?}: {}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + } + + /// Starts a background session on the prompt of the script and returns its id. + fn bg(&self, mode: &str) -> String { + self.ok(&["--mode", mode, "bg", "create hello"]) + .trim() + .to_string() + } + + fn wait_for_state(&self, id: &str, state: &str) { + let started = Instant::now(); + loop { + let listed = self.ok(&["ps", "--json"]); + let found = listed + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .any(|row| row["id"] == id && row["state"] == state); + if found { + return; + } + assert!(started.elapsed() < LIMIT, "{id} never was `{state}`"); + std::thread::sleep(Duration::from_millis(50)); + } + } + + /// `azazel remote --port 0 --json` with `args`, and `dirs` ahead of the rest of `PATH`. + fn remote(&self, args: &[&str], dirs: &[&Path]) -> Remote { + let mut all = vec!["remote", "--port", "0", "--json"]; + all.extend_from_slice(args); + let mut command = self.azazel(&all); + let mut path: Vec = dirs.iter().map(|dir| dir.to_path_buf()).collect(); + path.extend(std::env::split_paths( + &std::env::var_os("PATH").unwrap_or_default(), + )); + command.env("PATH", std::env::join_paths(path).unwrap()); + Remote::start(command) + } + + /// A directory with `fixture` in it as `name`. + fn tool(&self, name: &str, fixture: &Path) -> PathBuf { + let dir = self.dir.path().join(format!("tool-{name}")); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::copy( + fixture, + dir.join(format!("{name}{}", std::env::consts::EXE_SUFFIX)), + ) + .unwrap(); + dir + } +} + +impl Drop for Sandbox { + fn drop(&mut self) { + let listed = self.azazel(&["ps", "--json"]).output(); + let rows = listed + .map(|output| String::from_utf8_lossy(&output.stdout).into_owned()) + .unwrap_or_default(); + for row in rows + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + { + if let Some(id) = row["id"].as_str() { + let _ = self.azazel(&["kill", id]).output(); + } + } + } +} + +/// A running `azazel remote`. +struct Remote { + child: Child, + errors: Receiver, + /// The first line of its output, which `--json` makes `{"url","pair","port"}`. + first: Value, +} + +impl Remote { + fn start(mut command: Command) -> Remote { + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let lines = lines_of(child.stdout.take().unwrap()); + let errors = lines_of(child.stderr.take().unwrap()); + let line = lines.recv_timeout(LIMIT).unwrap_or_else(|_| { + let _ = child.kill(); + panic!( + "azazel remote printed nothing: {:?}", + errors.try_iter().collect::>() + ) + }); + let first = serde_json::from_str(&line).unwrap_or_else(|e| panic!("{line:?}: {e}")); + // Whatever it prints after that is not read, which a pipe that fills would punish. + std::thread::spawn(move || for _ in lines {}); + Remote { child, errors, first } + } + + fn port(&self) -> u16 { + self.first["port"].as_u64().unwrap() as u16 + } + + fn base(&self) -> String { + format!("http://127.0.0.1:{}", self.port()) + } + + fn secret(&self) -> String { + self.first["pair"] + .as_str() + .unwrap() + .split_once("#pair=") + .unwrap() + .1 + .to_string() + } + + /// Makes a link with `key` (`l` control, `v` view) and pairs with it; the device's token. + async fn pair_with(&mut self, secret: &str) -> String { + let answer = pair(&self.base(), secret, &[]).await; + assert_eq!(answer.0, 200, "{}", answer.1); + answer.1["token"].as_str().unwrap().to_string() + } + + /// The text of what it said on standard error up to a line with `wanted`. + fn said(&self, wanted: &str) -> Vec { + crate::common::read_until(&self.errors, wanted, LIMIT) + } + + /// Types `q` and waits for it to end. + fn quit(&mut self) -> std::process::ExitStatus { + let stdin = self.child.stdin.as_mut().unwrap(); + writeln!(stdin, "q").unwrap(); + stdin.flush().unwrap(); + let started = Instant::now(); + loop { + if let Some(status) = self.child.try_wait().unwrap() { + return status; + } + assert!(started.elapsed() < LIMIT, "azazel remote did not end"); + std::thread::sleep(Duration::from_millis(25)); + } + } +} + +impl Drop for Remote { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// POSTs a pairing secret; the status and the JSON answer. +async fn pair(base: &str, secret: &str, headers: &[(&str, &str)]) -> (u16, Value) { + let mut request = azazel_ai::tls::client() + .post(format!("{base}/api/pair")) + .header("X-Azazel", "1") + .json(&json!({ "secret": secret, "bearer": true })); + for (name, value) in headers { + request = request.header(*name, *value); + } + let response = request.send().await.unwrap(); + let status = response.status().as_u16(); + (status, response.json().await.unwrap_or(Value::Null)) +} + +type Socket = WebSocketStream>; + +async fn connect(port: u16, id: &str, token: Option<&str>, origin: &str) -> Socket { + let mut request = format!("ws://127.0.0.1:{port}/api/ws/{id}") + .into_client_request() + .unwrap(); + request.headers_mut().insert("origin", origin.parse().unwrap()); + if let Some(token) = token { + request + .headers_mut() + .insert("authorization", format!("Bearer {token}").parse().unwrap()); + } + tokio_tungstenite::connect_async(request).await.unwrap().0 +} + +async fn send(socket: &mut Socket, command: Value) { + socket.send(Message::text(command.to_string())).await.unwrap(); +} + +async fn next(socket: &mut Socket) -> Value { + loop { + match tokio::time::timeout(LIMIT, socket.next()).await.expect("a frame") { + Some(Ok(Message::Text(text))) => return serde_json::from_str(text.as_str()).unwrap(), + Some(Ok(Message::Ping(_) | Message::Pong(_))) => {} + other => panic!("expected a frame, got {other:?}"), + } + } +} + +/// The frames up to and including the first that `wanted` accepts. +async fn until(socket: &mut Socket, wanted: impl Fn(&Value) -> bool) -> Vec { + let mut seen = Vec::new(); + loop { + let frame = next(socket).await; + let done = wanted(&frame); + seen.push(frame); + if done { + return seen; + } + } +} + +async fn close_code(socket: &mut Socket) -> u16 { + loop { + match tokio::time::timeout(LIMIT, socket.next()).await.expect("a close") { + Some(Ok(Message::Close(Some(frame)))) => return u16::from(frame.code), + Some(Ok(Message::Text(_) | Message::Ping(_) | Message::Pong(_))) => {} + other => panic!("expected a close, got {other:?}"), + } + } +} + +/// Attaches and waits for the answer; returns it. +async fn attach(socket: &mut Socket, replay: &str) -> Value { + send( + socket, + json!({ "id": "attach", "type": "attach", "replay": replay }), + ) + .await; + until(socket, |frame| frame["id"] == "attach") + .await + .pop() + .unwrap() +} + +#[tokio::test] +async fn nothing_works_without_a_token_a_right_origin_or_a_fresh_link() { + let sandbox = Sandbox::new(); + let id = sandbox.bg("auto"); + let mut remote = sandbox.remote(&[], &[]); + let (base, port) = (remote.base(), remote.port()); + let client = azazel_ai::tls::client(); + + assert_eq!( + client + .get(format!("{base}/api/sessions")) + .send() + .await + .unwrap() + .status(), + 401 + ); + let mut nobody = connect(port, &id, None, &base).await; + assert_eq!(close_code(&mut nobody).await, 4401); + + // The page is public and carries its policy. + let page = client.get(format!("{base}/")).send().await.unwrap(); + assert_eq!(page.status(), 200); + let csp = page.headers()["content-security-policy"] + .to_str() + .unwrap() + .to_string(); + assert!( + csp.contains("default-src 'self'") && csp.contains("frame-ancestors 'none'"), + "{csp}" + ); + + // A link pairs once; from another origin it does not pair at all. + let secret = remote.secret(); + let foreign = pair(&base, &secret, &[("Origin", "https://evil.example")]).await; + assert_eq!(foreign.0, 403); + let token = remote.pair_with(&secret).await; + assert_eq!(pair(&base, &secret, &[]).await.0, 401); + + let listed: Value = client + .get(format!("{base}/api/sessions")) + .bearer_auth(&token) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(listed["sessions"][0]["id"], json!(id)); + let mut unknown = connect(port, "nosuch", Some(&token), &base).await; + assert_eq!(close_code(&mut unknown).await, 4404); +} + +#[tokio::test] +async fn a_prompt_streams_from_the_start_to_idle() { + let sandbox = Sandbox::new(); + let id = sandbox.bg("auto"); + let mut remote = sandbox.remote(&[], &[]); + let token = remote.pair_with(&remote.secret()).await; + let mut socket = connect(remote.port(), &id, Some(&token), &remote.base()).await; + assert_eq!(next(&mut socket).await["type"], "hello"); + // `all` replays what the session did since it started, the run of the prompt it began with. + let attached = attach(&mut socket, "all").await; + assert_eq!(attached["success"], true, "{attached}"); + let frames = until(&mut socket, |frame| frame["type"] == "idle").await; + let kinds: Vec<&str> = frames.iter().filter_map(|frame| frame["type"].as_str()).collect(); + assert!(kinds.contains(&"agent_start"), "{kinds:?}"); + let position = |kind: &str| kinds.iter().position(|k| *k == kind).unwrap(); + assert!( + position("agent_start") < position("tool_end") && position("tool_end") < position("idle"), + "{kinds:?}" + ); + assert!(sandbox.dir.path().join("project/hello.txt").is_file()); +} + +#[tokio::test] +async fn the_first_of_two_browsers_to_answer_wins_and_the_other_is_told() { + let sandbox = Sandbox::new(); + let id = sandbox.bg("manual"); + sandbox.wait_for_state(&id, "waiting for you"); + let mut remote = sandbox.remote(&[], &[]); + let token = remote.pair_with(&remote.secret()).await; + let mut first = connect(remote.port(), &id, Some(&token), &remote.base()).await; + let mut second = connect(remote.port(), &id, Some(&token), &remote.base()).await; + for socket in [&mut first, &mut second] { + next(socket).await; + attach(socket, "none").await; + } + let asked = until(&mut first, |frame| frame["type"] == "approval_request") + .await + .pop() + .unwrap(); + until(&mut second, |frame| frame["type"] == "approval_request").await; + let request_id = asked["request_id"].as_str().unwrap().to_string(); + + send( + &mut first, + json!({ "id": "yes", "type": "approval_response", "request_id": request_id, "decision": "allow" }), + ) + .await; + let closed = until(&mut second, |frame| frame["type"] == "request_closed") + .await + .pop() + .unwrap(); + assert_eq!(closed["request_id"], json!(request_id)); + // A second answer is turned away. + send( + &mut second, + json!({ "id": "late", "type": "approval_response", "request_id": request_id, "decision": "deny" }), + ) + .await; + let late = until(&mut second, |frame| frame["id"] == "late") + .await + .pop() + .unwrap(); + assert_eq!(late["success"], false, "{late}"); + until(&mut first, |frame| frame["type"] == "idle").await; +} + +#[tokio::test] +async fn a_view_link_watches_and_cannot_steer_and_a_control_link_cannot_reach_the_machine() { + let sandbox = Sandbox::new(); + let id = sandbox.bg("manual"); + sandbox.wait_for_state(&id, "waiting for you"); + let mut remote = sandbox.remote(&["--view"], &[]); + let view = remote.pair_with(&remote.secret()).await; + let mut watcher = connect(remote.port(), &id, Some(&view), &remote.base()).await; + next(&mut watcher).await; + assert_eq!(attach(&mut watcher, "none").await["success"], true); + send(&mut watcher, json!({ "id": "p", "type": "prompt", "text": "go" })).await; + let refused = until(&mut watcher, |frame| frame["id"] == "p") + .await + .pop() + .unwrap(); + assert_eq!(refused["success"], false, "{refused}"); + // The frames still come: the request that waits, and the answer to a read. + send(&mut watcher, json!({ "id": "s", "type": "get_state" })).await; + let state = until(&mut watcher, |frame| frame["id"] == "s") + .await + .pop() + .unwrap(); + assert_eq!(state["success"], true, "{state}"); + + // The viewer cannot make a control link; stdin of the server can. + let made: Value = azazel_ai::tls::client() + .post(format!("{}/api/links", remote.base())) + .bearer_auth(&view) + .header("X-Azazel", "1") + .json(&json!({ "access": "control" })) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert!(made["error"].is_string(), "{made}"); + // With `--json` the first link is also on standard error; read past it to the next one. + remote.said("pair="); + { + let stdin = remote.child.stdin.as_mut().unwrap(); + writeln!(stdin, "l").unwrap(); + stdin.flush().unwrap(); + } + let said = remote.said("pair="); + let secret = said + .last() + .unwrap() + .split_once("#pair=") + .unwrap() + .1 + .trim() + .to_string(); + let control = remote.pair_with(&secret).await; + let mut driver = connect(remote.port(), &id, Some(&control), &remote.base()).await; + next(&mut driver).await; + attach(&mut driver, "none").await; + for (n, command) in [ + json!({ "type": "shell", "command": "echo hi" }), + json!({ "type": "export", "path": "out.html" }), + json!({ "type": "set_role", "role": "default", "save": "home" }), + json!({ "type": "set_mode", "mode": "bypass" }), + ] + .into_iter() + .enumerate() + { + let mut command = command; + command["id"] = json!(format!("c{n}")); + send(&mut driver, command).await; + let answer = until(&mut driver, |frame| frame["id"] == json!(format!("c{n}"))) + .await + .pop() + .unwrap(); + assert_eq!(answer["success"], false, "{answer}"); + } + assert!(!sandbox.dir.path().join("project/out.html").exists()); +} + +#[test] +fn a_cloudflare_tunnel_is_the_only_other_address_the_server_answers_to() { + let sandbox = Sandbox::new(); + let tool = sandbox.tool("cloudflared", &CLOUDFLARED); + let mut remote = sandbox.remote(&["--tunnel"], &[&tool]); + assert_eq!(remote.first["url"], "https://fake-tunnel-test.trycloudflare.com"); + let pair_url = remote.first["pair"].as_str().unwrap(); + assert!( + pair_url.starts_with("https://fake-tunnel-test.trycloudflare.com/#pair="), + "{pair_url}" + ); + // cloudflared was told to lead to the port of the server. + let told = std::fs::read_to_string(tool.join("cloudflared.url")).unwrap(); + assert_eq!(told, format!("http://127.0.0.1:{}", remote.port())); + + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let client = azazel_ai::tls::client(); + let base = remote.base(); + let through = |host: &'static str| client.get(format!("{base}/api/me")).header("Host", host).send(); + assert_eq!( + through("fake-tunnel-test.trycloudflare.com") + .await + .unwrap() + .status(), + 401 + ); + assert_eq!(through("other.trycloudflare.com").await.unwrap().status(), 421); + let secret = remote.secret(); + let paired = pair( + &base, + &secret, + &[ + ("Host", "fake-tunnel-test.trycloudflare.com"), + ("Origin", "https://fake-tunnel-test.trycloudflare.com"), + ], + ) + .await; + assert_eq!(paired.0, 200, "{}", paired.1); + }); + assert!(remote.quit().success()); +} + +#[test] +fn without_cloudflared_the_run_says_how_to_install_it() { + let sandbox = Sandbox::new(); + // Nothing on `PATH` but an empty directory, and nothing in the home. + let empty = sandbox.dir.path().join("empty"); + std::fs::create_dir_all(&empty).unwrap(); + let mut command = sandbox.azazel(&["remote", "--port", "0", "--tunnel"]); + command.env("PATH", &empty); + let output = command.output().unwrap(); + assert!(!output.status.success()); + let said = String::from_utf8_lossy(&output.stderr); + assert!( + said.contains("cloudflared is not installed") && said.contains("install"), + "{said}" + ); + assert!(said.contains("developers.cloudflare.com"), "{said}"); +} + +/// Writes what the stand-in `tailscale` knows. +fn tailscale_knows(tool: &Path, status: Option<&str>) { + let data = tool.join("tailscale-data"); + std::fs::create_dir_all(&data).unwrap(); + if let Some(status) = status { + std::fs::write(data.join("status.json"), status).unwrap(); + } +} + +#[test] +fn tailscale_serves_the_port_and_only_that_entry_is_removed_afterwards() { + let sandbox = Sandbox::new(); + let tool = sandbox.tool("tailscale", &TAILSCALE); + tailscale_knows( + &tool, + Some(r#"{"BackendState":"Running","Self":{"DNSName":"Laptop.tail1234.ts.net."}}"#), + ); + // The user serves something on 443 already. + let serve = tool.join("tailscale-data/serve.json"); + std::fs::write(&serve, r#"{"TCP":{"443":{"HTTPS":true}}}"#).unwrap(); + let mut remote = sandbox.remote(&["--tailscale"], &[&tool]); + // 443 is theirs, so the next free port is used, and the address says which. + assert_eq!(remote.first["url"], "https://laptop.tail1234.ts.net:8443"); + let calls = std::fs::read_to_string(tool.join("tailscale-data/calls.log")).unwrap(); + assert!( + calls.contains(&format!( + "serve\t--bg\t--https=8443\thttp://127.0.0.1:{}", + remote.port() + )), + "{calls}" + ); + let serving: Value = serde_json::from_str(&std::fs::read_to_string(&serve).unwrap()).unwrap(); + assert!(serving["TCP"]["8443"].is_object() && serving["TCP"]["443"].is_object()); + + assert!(remote.quit().success()); + let left: Value = serde_json::from_str(&std::fs::read_to_string(&serve).unwrap()).unwrap(); + assert!( + left["TCP"]["8443"].is_null() && left["TCP"]["443"].is_object(), + "{left}" + ); +} + +#[test] +fn tailscale_that_is_not_signed_in_is_left_alone_and_the_run_says_what_to_do() { + let sandbox = Sandbox::new(); + let tool = sandbox.tool("tailscale", &TAILSCALE); + tailscale_knows( + &tool, + Some(r#"{"BackendState":"NeedsLogin","Self":{"DNSName":""}}"#), + ); + let mut command = sandbox.azazel(&["remote", "--port", "0", "--tailscale"]); + let mut path = vec![tool.clone()]; + path.extend(std::env::split_paths( + &std::env::var_os("PATH").unwrap_or_default(), + )); + command.env("PATH", std::env::join_paths(path).unwrap()); + let output = command.output().unwrap(); + assert!(!output.status.success()); + let said = String::from_utf8_lossy(&output.stderr); + assert!(said.contains("tailscale up"), "{said}"); + let calls = std::fs::read_to_string(tool.join("tailscale-data/calls.log")).unwrap(); + assert!(!calls.contains("--bg"), "nothing was served: {calls}"); +} diff --git a/tests/fixtures/fake-cloudflared/Cargo.toml b/tests/fixtures/fake-cloudflared/Cargo.toml new file mode 100644 index 00000000..272b2be2 --- /dev/null +++ b/tests/fixtures/fake-cloudflared/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "fake-cloudflared" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +publish.workspace = true +license.workspace = true + +[lints] +workspace = true diff --git a/tests/fixtures/fake-cloudflared/src/main.rs b/tests/fixtures/fake-cloudflared/src/main.rs new file mode 100644 index 00000000..b1fc98aa --- /dev/null +++ b/tests/fixtures/fake-cloudflared/src/main.rs @@ -0,0 +1,32 @@ +//! A stand-in for `cloudflared` for tests. `fake-cloudflared tunnel --url ` writes the lines a +//! quick tunnel writes, with the address `https://fake-tunnel-test.trycloudflare.com`, to standard +//! error, records the url it was given in `cloudflared.url` beside the program, and then waits +//! until it is killed. Started without `tunnel`, it fails. + +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) != Some("tunnel") { + eprintln!("fake-cloudflared: unknown command {}", args.join(" ")); + return ExitCode::from(2); + } + let url = args + .iter() + .position(|arg| arg == "--url") + .and_then(|at| args.get(at + 1)) + .cloned() + .unwrap_or_default(); + let program = std::env::current_exe().unwrap_or_default(); + let beside: PathBuf = program.parent().unwrap_or(Path::new(".")).join("cloudflared.url"); + let _ = std::fs::write(beside, &url); + eprintln!("INF Requesting new quick Tunnel on trycloudflare.com..."); + eprintln!("INF +--------------------------------------------------------------------------------------------+"); + eprintln!("INF | Your quick Tunnel has been created! Visit it at (it may take some time to be reachable): |"); + eprintln!("INF | https://fake-tunnel-test.trycloudflare.com |"); + eprintln!("INF +--------------------------------------------------------------------------------------------+"); + loop { + std::thread::sleep(std::time::Duration::from_secs(3600)); + } +} diff --git a/tests/fixtures/fake-tailscale/Cargo.toml b/tests/fixtures/fake-tailscale/Cargo.toml new file mode 100644 index 00000000..874800ac --- /dev/null +++ b/tests/fixtures/fake-tailscale/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "fake-tailscale" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +publish.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +serde_json.workspace = true diff --git a/tests/fixtures/fake-tailscale/src/main.rs b/tests/fixtures/fake-tailscale/src/main.rs new file mode 100644 index 00000000..7a7b1cba --- /dev/null +++ b/tests/fixtures/fake-tailscale/src/main.rs @@ -0,0 +1,64 @@ +//! A stand-in for `tailscale` for tests. What it knows is in the directory `tailscale-data` beside +//! the program, so a test copies the program to a directory of its own: +//! +//! - `status --json` prints `status.json`, or says the daemon is not running (exit 1); +//! - `serve status --json` prints `serve.json`, or `{}`; +//! - `serve --bg --https= ` adds the port to `serve.json`; +//! - `serve --https= off` removes it. +//! +//! Every call adds a line to `calls.log`: its arguments, with a tab between them. + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use serde_json::{Value, json}; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let program = std::env::current_exe().unwrap_or_default(); + let data: PathBuf = program.parent().unwrap_or(Path::new(".")).join("tailscale-data"); + if let Ok(mut log) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(data.join("calls.log")) + { + let _ = writeln!(log, "{}", args.join("\t")); + } + let words: Vec<&str> = args.iter().map(String::as_str).collect(); + let serve_file = data.join("serve.json"); + let mut serve: Value = std::fs::read_to_string(&serve_file) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_else(|| json!({})); + let https = args + .iter() + .find_map(|arg| arg.strip_prefix("--https=")) + .unwrap_or_default() + .to_string(); + match words.as_slice() { + ["status", "--json"] => match std::fs::read_to_string(data.join("status.json")) { + Ok(status) => println!("{status}"), + Err(_) => { + eprintln!("failed to connect to local tailscaled; it doesn't appear to be running"); + return ExitCode::from(1); + } + }, + ["serve", "status", "--json"] => println!("{serve}"), + ["serve", "--bg", _, target] if target.starts_with("http://127.0.0.1:") => { + serve["TCP"][&https] = json!({ "HTTPS": true }); + let _ = std::fs::write(&serve_file, serve.to_string()); + } + ["serve", _, "off"] => { + if let Some(tcp) = serve["TCP"].as_object_mut() { + tcp.remove(&https); + } + let _ = std::fs::write(&serve_file, serve.to_string()); + } + _ => { + eprintln!("fake-tailscale: unknown command {}", args.join(" ")); + return ExitCode::from(2); + } + } + ExitCode::SUCCESS +} diff --git a/tests/fixtures/scripts/web_session.json b/tests/fixtures/scripts/web_session.json new file mode 100644 index 00000000..9d3e2d6d --- /dev/null +++ b/tests/fixtures/scripts/web_session.json @@ -0,0 +1,17 @@ +{ + "lead": [ + { + "reply": { + "tool_calls": [ + { "id": "c1", "name": "write", "input": { "path": "hello.txt", "content": "hello from azazel\n" } } + ] + } + }, + { + "reply": { + "tool_calls": [{ "id": "c2", "name": "read", "input": { "path": "hello.txt" } }] + } + }, + { "reply": { "text": "Wrote and verified hello.txt." } } + ] +} From 2cb64edfe37883d87227ac318a4f8a3e319ccc92 Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:58:32 +0000 Subject: [PATCH 10/27] Docs and changelog for azazel remote --- CHANGELOG.md | 4 ++ docs/background-and-remote.md | 2 + docs/configuration.md | 10 ++++- docs/remote.md | 73 +++++++++++++++++++++++++++++++++-- 4 files changed, 85 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8fc66fd..979189b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ GitHub are its section here. ## [Unreleased] +### Added + +- `azazel remote` serves the background sessions of this machine to a web page on `127.0.0.1:7420`. A browser pairs with a single-use link or QR code, watches a session live and, with a control link, answers approvals and questions, steers and stops it. `--tunnel` reaches it from a phone through a Cloudflare quick tunnel (azazel offers to install `cloudflared`), `--tailscale` through Tailscale; `--view` makes a watch-only link. Settings are in `[remote]`; see `docs/remote.md`. Built with the `remote` Cargo feature. + ## [0.10.5] - 2026-11-15 ### Added diff --git a/docs/background-and-remote.md b/docs/background-and-remote.md index 0ec50017..f7ebe56d 100644 --- a/docs/background-and-remote.md +++ b/docs/background-and-remote.md @@ -5,6 +5,8 @@ that goes on after you close the terminal; you look in, answer it, or take it ov mechanism lets the UI on your machine show a session that runs on another machine over SSH, and lets a [schedule](#schedules) run a prompt at a time or when something happens. +To watch and steer these sessions from a browser or a phone, see [remote](remote.md). + There is no daemon. Each background session is one process (`azazel host`, started for you) that ends when it is no longer needed. When that process is killed in the middle of its work, the session is [started again where it stopped](#when-a-background-session-dies) the next time you attach. diff --git a/docs/configuration.md b/docs/configuration.md index 5dba1135..1990ee0f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -248,6 +248,13 @@ Hook events: `pre_tool_use`, `post_tool_use`, `post_tool_use_failure`, `user_pro | `[web]` | `search` | `"auto"` | `auto`, `provider`, `brave`, `tavily`, `exa`, `searxng` or `duckduckgo`; see [web and browser](web-and-browser.md) | | | `searxng_url` | `""` | Address of a SearXNG instance | | | `provider_search` | `true` | Under `search = "auto"`, search through the lead model's provider first when it has a search tool; see [the provider's own search](web-and-browser.md#the-providers-own-search) | +| `[remote]` | `port` | `7420` | The port `azazel remote` listens on, on this machine only; when it is taken the next nine are tried. 0 lets the system choose; see [remote](remote.md) | +| | `access` | `"cloudflare"` | How `azazel remote --share` and `/remote` reach the server from another device: `cloudflare` (a quick tunnel) or `tailscale` | +| | `public_url` | `""` | The address of your own tunnel or reverse proxy in front of the server; it becomes the origin of the links and an accepted origin | +| | `link_minutes` | `15` | Minutes a pairing link works (once) | +| | `device_hours` | `24` | Hours a paired device stays signed in | +| | `redact` | `true` | Replace API keys and tokens in the messages and tool results sent to a browser | +| | `allow_bypass` | `false` | Let a browser with control access switch to the `bypass` mode | | `[telemetry]` | `exporter` | `"off"` | `off`, `otlp` or `langsmith`; see [trace export](#trace-export) | | | `endpoint` | `""` | Collector address; empty uses the exporter's default | | | `project` | `""` | Project name shown by the backend: LangSmith's project, `service.name` over OTLP | @@ -381,7 +388,7 @@ Gated settings: `hooks`, `providers`, `permissions.allow`, `permissions.destruct is `bypass`, `lsp`, `debug.adapters`, `verify.commands`, `tools.shell`, `tools.format`, `tools.format_on_write`, `tools.check`, `tools.scan`, `tools.eval`, `browser.path`, `editor.command`, `voice.record_command`, `voice.stt_command`, `voice.play_command`, `advisor`, `telemetry`, `statusline.command`, -`triggers.mode`, `triggers.github_authors`, `triggers.slack_users`, `triggers.slack_url`. +`triggers.mode`, `triggers.github_authors`, `triggers.slack_users`, `triggers.slack_url`, `remote`. The interactive UI asks once per project, before it starts: `Trust this project? Its config can run commands. [y/N]`. The answer is stored in `~/.azazel/trust.json`. In the UI, `/trust` shows the decision and what it @@ -498,6 +505,7 @@ unknown tier or preset) exits with status 2. |---|---|---| | `azazel init` | | Choose the default model and create the project's config file; see [getting started](getting-started.md) | | `azazel doctor` | | Check the installation and the project's setup | +| `azazel remote` | | Follow and steer the background sessions from a browser or a phone: `azazel remote [--port N] [--view] [--json] [--share] [--tunnel] [--tailscale] [--public-url URL]`; see [remote](remote.md) | | `azazel update` | | Install the newest release; see [updating](getting-started.md#updating) | | `azazel completions` | | Print a completion script for a shell | | `azazel changelog` | | What changed in each release | diff --git a/docs/remote.md b/docs/remote.md index 8abb230e..39f393ea 100644 --- a/docs/remote.md +++ b/docs/remote.md @@ -14,6 +14,73 @@ The page speaks the [RPC protocol](rpc.md) unchanged: one JSON object per WebSoc directions. This page describes what is around that: how a browser gets in, which commands each kind of access may send, and the routes the server answers. +## Using it + +```sh +azazel bg "run the test suite and fix what fails" +azazel remote +``` + +`azazel remote` serves every background session of this machine on `http://127.0.0.1:7420` and prints a pairing +link and a QR code. Open the link in a browser on this machine, and the page lists the sessions. Nothing listens on +the network: the server binds `127.0.0.1` only. + +| Flag | Does | +|---|---| +| `--port ` | The port to listen on (`[remote] port`, 7420). When it is taken the next nine are tried and the one taken is printed. `0` lets the system choose | +| `--view` | Makes the first link a view link: it can watch but not answer or steer | +| `--json` | Prints `{"url", "pair", "port"}` as the first line of standard output; the rest goes to standard error | +| `--tunnel` | Reaches the server from other devices through a [Cloudflare quick tunnel](#from-a-phone-cloudflare) | +| `--tailscale` | Reaches it through [Tailscale](#from-a-phone-tailscale) | +| `--share` | Reaches it the way `[remote] access` says, `cloudflare` or `tailscale` | +| `--public-url ` | The address of your own tunnel or reverse proxy in front of the server | + +While it runs, type `l` and Enter for a new control link, `v` for a new view link, `r` to sign every device out and +void every link, and `q` to stop. Ending the server signs every device out; paired devices are not kept across +restarts. + +## From a phone: Cloudflare + +```sh +azazel remote --tunnel +``` + +This runs `cloudflared tunnel --url http://127.0.0.1:`, reads the `https://.trycloudflare.com` address it +prints, and shows the pairing link and QR code for that address. No Cloudflare account or domain is needed. The +tunnel stops when `azazel remote` does, and the address changes on every start, so devices pair again each time. + +`cloudflared` is found on `PATH` or in `~/.azazel/remote/`. When it is missing, a run at a terminal asks once: + +- **Install it for me** downloads the official release for your platform from + `github.com/cloudflare/cloudflared/releases/latest` into `~/.azazel/remote/`. +- **Show me how** prints the install command and the download page. +- **Cancel** ends the run. + +A run without a terminal, and a download that fails, print the same help: `winget install --id Cloudflare.cloudflared` +on Windows, `brew install cloudflared` on macOS, your distribution's package or the release binary on Linux, and +. + +The address is public, so the pairing link is what protects it: it works once, for 15 minutes, and the server +accepts the tunnel's host and nothing else besides this machine. Quick tunnels have no uptime guarantee and +allow 200 requests in flight; the page uses one WebSocket and no server-sent events, which they do not carry. To use +a named tunnel or a reverse proxy of your own, set `[remote] public_url` or pass `--public-url`. + +## From a phone: Tailscale + +```sh +azazel remote --tailscale +``` + +This asks `tailscale status --json` for the name of this machine on your tailnet, runs `tailscale serve --bg +--https= http://127.0.0.1:` on the first of the HTTPS ports 443, 8443 and 10000 that you do not serve +yet, and shows the link and QR code for `https://.ts.net`. The phone needs the Tailscale app signed in to the +same account. When the server stops, only the entry azazel added is removed (`tailscale serve --https= off`); +your other serve settings stay. + +azazel never installs Tailscale. When it is missing or not signed in, the run says what to do: install it from +, sign in with `tailscale up`, and install the app on the phone. Turn on MagicDNS and +HTTPS certificates in the Tailscale admin console if the machine has no name. + ## The HTTP and WebSocket API This section is the contract between the server (`crates/azazel-remote`) and the web page (`web/`). Everything the @@ -30,11 +97,11 @@ page does goes through the routes below. - **Authentication.** Every `/api/` route except `POST /api/pair` needs a signed-in device: the cookie `azazel_device` (what a browser has after pairing) or the header `Authorization: Bearer ` (scripts and tests). Without one the answer is `401`. -- **Host check.** The `Host` header must name the server: `127.0.0.1:`, `localhost:`, `[::1]:`, a - LAN address of this machine, or the host of `remote.public_url`. Anything else gets `421`. This stops DNS +- **Host check.** The `Host` header must name the server: `127.0.0.1:`, `localhost:`, `[::1]:`, the + host of the tunnel, or the host of `remote.public_url`. Anything else gets `421`. This stops DNS rebinding. - **Origin check.** A request that has an `Origin` header must carry one of the allowed origins (the same - addresses as above, with the scheme the server uses, and `remote.public_url`); otherwise `403`. A request + addresses as above, with the scheme the server uses); otherwise `403`. A request signed in by cookie must have an `Origin`; a request with a Bearer token may leave it out. - Answers on `/api/` carry `Cache-Control: no-store`. Every answer carries `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, and a `Content-Security-Policy` of `default-src 'self'; connect-src 'self'; From 04fc24e59adec71f4a747f9d985f804304fb9915 Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:00:51 +0000 Subject: [PATCH 11/27] remote: clippy fixes --- crates/azazel-cli/src/lib.rs | 4 +- crates/azazel-core/src/settings.rs | 4 +- crates/azazel-remote/build.rs | 4 +- crates/azazel-remote/src/assets.rs | 5 ++- crates/azazel-remote/src/http.rs | 36 ++++++++++-------- crates/azazel-remote/tests/it/common.rs | 41 +++++++++++++++++---- crates/azazel-remote/tests/it/http.rs | 2 +- crates/azazel-remote/tests/it/main.rs | 2 + crates/azazel-tools/src/lsp/install.rs | 2 + tests/fixtures/fake-cloudflared/src/main.rs | 16 ++++++-- 10 files changed, 81 insertions(+), 35 deletions(-) diff --git a/crates/azazel-cli/src/lib.rs b/crates/azazel-cli/src/lib.rs index d4ae014c..5424bc74 100644 --- a/crates/azazel-cli/src/lib.rs +++ b/crates/azazel-cli/src/lib.rs @@ -24,8 +24,6 @@ pub mod history; pub mod hooks; #[cfg(feature = "detach")] pub mod host; -#[cfg(feature = "remote")] -pub mod remote; pub mod init; pub mod inventory; pub mod login; @@ -41,6 +39,8 @@ pub mod models; pub mod orchestration; pub mod pkg; pub mod print; +#[cfg(feature = "remote")] +pub mod remote; pub mod reports; pub mod resets; pub mod resources; diff --git a/crates/azazel-core/src/settings.rs b/crates/azazel-core/src/settings.rs index ee321035..8ead72b4 100644 --- a/crates/azazel-core/src/settings.rs +++ b/crates/azazel-core/src/settings.rs @@ -13,8 +13,8 @@ use toml::{Table, Value}; use crate::config::{ AdvisorWhen, Autocomplete, CacheWarming, CheckReport, Config, DesktopNotify, DestructivePolicy, DiffView, EditorMode, GlyphSetting, ImageMode, Indicator, LspInstall, PatchMode, PermissionMode, ProcessPriority, - QueueMode, ReadGuard, RemoteAccess, SessionResume, StatusPreset, StatusSeparator, TelemetryExporter, ToolStyle, - WorktreeTarget, WriteSeverity, + QueueMode, ReadGuard, RemoteAccess, SessionResume, StatusPreset, StatusSeparator, TelemetryExporter, + ToolStyle, WorktreeTarget, WriteSeverity, }; /// A page of the settings screen. diff --git a/crates/azazel-remote/build.rs b/crates/azazel-remote/build.rs index a267d6db..706a8a69 100644 --- a/crates/azazel-remote/build.rs +++ b/crates/azazel-remote/build.rs @@ -58,7 +58,9 @@ fn main() { } fn walk(root: &Path, dir: &Path, files: &mut Vec<(String, Vec)>) { - let Ok(entries) = std::fs::read_dir(dir) else { return }; + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { diff --git a/crates/azazel-remote/src/assets.rs b/crates/azazel-remote/src/assets.rs index 377a2d4f..dbb41dbd 100644 --- a/crates/azazel-remote/src/assets.rs +++ b/crates/azazel-remote/src/assets.rs @@ -41,7 +41,10 @@ pub(crate) fn cache_control(asset: &Asset) -> &'static str { pub(crate) fn inflate(asset: &Asset) -> Vec { let mut out = Vec::new(); // The bytes were made by the build script from a file it read; they are a valid gzip stream. - if flate2::read::GzDecoder::new(asset.gz).read_to_end(&mut out).is_err() { + if flate2::read::GzDecoder::new(asset.gz) + .read_to_end(&mut out) + .is_err() + { out.clear(); } out diff --git a/crates/azazel-remote/src/http.rs b/crates/azazel-remote/src/http.rs index cda8dc4e..4c5ff051 100644 --- a/crates/azazel-remote/src/http.rs +++ b/crates/azazel-remote/src/http.rs @@ -63,7 +63,7 @@ fn error(status: u16, message: &str) -> Res { json_reply(status, json!({ "error": message })) } -fn header<'a>(req: &'a Request, name: impl hyper::header::AsHeaderName) -> Option<&'a str> { +fn header(req: &Request, name: impl hyper::header::AsHeaderName) -> Option<&str> { req.headers().get(name).and_then(|v| v.to_str().ok()) } @@ -85,25 +85,29 @@ fn authenticate( shared: &Shared, req: &Request, needs_origin: bool, -) -> Result, Res> { +) -> Result, Box> { let Some((token, cookie)) = token(req) else { return Ok(None); }; if cookie && needs_origin && header(req, ORIGIN).is_none() { - return Err(error( + return Err(Box::new(error( 403, "a request signed in by cookie must say where it comes from (`Origin`)", - )); + ))); } Ok(shared.auth.device(&token).map(|device| (token, device))) } -fn signed_in(shared: &Shared, req: &Request, needs_origin: bool) -> Result<(String, Device), Res> { +fn signed_in( + shared: &Shared, + req: &Request, + needs_origin: bool, +) -> Result<(String, Device), Box> { authenticate(shared, req, needs_origin)?.ok_or_else(|| { - error( + Box::new(error( 401, "not signed in: open the pairing link again, or ask for a new one", - ) + )) }) } @@ -136,7 +140,7 @@ async fn route(shared: &Arc, peer: IpAddr, mut req: Request) - "version": env!("CARGO_PKG_VERSION"), }), ), - Err(res) => res, + Err(res) => *res, }, (Method::GET, "/api/sessions") => match signed_in(shared, &req, false) { Ok(_) => { @@ -144,7 +148,7 @@ async fn route(shared: &Arc, peer: IpAddr, mut req: Request) - sessions.sort_by(|a, b| b.started.cmp(&a.started)); json_reply(200, json!({ "sessions": sessions })) } - Err(res) => res, + Err(res) => *res, }, (Method::POST, "/api/links") => links(shared, req).await, (Method::POST, "/api/logout") => match signed_in(shared, &req, true) { @@ -159,7 +163,7 @@ async fn route(shared: &Arc, peer: IpAddr, mut req: Request) - ); res } - Err(res) => res, + Err(res) => *res, }, (Method::GET, p) if p.starts_with("/api/ws/") => socket(shared, &mut req, &p["/api/ws/".len()..]), (_, "/api/pair" | "/api/me" | "/api/sessions" | "/api/links" | "/api/logout") => { @@ -207,12 +211,12 @@ fn page(req: &Request) -> Res { res } -async fn body(req: Request) -> Result { +async fn body(req: Request) -> Result> { Limited::new(req.into_body(), BODY_LIMIT) .collect() .await .map(|collected| collected.to_bytes()) - .map_err(|_| error(413, "the request is too large")) + .map_err(|_| Box::new(error(413, "the request is too large"))) } #[derive(Deserialize)] @@ -227,7 +231,7 @@ async fn pair(shared: &Arc, peer: IpAddr, req: Request) -> Res let secure = shared.is_https_host(&host); let bytes = match body(req).await { Ok(bytes) => bytes, - Err(res) => return res, + Err(res) => return *res, }; let Ok(pair) = serde_json::from_slice::(&bytes) else { return error(400, "send {\"secret\": \"…\"}"); @@ -278,12 +282,12 @@ struct LinkBody { async fn links(shared: &Arc, req: Request) -> Res { let device = match signed_in(shared, &req, true) { Ok((_, device)) => device, - Err(res) => return res, + Err(res) => return *res, }; let origin = header(&req, ORIGIN).map(str::to_string); let bytes = match body(req).await { Ok(bytes) => bytes, - Err(res) => return res, + Err(res) => return *res, }; let Ok(wanted) = serde_json::from_slice::(&bytes) else { return error(400, "send {\"access\": \"view\"} or {\"access\": \"control\"}"); @@ -302,7 +306,7 @@ async fn links(shared: &Arc, req: Request) -> Res { fn socket(shared: &Arc, req: &mut Request, id: &str) -> Res { let device = match authenticate(shared, req, true) { Ok(device) => device.map(|(_, device)| device), - Err(res) => return res, + Err(res) => return *res, }; let wants = |name: &str, wanted: &str| { header(req, name).is_some_and(|v| v.split(',').any(|part| part.trim().eq_ignore_ascii_case(wanted))) diff --git a/crates/azazel-remote/tests/it/common.rs b/crates/azazel-remote/tests/it/common.rs index 82916cdf..9761a685 100644 --- a/crates/azazel-remote/tests/it/common.rs +++ b/crates/azazel-remote/tests/it/common.rs @@ -116,7 +116,10 @@ impl Answer { /// One HTTP/1.1 request on a connection of its own. `Host` is the server's unless given. pub async fn request(port: u16, method: &str, path: &str, headers: &[(&str, &str)], body: &str) -> Answer { - let mut head = format!("{method} {path} HTTP/1.1\r\nConnection: close\r\nContent-Length: {}\r\n", body.len()); + let mut head = format!( + "{method} {path} HTTP/1.1\r\nConnection: close\r\nContent-Length: {}\r\n", + body.len() + ); if !headers.iter().any(|(name, _)| name.eq_ignore_ascii_case("host")) { head.push_str(&format!("Host: 127.0.0.1:{port}\r\n")); } @@ -128,11 +131,21 @@ pub async fn request(port: u16, method: &str, path: &str, headers: &[(&str, &str stream.write_all(head.as_bytes()).await.unwrap(); stream.write_all(body.as_bytes()).await.unwrap(); let mut raw = Vec::new(); - tokio::time::timeout(WAIT, stream.read_to_end(&mut raw)).await.unwrap().unwrap(); + tokio::time::timeout(WAIT, stream.read_to_end(&mut raw)) + .await + .unwrap() + .unwrap(); let split = raw.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); let head = String::from_utf8_lossy(&raw[..split]).into_owned(); let mut lines = head.lines(); - let status = lines.next().unwrap().split_whitespace().nth(1).unwrap().parse().unwrap(); + let status = lines + .next() + .unwrap() + .split_whitespace() + .nth(1) + .unwrap() + .parse() + .unwrap(); let headers = lines .filter_map(|line| line.split_once(':')) .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string())) @@ -156,10 +169,16 @@ pub async fn pair(server: &Server, access: Access) -> String { pub type Socket = WebSocketStream>; pub async fn connect(port: u16, id: &str, token: Option<&str>) -> Socket { - let mut request = format!("ws://127.0.0.1:{port}/api/ws/{id}").into_client_request().unwrap(); - request.headers_mut().insert("origin", format!("http://127.0.0.1:{port}").parse().unwrap()); + let mut request = format!("ws://127.0.0.1:{port}/api/ws/{id}") + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", format!("http://127.0.0.1:{port}").parse().unwrap()); if let Some(token) = token { - request.headers_mut().insert("authorization", format!("Bearer {token}").parse().unwrap()); + request + .headers_mut() + .insert("authorization", format!("Bearer {token}").parse().unwrap()); } tokio_tungstenite::connect_async(request).await.unwrap().0 } @@ -167,7 +186,10 @@ pub async fn connect(port: u16, id: &str, token: Option<&str>) -> Socket { /// The next text message, as JSON. pub async fn next_json(socket: &mut Socket) -> serde_json::Value { loop { - match tokio::time::timeout(WAIT, socket.next()).await.expect("a message") { + match tokio::time::timeout(WAIT, socket.next()) + .await + .expect("a message") + { Some(Ok(Message::Text(text))) => return serde_json::from_str(text.as_str()).unwrap(), Some(Ok(Message::Ping(_) | Message::Pong(_))) => {} other => panic!("expected a text message, got {other:?}"), @@ -191,6 +213,9 @@ pub async fn send(socket: &mut Socket, value: serde_json::Value) { } pub async fn sent(received: &mut mpsc::UnboundedReceiver) -> serde_json::Value { - let line = tokio::time::timeout(WAIT, received.recv()).await.expect("a command").unwrap(); + let line = tokio::time::timeout(WAIT, received.recv()) + .await + .expect("a command") + .unwrap(); serde_json::from_str(&line).unwrap() } diff --git a/crates/azazel-remote/tests/it/http.rs b/crates/azazel-remote/tests/it/http.rs index e4b4afb8..4569f6fb 100644 --- a/crates/azazel-remote/tests/it/http.rs +++ b/crates/azazel-remote/tests/it/http.rs @@ -254,7 +254,7 @@ async fn a_public_address_is_accepted_and_makes_the_cookie_secure() { async fn a_taken_port_gives_way_to_the_next_one() { // Tests running beside this one hold ports of their own, so the port taken here is one whose // successor is free. - let (taken, port) = loop { + let (_taken, port) = loop { let taken = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = taken.local_addr().unwrap().port(); if port < u16::MAX - 10 diff --git a/crates/azazel-remote/tests/it/main.rs b/crates/azazel-remote/tests/it/main.rs index df034837..90f8413b 100644 --- a/crates/azazel-remote/tests/it/main.rs +++ b/crates/azazel-remote/tests/it/main.rs @@ -1,3 +1,5 @@ +#![allow(clippy::unwrap_used)] + //! The server over real sockets: pairing, the checks on `Host` and `Origin`, the policy on a //! WebSocket, and the limits. The sessions behind it are a stand-in. diff --git a/crates/azazel-tools/src/lsp/install.rs b/crates/azazel-tools/src/lsp/install.rs index deb9604f..0cae1fd4 100644 --- a/crates/azazel-tools/src/lsp/install.rs +++ b/crates/azazel-tools/src/lsp/install.rs @@ -418,6 +418,8 @@ fn unpack(bytes: &[u8], kind: Archive, dir: &Path) -> Result { #[cfg(test)] mod tests { + use std::io::Write; + use super::*; #[test] diff --git a/tests/fixtures/fake-cloudflared/src/main.rs b/tests/fixtures/fake-cloudflared/src/main.rs index b1fc98aa..eda0f46a 100644 --- a/tests/fixtures/fake-cloudflared/src/main.rs +++ b/tests/fixtures/fake-cloudflared/src/main.rs @@ -22,10 +22,18 @@ fn main() -> ExitCode { let beside: PathBuf = program.parent().unwrap_or(Path::new(".")).join("cloudflared.url"); let _ = std::fs::write(beside, &url); eprintln!("INF Requesting new quick Tunnel on trycloudflare.com..."); - eprintln!("INF +--------------------------------------------------------------------------------------------+"); - eprintln!("INF | Your quick Tunnel has been created! Visit it at (it may take some time to be reachable): |"); - eprintln!("INF | https://fake-tunnel-test.trycloudflare.com |"); - eprintln!("INF +--------------------------------------------------------------------------------------------+"); + eprintln!( + "INF +--------------------------------------------------------------------------------------------+" + ); + eprintln!( + "INF | Your quick Tunnel has been created! Visit it at (it may take some time to be reachable): |" + ); + eprintln!( + "INF | https://fake-tunnel-test.trycloudflare.com |" + ); + eprintln!( + "INF +--------------------------------------------------------------------------------------------+" + ); loop { std::thread::sleep(std::time::Duration::from_secs(3600)); } From 242454033c2617310dc3f82d69f7dd73ad36a8ea Mon Sep 17 00:00:00 2001 From: sin <92541374+sinnafuls@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:03:43 +0000 Subject: [PATCH 12/27] Web: design pass (tokens, Geist, brand mark, tool cards, composer, sheets, hub) --- web/src/app.css | 341 ++++++++++++++---- web/src/lib/components/AgentHub.svelte | 162 +++++---- web/src/lib/components/ApprovalSheet.svelte | 8 +- web/src/lib/components/Brand.svelte | 34 +- web/src/lib/components/Composer.svelte | 14 +- web/src/lib/components/DiffView.svelte | 55 +-- web/src/lib/components/PairDevice.svelte | 2 +- web/src/lib/components/QuestionSheet.svelte | 9 +- web/src/lib/components/SessionList.svelte | 52 ++- web/src/lib/components/Sheet.svelte | 88 ++++- web/src/lib/components/StateDot.svelte | 37 +- web/src/lib/components/StatusBar.svelte | 44 ++- web/src/lib/components/ToolCard.svelte | 116 ++++-- web/src/lib/components/Transcript.svelte | 91 ++--- web/src/lib/components/UsagePanel.svelte | 91 +++-- web/src/lib/fonts/OFL-Geist.txt | 93 +++++ .../lib/fonts/geist-latin-wght-normal.woff2 | Bin 0 -> 29400 bytes .../fonts/geist-mono-latin-wght-normal.woff2 | Bin 0 -> 23128 bytes web/src/lib/session/reduce.ts | 9 +- web/src/routes/+layout.svelte | 17 +- web/src/routes/s/[id]/+layout.svelte | 12 +- 21 files changed, 880 insertions(+), 395 deletions(-) create mode 100644 web/src/lib/fonts/OFL-Geist.txt create mode 100644 web/src/lib/fonts/geist-latin-wght-normal.woff2 create mode 100644 web/src/lib/fonts/geist-mono-latin-wght-normal.woff2 diff --git a/web/src/app.css b/web/src/app.css index b8c880a4..06b2edd0 100644 --- a/web/src/app.css +++ b/web/src/app.css @@ -1,39 +1,92 @@ @import 'tailwindcss'; /* - * Tokens use shadcn-svelte's names and are defined once with light-dark(). The page follows the - * system; `html.light` / `html.dark` (the theme toggle) overrides it. One accent (amber) marks - * "this needs you" and the primary action. Green, red and blue are status only. + * azazel web: design tokens. + * + * Reference: Linear's system (a four-step surface ladder carried by hairlines, one scarce accent, + * quiet type), with a terminal's mono voice in tool output. + * + * Three layers: primitives (the ramps, in OKLCH, hue 268 for neutrals so every grey leans the same way + * as the canvas), semantic roles (what components use), and Tailwind's @theme mapping at the bottom. + * light-dark() picks the value per theme; `html.light` / `html.dark` overrides the system choice. + * + * Accent: ember (hue 45). It means "this needs you" and "the primary action", nothing else. + * Status colours (blue working, green done, red failed) never decorate. */ + +@font-face { + font-family: 'Geist'; + src: url('./lib/fonts/geist-latin-wght-normal.woff2') format('woff2-variations'); + font-weight: 100 900; + font-style: normal; + font-display: swap; +} +@font-face { + font-family: 'Geist Mono'; + src: url('./lib/fonts/geist-mono-latin-wght-normal.woff2') format('woff2-variations'); + font-weight: 100 900; + font-style: normal; + font-display: swap; +} + :root { color-scheme: light dark; - --background: light-dark(#f6f6f7, #0f1012); - --foreground: light-dark(#17181b, #e6e7e9); - --card: light-dark(#ffffff, #15171a); - --raised: light-dark(#eeeef0, #1c1e22); - --border: light-dark(#dcdde1, #272a30); - --input: light-dark(#c4c7ce, #353941); - --muted-foreground: light-dark(#575c66, #8d929c); - --primary: light-dark(#d98a1c, #e8a23c); - --primary-foreground: light-dark(#1c1305, #1a1204); - --accent-text: light-dark(#8a4b00, #f0b45a); - --ring: light-dark(#b86f06, #e8a23c); - --destructive: light-dark(#c4323a, #f0646a); - --destructive-foreground: light-dark(#ffffff, #1a0709); - --success: light-dark(#197a47, #5cc98a); - --info: light-dark(#1f5fbf, #6ea8fe); - --diff-add: light-dark(#dcf3e5, #12281c); - --diff-del: light-dark(#fbe3e4, #301518); - --diff-add-fg: light-dark(#14613a, #7fdba4); - --diff-del-fg: light-dark(#a2262d, #f58d92); - --muted: var(--raised); - --secondary: var(--raised); - --secondary-foreground: var(--foreground); - --accent: var(--raised); - --accent-foreground: var(--foreground); - --popover: var(--card); - --popover-foreground: var(--foreground); - --card-foreground: var(--foreground); + + /* surface ladder: canvas < sidebar < card < raised < overlay */ + --background: light-dark(oklch(0.978 0.004 268), oklch(0.155 0.008 268)); + --sidebar: light-dark(oklch(0.962 0.005 268), oklch(0.185 0.009 268)); + --card: light-dark(oklch(1 0 0), oklch(0.205 0.01 268)); + --raised: light-dark(oklch(0.947 0.006 268), oklch(0.245 0.011 268)); + --overlay: light-dark(oklch(1 0 0), oklch(0.275 0.012 268)); + --inset: light-dark(oklch(0.965 0.005 268), oklch(0.13 0.008 268)); + + /* hairlines */ + --border: light-dark(oklch(0.905 0.006 268), oklch(0.285 0.012 268)); + --border-strong: light-dark(oklch(0.84 0.008 268), oklch(0.36 0.013 268)); + --input: light-dark(oklch(0.8 0.009 268), oklch(0.4 0.014 268)); + + /* ink: three strengths */ + --foreground: light-dark(oklch(0.215 0.012 268), oklch(0.955 0.004 268)); + --ink-2: light-dark(oklch(0.38 0.012 268), oklch(0.82 0.007 268)); + --muted-foreground: light-dark(oklch(0.5 0.012 268), oklch(0.7 0.011 268)); + --faint: light-dark(oklch(0.62 0.01 268), oklch(0.56 0.012 268)); + + /* accent: ember */ + --primary: light-dark(oklch(0.66 0.19 45), oklch(0.74 0.17 50)); + --primary-hover: light-dark(oklch(0.62 0.19 45), oklch(0.79 0.16 52)); + --primary-foreground: oklch(0.2 0.04 45); + --accent-text: light-dark(oklch(0.5 0.17 40), oklch(0.8 0.14 60)); + --ring: light-dark(oklch(0.6 0.19 45), oklch(0.74 0.17 50)); + + /* status */ + --info: light-dark(oklch(0.55 0.17 255), oklch(0.74 0.12 250)); + --success: light-dark(oklch(0.52 0.14 155), oklch(0.77 0.15 155)); + --destructive: light-dark(oklch(0.53 0.2 25), oklch(0.72 0.16 22)); + --destructive-foreground: light-dark(oklch(0.99 0 0), oklch(0.16 0.03 22)); + + /* diff */ + --diff-add: light-dark(oklch(0.95 0.045 155), oklch(0.27 0.06 155)); + --diff-del: light-dark(oklch(0.955 0.03 20), oklch(0.27 0.06 22)); + --diff-add-fg: light-dark(oklch(0.4 0.11 155), oklch(0.82 0.13 155)); + --diff-del-fg: light-dark(oklch(0.46 0.15 22), oklch(0.82 0.1 22)); + + /* depth: neutral-tinted, a faint top highlight on lifted dark surfaces */ + --shadow-sm: 0 1px 2px light-dark(oklch(0.3 0.02 268 / 0.08), oklch(0 0 0 / 0.4)); + --shadow-md: + 0 4px 14px -2px light-dark(oklch(0.3 0.02 268 / 0.12), oklch(0 0 0 / 0.5)), + 0 1px 2px light-dark(oklch(0.3 0.02 268 / 0.06), oklch(0 0 0 / 0.3)); + --shadow-lg: + 0 18px 48px -8px light-dark(oklch(0.3 0.02 268 / 0.22), oklch(0 0 0 / 0.65)), + 0 4px 12px light-dark(oklch(0.3 0.02 268 / 0.08), oklch(0 0 0 / 0.35)); + --edge: inset 0 1px 0 light-dark(oklch(1 0 0 / 0.6), oklch(1 0 0 / 0.045)); + --glow: 0 0 0 3px color-mix(in oklab, var(--ring) 28%, transparent); + + /* motion */ + --ease-out: cubic-bezier(0.22, 1, 0.36, 1); + --ease-in: cubic-bezier(0.5, 0, 0.75, 0); + --dur-fast: 120ms; + --dur: 180ms; + --dur-slow: 260ms; } :root.light { color-scheme: light; @@ -44,12 +97,26 @@ @theme inline { --color-background: var(--background); + --color-sidebar: var(--sidebar); --color-foreground: var(--foreground); --color-card: var(--card); + --color-card-foreground: var(--foreground); + --color-popover: var(--overlay); + --color-popover-foreground: var(--foreground); --color-raised: var(--raised); + --color-overlay: var(--overlay); + --color-inset: var(--inset); --color-border: var(--border); + --color-border-strong: var(--border-strong); --color-input: var(--input); + --color-ink-2: var(--ink-2); + --color-muted: var(--raised); --color-muted-foreground: var(--muted-foreground); + --color-faint: var(--faint); + --color-secondary: var(--raised); + --color-secondary-foreground: var(--foreground); + --color-accent: var(--raised); + --color-accent-foreground: var(--foreground); --color-primary: var(--primary); --color-primary-foreground: var(--primary-foreground); --color-accent-text: var(--accent-text); @@ -62,26 +129,37 @@ --color-diff-del: var(--diff-del); --color-diff-add-fg: var(--diff-add-fg); --color-diff-del-fg: var(--diff-del-fg); - --color-muted: var(--muted); - --color-secondary: var(--secondary); - --color-secondary-foreground: var(--secondary-foreground); - --color-accent: var(--accent); - --color-accent-foreground: var(--accent-foreground); - --color-popover: var(--popover); - --color-popover-foreground: var(--popover-foreground); - --color-card-foreground: var(--card-foreground); + --font-sans: - ui-sans-serif, system-ui, -apple-system, 'Segoe UI Variable', 'Segoe UI', Roboto, - 'Helvetica Neue', Arial, sans-serif; - --font-mono: - ui-monospace, 'SF Mono', 'Cascadia Mono', 'JetBrains Mono', Menlo, Consolas, 'Liberation Mono', - monospace; - --radius-sm: 4px; - --radius-md: 6px; - --radius-lg: 10px; - --radius-xl: 14px; + 'Geist', ui-sans-serif, system-ui, -apple-system, 'Segoe UI Variable', 'Segoe UI', Roboto, + sans-serif; + --font-mono: 'Geist Mono', ui-monospace, 'SF Mono', 'Cascadia Mono', Menlo, Consolas, monospace; + + /* type scale, ratio ~1.15 for a dense tool; whole pixels */ --text-2xs: 0.6875rem; --text-2xs--line-height: 1rem; + --text-xs: 0.75rem; + --text-xs--line-height: 1rem; + --text-sm: 0.8125rem; + --text-sm--line-height: 1.25rem; + --text-base: 0.9375rem; + --text-base--line-height: 1.5rem; + --text-lg: 1.0625rem; + --text-lg--line-height: 1.5rem; + --text-xl: 1.25rem; + --text-xl--line-height: 1.75rem; + + /* radius: one scale. controls 8, cards 12, sheets 16, pills full */ + --radius-xs: 4px; + --radius-sm: 6px; + --radius-md: 8px; + --radius-lg: 12px; + --radius-xl: 16px; + --radius-2xl: 20px; + + --animate-enter: enter var(--dur) var(--ease-out) both; + --animate-ping-soft: ping-soft 1.8s var(--ease-out) infinite; + --animate-shimmer: shimmer 1.8s linear infinite; } @layer base { @@ -99,12 +177,26 @@ font-family: var(--font-sans); font-size: 14px; line-height: 1.5; + letter-spacing: -0.006em; + font-feature-settings: + 'cv11' 1, + 'ss01' 1; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: 100%; + -webkit-tap-highlight-color: transparent; + } + code, + kbd, + pre, + samp { + font-family: var(--font-mono); + letter-spacing: 0; + font-feature-settings: 'liga' 0; } :focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; + border-radius: 4px; } button, [role='button'], @@ -116,10 +208,10 @@ cursor: not-allowed; } ::selection { - background: color-mix(in oklab, var(--primary) 35%, transparent); + background: color-mix(in oklab, var(--primary) 32%, transparent); } @media (pointer: coarse) { - input, + input:not([type='checkbox']), textarea, select { font-size: 16px; @@ -141,15 +233,62 @@ .num { font-variant-numeric: tabular-nums; } + /* The micro-label: used sparingly, on panel headings. */ + .label { + font-size: 0.6875rem; + font-weight: 500; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--muted-foreground); + } + /* A lifted surface: hairline + faint top edge, no drop shadow unless it floats. */ + .surface { + background: var(--card); + border: 1px solid var(--border); + box-shadow: var(--edge); + } + .float { + background: var(--overlay); + border: 1px solid var(--border-strong); + box-shadow: var(--edge), var(--shadow-lg); + } + .pad-b { + padding-bottom: max(0.75rem, env(safe-area-inset-bottom)); + } + .pad-t { + padding-top: env(safe-area-inset-top); + } + /* Press feedback on touch and click; transform only. */ + .press { + transition: transform var(--dur-fast) var(--ease-out); + } + .press:active:not(:disabled) { + transform: scale(0.97); + } + /* Shimmer for "thinking" text. */ + .shimmer { + background: linear-gradient( + 100deg, + var(--muted-foreground) 35%, + var(--foreground) 50%, + var(--muted-foreground) 65% + ) + 0 0 / 220% 100%; + -webkit-background-clip: text; + background-clip: text; + color: transparent; + animation: shimmer 2s linear infinite; + } /* Rendered model markdown. Everything inside is sanitised first. */ .md { font-size: 0.9375rem; - line-height: 1.65; + line-height: 1.7; overflow-wrap: anywhere; + color: var(--foreground); } .md > * + * { - margin-top: 0.75em; + margin-top: 0.8em; } .md h1, .md h2, @@ -157,22 +296,22 @@ .md h4 { font-weight: 600; line-height: 1.3; - letter-spacing: -0.01em; - margin-top: 1.25em; + letter-spacing: -0.015em; + margin-top: 1.4em; } .md h1 { font-size: 1.25rem; } .md h2 { - font-size: 1.125rem; + font-size: 1.0625rem; } .md h3, .md h4 { - font-size: 1rem; + font-size: 0.9375rem; } .md ul, .md ol { - padding-left: 1.4em; + padding-left: 1.35em; } .md ul { list-style: disc; @@ -181,68 +320,87 @@ list-style: decimal; } .md li + li { - margin-top: 0.25em; + margin-top: 0.3em; } .md li::marker { - color: var(--muted-foreground); + color: var(--faint); + } + .md strong { + font-weight: 600; } .md a { color: var(--accent-text); text-decoration: underline; text-underline-offset: 3px; text-decoration-thickness: 1px; + text-decoration-color: color-mix(in oklab, var(--accent-text) 45%, transparent); + } + .md a:hover { + text-decoration-color: currentColor; } .md blockquote { - border-left: 2px solid var(--input); + border-left: 2px solid var(--border-strong); padding-left: 0.9em; color: var(--muted-foreground); } .md hr { border: 0; border-top: 1px solid var(--border); - margin: 1.25em 0; + margin: 1.4em 0; } .md code { - font-family: var(--font-mono); - font-size: 0.85em; + font-size: 0.84em; background: var(--raised); - border-radius: 4px; - padding: 0.12em 0.4em; + border: 1px solid var(--border); + border-radius: 5px; + padding: 0.1em 0.38em; } .md pre { - background: var(--card); + background: var(--inset); border: 1px solid var(--border); border-radius: var(--radius-lg); - padding: 0.75rem 0.9rem; + padding: 0.85rem 1rem; overflow-x: auto; font-size: 0.8125rem; - line-height: 1.55; + line-height: 1.6; scrollbar-width: thin; + box-shadow: inset 0 1px 0 light-dark(oklch(0 0 0 / 0.03), oklch(0 0 0 / 0.25)); } .md pre code { background: none; + border: 0; padding: 0; font-size: inherit; } .md table { display: block; overflow-x: auto; - border-collapse: collapse; + border-collapse: separate; + border-spacing: 0; font-size: 0.875rem; + border: 1px solid var(--border); + border-radius: var(--radius-md); + width: max-content; + max-width: 100%; } .md th, .md td { - border: 1px solid var(--border); - padding: 0.35rem 0.65rem; + border-bottom: 1px solid var(--border); + padding: 0.4rem 0.8rem; text-align: left; } + .md tr:last-child td { + border-bottom: 0; + } .md th { background: var(--raised); - font-weight: 600; + font-weight: 500; + color: var(--ink-2); + font-size: 0.8125rem; } .hljs-comment, .hljs-quote { - color: var(--muted-foreground); + color: var(--faint); font-style: italic; } .hljs-keyword, @@ -273,15 +431,11 @@ } } -@keyframes pulse-dot { - 50% { - opacity: 0.35; - } -} -@keyframes sheet-up { +/* Motion explains a change of state; it moves transform and opacity only. */ +@keyframes enter { from { - transform: translateY(28px); opacity: 0; + transform: translateY(6px); } } @keyframes fade-in { @@ -289,6 +443,22 @@ opacity: 0; } } +@keyframes ping-soft { + 0% { + transform: scale(1); + opacity: 0.55; + } + 80%, + 100% { + transform: scale(2.6); + opacity: 0; + } +} +@keyframes shimmer { + to { + background-position: -220% 0; + } +} @keyframes caret { 50% { opacity: 0; @@ -302,6 +472,14 @@ transform: scaleX(1); } } +@keyframes bar { + 0% { + transform: translateX(-100%); + } + 100% { + transform: translateX(260%); + } +} @media (prefers-reduced-motion: reduce) { *, @@ -312,4 +490,9 @@ transition-duration: 0.001ms !important; scroll-behavior: auto !important; } + .shimmer { + animation: none; + color: var(--muted-foreground); + background: none; + } } diff --git a/web/src/lib/components/AgentHub.svelte b/web/src/lib/components/AgentHub.svelte index 053c1e3b..c9ad49b9 100644 --- a/web/src/lib/components/AgentHub.svelte +++ b/web/src/lib/components/AgentHub.svelte @@ -4,6 +4,8 @@ import { cost, duration, tokens } from '$lib/format'; import { toasts } from '$lib/toasts.svelte'; import Square from '@lucide/svelte/icons/square'; + import Users from '@lucide/svelte/icons/users'; + import { onMount } from 'svelte'; let { session, @@ -12,6 +14,7 @@ }: { session: Session; canControl: boolean; active?: string | null } = $props(); const members = $derived(session.model.roster); + const subs = $derived(members.filter((m) => m.id !== 'lead').length); const live = $derived( members.filter( (m) => m.state === 'running' || m.state === 'queued' || m.state === 'waiting for approval' @@ -19,6 +22,16 @@ ); let confirming = $state(null); + // The roster reports elapsed time when it was sent. A running agent keeps counting from that + // moment, so the number moves between frames instead of freezing. + let now = $state(Date.now()); + onMount(() => { + const t = setInterval(() => (now = Date.now()), 1000); + return () => clearInterval(t); + }); + const elapsed = (m: (typeof members)[number]) => + m.state === 'running' ? m.elapsed_ms + Math.max(0, now - session.model.rosterAt) : m.elapsed_ms; + async function stop(id: string) { try { await session.agentStop(id); @@ -31,84 +44,89 @@ } const stoppable = (s: string) => s === 'running' || s === 'queued' || s === 'waiting for approval'; + const href = (id: string) => + id === 'lead' + ? `/s/${encodeURIComponent(session.id)}` + : `/s/${encodeURIComponent(session.id)}/agents/${encodeURIComponent(id)}`;
-
- {members.length - ? `${members.length} agent${members.length === 1 ? '' : 's'}` - : 'No agents yet'} - {#if live}{live} active{/if} -
- - {#if members.length <= 1} -

- When the lead hands work to sub-agents, they show up here with what each one is doing. You can - open one to read its work, message it or stop it. -

- {/if} - - + {/if}
diff --git a/web/src/lib/components/ApprovalSheet.svelte b/web/src/lib/components/ApprovalSheet.svelte index 24a54f17..aa4972b7 100644 --- a/web/src/lib/components/ApprovalSheet.svelte +++ b/web/src/lib/components/ApprovalSheet.svelte @@ -64,13 +64,15 @@
- {f.access} {#if f.destructive} {:else}
{prettyInput(
+				class="bg-inset scroll-thin max-h-40 overflow-auto rounded-md border p-2.5 font-mono text-xs leading-5 whitespace-pre-wrap break-words">{prettyInput(
 					f.input,
 					900
 				)}
@@ -110,7 +112,7 @@ diff --git a/web/src/lib/components/Brand.svelte b/web/src/lib/components/Brand.svelte index a4217c70..f17a072a 100644 --- a/web/src/lib/components/Brand.svelte +++ b/web/src/lib/components/Brand.svelte @@ -1,13 +1,29 @@ - - + + - azazel + /> + + + {#if word}azazel{/if} diff --git a/web/src/lib/components/Composer.svelte b/web/src/lib/components/Composer.svelte index ae2643c2..3081ba0a 100644 --- a/web/src/lib/components/Composer.svelte +++ b/web/src/lib/components/Composer.svelte @@ -123,19 +123,19 @@ ? followUp ? 'Queue something for when it is done…' : 'Steer the agent…' - : 'Message azazel…' + : 'Ask azazel to do something…' );
{ e.preventDefault(); void submit(); }} data-composer > -
+
{#if mention}
    session.abort().catch((e) => toasts.push(String(e.message ?? e), 'error'))} @@ -237,7 +237,7 @@ {/if} import { parseDiff } from '$lib/tools'; - let { diff, max = 18 }: { diff: string; max?: number } = $props(); + let { diff, max = 18, file }: { diff: string; max?: number; file?: string } = $props(); const lines = $derived(parseDiff(diff)); + const body = $derived(lines.filter((l) => l.kind !== 'meta')); let all = $state(false); - const shown = $derived(all ? lines : lines.slice(0, max)); + const shown = $derived(all ? body : body.slice(0, max)); const stats = $derived({ - add: lines.filter((l) => l.kind === 'add').length, - del: lines.filter((l) => l.kind === 'del').length + add: body.filter((l) => l.kind === 'add').length, + del: body.filter((l) => l.kind === 'del').length }); + const name = $derived( + file ?? lines.find((l) => l.text.startsWith('+++'))?.text.replace(/^\+\+\+ (b\/)?/, '') ?? '' + ); -
    +
    +
    + {name || 'diff'} + +{stats.add} + −{stats.del} +
    {#each shown as l, i (i)} - {#if l.kind === 'meta'} -
    {l.text}
    - {:else if l.kind === 'hunk'} -
    {l.text}
    + {#if l.kind === 'hunk'} +
    {l.text}
    {:else}
    -
    - +{stats.add} - −{stats.del} max} + - {/if} -
    -
    + {all ? 'Show less' : `Show all ${body.length} lines`} + + {/if} +
    diff --git a/web/src/lib/components/PairDevice.svelte b/web/src/lib/components/PairDevice.svelte index c9066ca2..ea4be7c2 100644 --- a/web/src/lib/components/PairDevice.svelte +++ b/web/src/lib/components/PairDevice.svelte @@ -71,7 +71,7 @@ {@html svg}
    - {link.url} + {link.url} diff --git a/web/src/lib/components/QuestionSheet.svelte b/web/src/lib/components/QuestionSheet.svelte index d1e67f26..1e54f59f 100644 --- a/web/src/lib/components/QuestionSheet.svelte +++ b/web/src/lib/components/QuestionSheet.svelte @@ -120,6 +120,7 @@ {#if isPlan}

    {f.path}

    -
    +
    {#if revising} @@ -174,7 +175,7 @@ {:else if q.code}
    {q.code}
    + class="bg-inset scroll-thin max-h-40 overflow-auto rounded-md border p-2.5 font-mono text-xs leading-5">{q.code} {/if} {#if q.expects === 'confirm'} @@ -240,7 +241,7 @@ >Or write your own answer{/if} void } = @@ -16,58 +17,69 @@ (a, b) => order(a.state) - order(b.state) || Date.parse(b.started) - Date.parse(a.started) ) ); + const home = (p: string) => + p.replace(/^\/home\/[^/]+/, '~').replace(/^[A-Za-z]:\\Users\\[^\\]+/, '~');