Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

452 linesCodeBlameRaw
1//! g1t taking on what it is asked in a work item or a pull request:
2//! assigned the work item (`work_item.assigned` adding `g1t`), or mentioned
3//! in a comment (`comment.created` whose text says `@g1t`).
4//!
5//! g1t reacts 👀 to what asked it (the comment, or the work item for an
6//! assignment) and starts a session on the workspace's own Claude, as the
7//! person who asked ([`Integrations::start_agent_session`]): a pull
8//! request's mention carries on with that pull request on its branch, and
9//! a work item's works on the work item, in the repository it was filed in
10//! (or its first target, or the first it touched). The comment is the
11//! session's instruction, so "that's not what I meant" reaches it, along
12//! with where to find what the sessions before it did. A mention on a thread where that same person's
13//! session is still going is passed to that session instead of starting
14//! another. The session shows in the thread's timeline as it goes.
15//!
16//! Only the workspace's members can ask; anyone else's mention is an
17//! ordinary one. When the session cannot start (no Anthropic key, say),
18//! g1t says why in the thread. Each ask is acted on once (`summons`), and
19//! a thread is answered at most [`MAX_PER_HOUR`] times an hour, so a
20//! session that writes `@g1t` itself cannot start sessions without end.
21
22use g1t_contracts::agent_sessions::{AgentMode, Asked, StartAgentSessionArgs};
23use g1t_contracts::events::Event;
24use g1t_contracts::identity::UserIdArgs;
25use g1t_contracts::repos::{PathByIdArgs, RepoPath};
26use g1t_contracts::time::rfc3339;
27use g1t_contracts::updates::update_command;
28use g1t_contracts::work::{Comment, CommentKind, PullDetail, ReactArgs, ReactionContent, ViewArgs, WorkItemDetail, WorkItemViewArgs};
29use g1t_contracts::{FailureCode, Outcome, User, Viewer, system};
30use g1t_kit::now_ms;
31use serde::Deserialize;
32use serde_json::Value;
33use worker::Result;
34
35use crate::Integrations;
36
37/// The most times g1t answers one thread in an hour.
38pub const MAX_PER_HOUR: u32 = 6;
39const HOUR_MS: u64 = 60 * 60 * 1000;
40
41/// A thread asked in.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub enum On {
44 /// Pull request `number` of the event's repository.
45 Pull { number: u32 },
46 /// Work item `number` of `workspace`.
47 Item { workspace: String, number: u32 },
48}
49
50impl On {
51 fn number(&self) -> u32 {
52 match self {
53 On::Pull { number } | On::Item { number, .. } => *number,
54 }
55 }
56}
57
58/// What g1t was asked, read from an event before anything is looked up.
59#[derive(Debug, PartialEq, Eq)]
60pub enum Ask {
61 /// Assigned the work item.
62 Assigned { on: On },
63 /// Comment `comment_id` on a work item or a pull request may mention it.
64 Commented { on: On, comment_id: String },
65}
66
67impl Ask {
68 fn on(&self) -> &On {
69 match self {
70 Ask::Assigned { on } | Ask::Commented { on, .. } => on,
71 }
72 }
73}
74
75/// What an event asks of g1t, if anything.
76pub fn ask_in(event: &Event) -> Option<Ask> {
77 let actor = event.actor.as_deref()?;
78 // g1t's own doings never ask it anything.
79 if system::is_system_id(actor) {
80 return None;
81 }
82 let number = event.data["number"].as_u64().and_then(|n| u32::try_from(n).ok())?;
83 let item = || event.data["workspace"].as_str().filter(|slug| !slug.is_empty()).map(|slug| On::Item { workspace: slug.to_lowercase(), number });
84 match event.kind.as_str() {
85 "work_item.assigned" => {
86 let added = event.data["added"].as_array()?;
87 added.iter().any(|name| name.as_str() == Some(system::USERNAME)).then_some(Ask::Assigned { on: item()? })
88 }
89 "comment.created" => {
90 // An agent writing as itself, from before agents were removed, never asks.
91 if !event.data["agent"].is_null() {
92 return None;
93 }
94 let comment_id = event.data["commentId"].as_str()?.to_owned();
95 let on = if event.data["itemId"].is_string() { item()? } else { On::Pull { number } };
96 Some(Ask::Commented { on, comment_id })
97 }
98 _ => None,
99 }
100}
101
102/// Whether `text` mentions `@g1t`: outside code and quotes, and not as part
103/// of a longer name (`@g1t-agent`) or a team (`@g1t/core`).
104pub fn mentions_g1t(text: &str) -> bool {
105 let text = text.to_ascii_lowercase();
106 let mut fenced = false;
107 for line in text.lines() {
108 let trimmed = line.trim_start();
109 if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
110 fenced = !fenced;
111 continue;
112 }
113 if fenced || trimmed.starts_with('>') || line.starts_with(" ") || line.starts_with('\t') {
114 continue;
115 }
116 // Inline code: every other run between backticks.
117 for (at, part) in trimmed.split('`').enumerate() {
118 if at % 2 == 1 {
119 continue;
120 }
121 let bytes = part.as_bytes();
122 let mut from = 0;
123 while let Some(found) = part[from..].find("@g1t") {
124 let start = from + found;
125 let end = start + 4;
126 let before = start.checked_sub(1).map(|i| bytes[i]);
127 let after = bytes.get(end).copied();
128 let word = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'/' | b'.' | b'@');
129 let ends = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'/');
130 if !before.is_some_and(word) && !after.is_some_and(ends) {
131 return true;
132 }
133 from = end;
134 }
135 }
136 }
137 false
138}
139
140#[derive(Deserialize)]
141struct Counted {
142 n: u32,
143}
144
145#[derive(Deserialize)]
146struct Running {
147 provider_session_id: String,
148 connection_id: String,
149}
150
151/// The thread asked in, as the asker sees it.
152struct Thread {
153 /// Its page on the site.
154 url: String,
155 /// `owner/name#number` for a pull request, `workspace#number` for a
156 /// work item: what asks are counted against.
157 key: String,
158 /// The repository a session on it works in: a pull request's, or a
159 /// work item's origin (else its first target, else the first it
160 /// touched). None for a work item linked to no repository.
161 repo: Option<RepoPath>,
162 comments: Vec<Comment>,
163 /// The work item's number, or the pull request's work item's, if any.
164 item: Option<u32>,
165 /// Set for a pull request: its number.
166 pull: Option<u32>,
167 /// A pull request g1t opened (an update), whose `@g1t` commands are
168 /// the security service's.
169 g1t_pull: bool,
170 open: bool,
171}
172
173impl Integrations {
174 /// Acts on what an event asks of g1t. Never fails the batch: a problem
175 /// is logged, and the ask is not tried again.
176 pub(crate) async fn summon(&self, event: &Event) {
177 let Some(ask) = ask_in(event) else { return };
178 if let Err(error) = self.answer_ask(event, ask).await {
179 worker::console_error!("summon: {} {}: {error}", event.kind, event.id);
180 }
181 }
182
183 async fn answer_ask(&self, event: &Event, ask: Ask) -> Result<()> {
184 let Some(actor_id) = event.actor.as_deref() else { return Ok(()) };
185 // A pull request's repository, which names its workspace.
186 let pull_repo = match ask.on() {
187 On::Pull { .. } => {
188 let Some(repo_id) = event.repo_id.as_deref() else { return Ok(()) };
189 let found: Option<RepoPath> = g1t_kit::call(&self.repos, "path_by_id", &PathByIdArgs { id: repo_id.to_owned() }).await?;
190 let Some(repo) = found else { return Ok(()) };
191 Some(repo)
192 }
193 On::Item { .. } => None,
194 };
195 let workspace = match (ask.on(), &pull_repo) {
196 (On::Item { workspace, .. }, _) => workspace.clone(),
197 (_, Some(repo)) => repo.namespace.to_lowercase(),
198 _ => return Ok(()),
199 };
200 // Who asked, as they are now: only the workspace's members may.
201 let actor: Viewer = g1t_kit::call(&self.identity, "user_by_id", &UserIdArgs { id: actor_id.to_owned() }).await?;
202 let Some(actor) = actor.filter(|actor| actor.verified && actor.is_member(&workspace)) else { return Ok(()) };
203 let number = ask.on().number();
204 let Some(thread) = self.thread(&actor, ask.on(), pull_repo).await? else { return Ok(()) };
205 let site = self.site_url.trim_end_matches('/');
206 let (comment, url) = match &ask {
207 Ask::Assigned { .. } => (None, thread.url.clone()),
208 Ask::Commented { comment_id, .. } => {
209 let Some(comment) = thread.comments.iter().find(|comment| &comment.id == comment_id && comment.kind == CommentKind::Comment) else {
210 return Ok(());
211 };
212 if !mentions_g1t(&comment.body) {
213 return Ok(());
214 }
215 // `@g1t rebase` on an update g1t opened is the security service's.
216 if thread.g1t_pull && update_command(&comment.body).is_some() {
217 return Ok(());
218 }
219 (Some(comment), format!("{}#{}", thread.url, comment.id))
220 }
221 };
222 if !thread.open {
223 return Ok(());
224 }
225 // Once per ask, and a few times an hour per thread.
226 if !self.first_time(&event.id, &thread.key).await? {
227 return Ok(());
228 }
229 let react_to = comment.map(|comment| comment.id.clone());
230 let system = User::system(&workspace);
231 // A pull request is named in its repository; a work item, in its workspace.
232 let in_repo = thread.pull.and(thread.repo.clone());
233 let _: Outcome<Value> = g1t_kit::call(
234 &self.work,
235 "react",
236 &ReactArgs {
237 actor: system.clone(),
238 repo: in_repo.clone(),
239 workspace: workspace.clone(),
240 number,
241 comment_id: react_to,
242 content: ReactionContent::Eyes,
243 remove: false,
244 },
245 )
246 .await?;
247 let text = comment.map(|comment| comment.body.clone());
248 // The asker's session on this thread, still going: told, not doubled.
249 let numbers: Vec<u32> = [thread.pull, thread.item].into_iter().flatten().collect();
250 if let Some(text) = &text
251 && self.tell_running(&workspace, in_repo.as_ref(), &actor, &numbers, text, &url).await?
252 {
253 return Ok(());
254 }
255 let Some(repo) = thread.repo.clone() else {
256 let body = format!(
257 "@{}, I can't take this on: the work item is linked to no repository. Link the repository the work is in, then ask again.",
258 actor.username
259 );
260 return self.comment(&system, &workspace, None, number, body).await;
261 };
262 let started = self
263 .start_agent_session(StartAgentSessionArgs {
264 actor: actor.clone(),
265 repo,
266 item: thread.item.filter(|_| thread.pull.is_none()),
267 pull: thread.pull,
268 asked: Some(Asked { by: actor.username.clone(), comment: text, url }),
269 title: None,
270 body: None,
271 instruction: None,
272 mode: Some(AgentMode::Implement),
273 handoff: Some(false),
274 })
275 .await?;
276 if let Outcome::Fail(failure) = started {
277 let mut body = format!("@{}, I can't take this on: {}.", actor.username, failure.message.trim().trim_end_matches('.'));
278 // No Anthropic account to start on: where to add one.
279 if failure.code == FailureCode::Conflict {
280 body.push_str(&format!(" Add an Anthropic key in [the workspace's AI settings]({site}/{workspace}/-/ai), then ask again."));
281 }
282 self.comment(&system, &workspace, in_repo.as_ref(), number, body).await?;
283 }
284 Ok(())
285 }
286
287 /// The thread asked in, as `actor` may see it: a pull request of
288 /// `pull_repo`, or a work item.
289 async fn thread(&self, actor: &User, on: &On, pull_repo: Option<RepoPath>) -> Result<Option<Thread>> {
290 let site = self.site_url.trim_end_matches('/');
291 match (on, pull_repo) {
292 (On::Item { workspace, number }, _) => {
293 let view = WorkItemViewArgs { workspace: workspace.clone(), number: *number, viewer: Some(actor.clone()) };
294 let found: Outcome<WorkItemDetail> = g1t_kit::call(&self.work, "get_work_item", &view).await?;
295 let Outcome::Ok(detail) = found else { return Ok(None) };
296 // Origin first, then targets, then those it touched.
297 let repo = detail.item.repos.iter().find_map(|link| {
298 let (namespace, name) = link.path.split_once('/')?;
299 Some(RepoPath { namespace: namespace.to_lowercase(), name: name.to_owned() })
300 });
301 Ok(Some(Thread {
302 url: format!("{site}/{workspace}/-/work/{number}"),
303 key: format!("{workspace}#{number}"),
304 repo,
305 open: detail.item.state == g1t_contracts::work::State::Open,
306 comments: detail.comments,
307 item: Some(*number),
308 pull: None,
309 g1t_pull: false,
310 }))
311 }
312 (On::Pull { number }, Some(repo)) => {
313 let view = ViewArgs { repo: repo.clone(), number: *number, viewer: Some(actor.clone()), after_seq: 0 };
314 let found: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view).await?;
315 let Outcome::Ok(detail) = found else { return Ok(None) };
316 let path = format!("{}/{}", repo.namespace.to_lowercase(), repo.name);
317 Ok(Some(Thread {
318 url: format!("{site}/{path}/pull/{number}"),
319 key: format!("{path}#{number}"),
320 open: detail.pull.status.is_active(),
321 g1t_pull: detail.pull.author.is_system() || system::is_system_id(&detail.pull.author.id),
322 item: detail.pull.item,
323 pull: Some(*number),
324 comments: detail.comments,
325 repo: Some(repo),
326 }))
327 }
328 (On::Pull { .. }, None) => Ok(None),
329 }
330 }
331
332 /// Records ask `event_id` on `thread` (a [`Thread`]'s key): whether it
333 /// is new and the thread has not been answered [`MAX_PER_HOUR`] times
334 /// this hour.
335 async fn first_time(&self, event_id: &str, thread: &str) -> Result<bool> {
336 let now = now_ms();
337 let recent = self
338 .db
339 .prepare("SELECT COUNT(*) AS n FROM summons WHERE thread = ? AND at > ?")
340 .bind(&[thread.into(), rfc3339(now.saturating_sub(HOUR_MS)).into()])?
341 .first::<Counted>(None)
342 .await?
343 .map_or(0, |row| row.n);
344 if recent >= MAX_PER_HOUR {
345 worker::console_log!("summon: {thread} asked {recent} times this hour; {event_id} let be");
346 return Ok(false);
347 }
348 let inserted = self
349 .db
350 .prepare("INSERT INTO summons (event_id, thread, at) VALUES (?, ?, ?) ON CONFLICT DO NOTHING RETURNING event_id")
351 .bind(&[event_id.into(), thread.into(), rfc3339(now).into()])?
352 .first::<Value>(None)
353 .await?;
354 Ok(inserted.is_some())
355 }
356
357 /// Passes `text` to `actor`'s own session on `numbers` in `workspace`
358 /// (in `repo`, for a pull request's) that g1t started and is still
359 /// going. Whether there was one.
360 async fn tell_running(&self, workspace: &str, repo: Option<&RepoPath>, actor: &User, numbers: &[u32], text: &str, url: &str) -> Result<bool> {
361 let repo_name = repo.map(|repo| format!("{}/{}", repo.namespace.to_lowercase(), repo.name));
362 let running = self
363 .db
364 .prepare(
365 "SELECT provider_session_id, connection_id FROM agent_runs
366 WHERE workspace = ?1 AND (?2 IS NULL OR repo = ?2) AND status = 'running' AND json_extract(actor, '$.id') = ?3
367 AND item IN (SELECT value FROM json_each(?4))
368 ORDER BY created_at DESC LIMIT 1",
369 )
370 .bind(&[workspace.into(), crate::optional(repo_name.as_deref()), actor.id.as_str().into(), serde_json::to_string(numbers)?.into()])?
371 .first::<Running>(None)
372 .await?;
373 let Some(running) = running else { return Ok(false) };
374 let Some(row) = self.ai_row(&running.connection_id).await? else { return Ok(false) };
375 let key = self.ai_secret(&row).unwrap_or_default();
376 let message = format!(
377 "@{} said, in a comment on g1t ({url}):\n\n<comment>\n{}\n</comment>\n\nTake it into account; your report answers them, on this session's card in that thread.",
378 actor.username,
379 text.trim()
380 );
381 let sent = self
382 .call_anthropic(&key, worker::Method::Post, &format!("/v1/sessions/{}/events", running.provider_session_id), Some(crate::agent_sessions::message_event(&message)))
383 .await?;
384 Ok(sent.is_ok())
385 }
386}
387
388/// The cron: asks older than a week are forgotten.
389pub async fn forget_old(service: &Integrations) {
390 let before = rfc3339(now_ms().saturating_sub(7 * 24 * HOUR_MS));
391 let forgot = async { service.db.prepare("DELETE FROM summons WHERE at < ?").bind(&[before.into()])?.run().await };
392 if let Err(error) = forgot.await {
393 worker::console_error!("summon: old asks not cleared: {error}");
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400 use serde_json::json;
401
402 fn event(kind: &str, actor: &str, data: Value) -> Event {
403 Event {
404 id: "evt_1".into(),
405 kind: kind.into(),
406 source: "work".into(),
407 time: String::new(),
408 repo_id: Some("rep_1".into()),
409 actor: Some(actor.into()),
410 data,
411 }
412 }
413
414 #[test]
415 fn a_mention_is_an_at_g1t_outside_code_and_quotes() {
416 assert!(mentions_g1t("@g1t try again, the test is still red"));
417 assert!(mentions_g1t("Thanks. @g1t: use the other API."));
418 assert!(mentions_g1t("(@g1t) please"));
419 assert!(mentions_g1t("Hey @G1T"));
420 assert!(!mentions_g1t("@g1t-agent was retired"), "a longer name");
421 assert!(!mentions_g1t("ask @g1t/core"), "a team");
422 assert!(!mentions_g1t("mail g1t@users.noreply.g1t.sh"));
423 assert!(!mentions_g1t("run `@g1t rebase` on updates"), "inline code");
424 assert!(!mentions_g1t("```\n@g1t\n```"), "a code block");
425 assert!(!mentions_g1t("> @g1t do it\n\nI disagree."), "a quote");
426 assert!(mentions_g1t("```\nlog\n```\n@g1t look at the log above"));
427 }
428
429 #[test]
430 fn assigning_g1t_and_commenting_ask_and_nothing_g1t_does_does() {
431 let item = On::Item { workspace: "acme".into(), number: 4 };
432 assert_eq!(
433 ask_in(&event("work_item.assigned", "usr_ana", json!({ "itemId": "wki_1", "workspace": "acme", "number": 4, "added": ["g1t"] }))),
434 Some(Ask::Assigned { on: item.clone() })
435 );
436 assert_eq!(ask_in(&event("work_item.assigned", "usr_ana", json!({ "workspace": "acme", "number": 4, "added": ["bo"] }))), None);
437 assert_eq!(
438 ask_in(&event("comment.created", "usr_ana", json!({ "number": 4, "commentId": "cmt_1", "pullId": "pr_1" }))),
439 Some(Ask::Commented { on: On::Pull { number: 4 }, comment_id: "cmt_1".into() })
440 );
441 assert_eq!(
442 ask_in(&event("comment.created", "usr_ana", json!({ "number": 4, "commentId": "cmt_1", "itemId": "wki_1", "workspace": "Acme" }))),
443 Some(Ask::Commented { on: item, comment_id: "cmt_1".into() })
444 );
445 assert_eq!(ask_in(&event("comment.created", "g1t", json!({ "number": 4, "commentId": "cmt_1" }))), None);
446 assert_eq!(
447 ask_in(&event("comment.created", "usr_ana", json!({ "number": 4, "commentId": "cmt_1", "agent": { "id": "agt_1" } }))),
448 None
449 );
450 assert_eq!(ask_in(&event("work_item.closed", "usr_ana", json!({ "workspace": "acme", "number": 4 }))), None);
451 }
452}