g1t/crates/contracts/src/agents.rs
Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 1 | //! Agents at work and what they remember. Kept by the work service. |
| 2 | //! | |
| 3 | //! Every sandbox g1t starts for an agent is an [`AgentRun`]: what it is | |
| 4 | //! doing, on which pull request or issue, step by step, what it cost, and | |
| 5 | //! how it ended. People watch runs live, stop them and message them. | |
| 6 | //! | |
| 7 | //! Memory is what agents and people have learned that the next agent | |
| 8 | //! should know: about one project (its codebase), or about the whole | |
| 9 | //! workspace (true across its projects). It is members-only, is given to | |
| 10 | //! every g1t agent run, and never holds a secret. | |
| 11 | //! | |
| 12 | //! Each `*Args` struct is the argument of the method of the same name, | |
| 13 | //! served at `POST /rpc/<method>`. | |
| 14 | ||
| 15 | use serde::{Deserialize, Serialize}; | |
| 16 | ||
| 17 | use crate::repos::RepoPath; | |
| 18 | use crate::work::{Pull, PullStatus, SessionEntry}; | |
| 19 | use crate::{User, Viewer}; | |
| 20 | ||
| 21 | /// The work an agent run does. | |
| 22 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] | |
| 23 | #[serde(rename_all = "snake_case")] | |
| 24 | pub enum RunKind { | |
| 25 | /// Making the change an issue asks for. | |
| 26 | Implement, | |
| 27 | /// Addressing failed checks or a review on its own pull request. | |
| 28 | Revise, | |
| 29 | /// Reviewing someone's pull request. | |
| 30 | Review, | |
| 31 | /// Answering another agent's question or handoff. | |
| 32 | Answer, | |
| 33 | /// Merging in the branch a pull request will land on. | |
| 34 | Update, | |
| 35 | /// Turning an outcome into a plan of issues. | |
| 36 | Plan, | |
| 37 | /// Running an issue's acceptance checks. Not an agent: a sandbox. | |
| 38 | Checks, | |
| 39 | /// Building and checking a state of the merge queue. Not an agent. | |
| 40 | Queue, | |
| 41 | /// Finding out whether a pull request merges cleanly. Not an agent. | |
| 42 | Mergecheck, | |
| 43 | } | |
| 44 | ||
| 45 | impl RunKind { | |
| 46 | pub const ALL: [RunKind; 9] = [ | |
| 47 | RunKind::Implement, | |
| 48 | RunKind::Revise, | |
| 49 | RunKind::Review, | |
| 50 | RunKind::Answer, | |
| 51 | RunKind::Update, | |
| 52 | RunKind::Plan, | |
| 53 | RunKind::Checks, | |
| 54 | RunKind::Queue, | |
| 55 | RunKind::Mergecheck, | |
| 56 | ]; | |
| 57 | ||
| 58 | pub fn as_str(self) -> &'static str { | |
| 59 | match self { | |
| 60 | RunKind::Implement => "implement", | |
| 61 | RunKind::Revise => "revise", | |
| 62 | RunKind::Review => "review", | |
| 63 | RunKind::Answer => "answer", | |
| 64 | RunKind::Update => "update", | |
| 65 | RunKind::Plan => "plan", | |
| 66 | RunKind::Checks => "checks", | |
| 67 | RunKind::Queue => "queue", | |
| 68 | RunKind::Mergecheck => "mergecheck", | |
| 69 | } | |
| 70 | } | |
| 71 | ||
| 72 | pub fn parse(value: &str) -> Option<RunKind> { | |
| 73 | RunKind::ALL.into_iter().find(|kind| kind.as_str() == value) | |
| 74 | } | |
| 75 | ||
| 76 | /// Whether a model does the work, rather than commands g1t runs. | |
| 77 | pub fn is_agent(self) -> bool { | |
| 78 | !matches!(self, RunKind::Checks | RunKind::Queue | RunKind::Mergecheck) | |
| 79 | } | |
| 80 | ||
| 81 | /// Whether a message reaches the agent while it runs: the harness asks | |
| 82 | /// for messages after each tool call in these. Others read nothing new | |
| 83 | /// until the next run on the same pull request. | |
| 84 | pub fn takes_messages(self) -> bool { | |
| 85 | matches!(self, RunKind::Implement | RunKind::Revise | RunKind::Answer) | |
| 86 | } | |
| 87 | } | |
| 88 | ||
| 89 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] | |
| 90 | #[serde(rename_all = "snake_case")] | |
| 91 | pub enum RunStatus { | |
| 92 | /// Its sandbox is starting. | |
| 93 | Queued, | |
| 94 | Running, | |
| 95 | Succeeded, | |
| 96 | Failed, | |
| 97 | /// A person stopped it. | |
| 98 | Stopped, | |
| 99 | } | |
| 100 | ||
| 101 | impl RunStatus { | |
| 102 | pub fn as_str(self) -> &'static str { | |
| 103 | match self { | |
| 104 | RunStatus::Queued => "queued", | |
| 105 | RunStatus::Running => "running", | |
| 106 | RunStatus::Succeeded => "succeeded", | |
| 107 | RunStatus::Failed => "failed", | |
| 108 | RunStatus::Stopped => "stopped", | |
| 109 | } | |
| 110 | } | |
| 111 | ||
| 112 | pub fn parse(value: &str) -> Option<RunStatus> { | |
| 113 | [ | |
| 114 | RunStatus::Queued, | |
| 115 | RunStatus::Running, | |
| 116 | RunStatus::Succeeded, | |
| 117 | RunStatus::Failed, | |
| 118 | RunStatus::Stopped, | |
| 119 | ] | |
| 120 | .into_iter() | |
| 121 | .find(|status| status.as_str() == value) | |
| 122 | } | |
| 123 | ||
| 124 | pub fn is_active(self) -> bool { | |
| 125 | matches!(self, RunStatus::Queued | RunStatus::Running) | |
| 126 | } | |
| 127 | } | |
| 128 | ||
| 129 | /// One step of a run, as one short line. | |
| 130 | #[derive(Clone, Debug, Serialize, Deserialize)] | |
| 131 | pub struct RunStep { | |
| 132 | /// RFC 3339. | |
| 133 | pub at: String, | |
| 134 | pub text: String, | |
| 135 | } | |
| 136 | ||
| 137 | /// One sandbox g1t started: an agent at work, or a run of checks. | |
| 138 | #[derive(Clone, Debug, Serialize, Deserialize)] | |
| 139 | #[serde(rename_all = "camelCase")] | |
| 140 | pub struct AgentRun { | |
| 141 | pub id: String, | |
| 142 | pub repo: RepoPath, | |
| 143 | /// The pull request it works on; for a plan, none. | |
| 144 | pub number: Option<u32>, | |
| 145 | /// That pull request's title, or the plan's brief. | |
| 146 | pub title: Option<String>, | |
| 147 | pub kind: RunKind, | |
| 148 | /// Who is working: `g1t-agent` for g1t's own agent, `g1t` for a sandbox | |
| 149 | /// that runs commands. | |
| 150 | pub agent: String, | |
| 151 | /// The model, by its public name. Members only. | |
| 152 | pub model: Option<String>, | |
| 153 | pub status: RunStatus, | |
| 154 | /// What it is doing now, in one line. | |
| 155 | pub step: Option<String>, | |
| 156 | /// Every step so far, oldest first. Empty in lists. | |
| 157 | #[serde(default)] | |
| 158 | pub steps: Vec<RunStep>, | |
| 159 | /// How many steps there are. | |
| 160 | #[serde(default)] | |
| 161 | pub step_count: u32, | |
| 162 | /// Who put it to work, when a person did. | |
| 163 | pub started_by: Option<String>, | |
| 164 | /// Why it failed. | |
| 165 | pub error: Option<String>, | |
| 166 | /// What it cost, in US dollars, as the harness reported it. Members only. | |
| 167 | pub cost_usd: Option<f64>, | |
| 168 | pub turns: Option<u32>, | |
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 169 | /// The most it may cost, in US dollars, from its guardrails. None: no |
| 170 | /// cap. Members only. | |
| 171 | #[serde(default)] | |
| 172 | pub budget_usd: Option<f64>, | |
| 173 | /// The longest it may take, in minutes, from its guardrails. | |
| 174 | #[serde(default)] | |
| 175 | pub time_cap_minutes: Option<u32>, | |
| 176 | /// `budget` or `time` when g1t stopped it for reaching a cap. | |
| 177 | #[serde(default)] | |
| 178 | pub halted: Option<String>, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 179 | /// RFC 3339. |
| 180 | pub created_at: String, | |
| 181 | pub started_at: Option<String>, | |
| 182 | pub finished_at: Option<String>, | |
| 183 | pub updated_at: String, | |
| 184 | } | |
| 185 | ||
| 186 | /// What lets a sandbox, and nothing else, report on its run. | |
| 187 | #[derive(Clone, Debug, Serialize, Deserialize)] | |
| 188 | #[serde(rename_all = "camelCase")] | |
| 189 | pub struct AgentRunTicket { | |
| 190 | pub run_id: String, | |
| 191 | pub token: String, | |
| 192 | } | |
| 193 | ||
| 194 | /// `open_run`: records a sandbox the runner is starting. Called by the | |
| 195 | /// runner service only. Returns `Outcome<AgentRunTicket>`. | |
| 196 | #[derive(Debug, Serialize, Deserialize)] | |
| 197 | #[serde(rename_all = "camelCase")] | |
| 198 | pub struct OpenRunArgs { | |
| 199 | /// Who the sandbox acts as. | |
| 200 | pub actor: User, | |
| 201 | pub repo: RepoPath, | |
| 202 | #[serde(default)] | |
| 203 | pub number: Option<u32>, | |
| 204 | #[serde(default)] | |
| 205 | pub pull_id: Option<String>, | |
| 206 | /// For a run with no pull request, such as a plan: what it is about. | |
| 207 | #[serde(default)] | |
| 208 | pub title: Option<String>, | |
| 209 | pub kind: RunKind, | |
| 210 | #[serde(default)] | |
| 211 | pub agent: Option<String>, | |
| 212 | #[serde(default)] | |
| 213 | pub model: Option<String>, | |
| 214 | /// The sandbox's name, which stopping it needs. | |
| 215 | pub sandbox: String, | |
| 216 | #[serde(default)] | |
| 217 | pub started_by: Option<String>, | |
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 218 | /// Its cost cap, from its guardrails, in US dollars. |
| 219 | #[serde(default)] | |
| 220 | pub budget_usd: Option<f64>, | |
| 221 | /// Its time cap, from its guardrails, in minutes. | |
| 222 | #[serde(default)] | |
| 223 | pub time_cap_minutes: Option<u32>, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 224 | } |
| 225 | ||
| 226 | /// `report_run`: a sandbox telling how its run goes, with the run's token. | |
| 227 | /// Steps are added, the current step replaced, and an outcome ends the run. | |
| 228 | /// A finished run accepts nothing more. Returns `Outcome<RunStatus>`: the | |
| 229 | /// run's status after the report, so a sandbox can tell it was stopped. | |
| 230 | #[derive(Debug, Default, Serialize, Deserialize)] | |
| 231 | #[serde(rename_all = "camelCase", default)] | |
| 232 | pub struct ReportRunArgs { | |
| 233 | pub run_id: String, | |
| 234 | pub token: String, | |
| 235 | pub steps: Vec<String>, | |
| 236 | pub step: Option<String>, | |
| 237 | pub cost_usd: Option<f64>, | |
| 238 | pub turns: Option<u32>, | |
| 239 | /// `succeeded` or `failed`, to end the run. | |
| 240 | pub outcome: Option<RunStatus>, | |
| 241 | pub error: Option<String>, | |
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 242 | /// `budget` or `time`: the run reached a cap of its guardrails and |
| 243 | /// stopped. Ends it as stopped, like a person's stop. | |
| 244 | pub halt: Option<crate::guardrails::Halt>, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 245 | } |
| 246 | ||
| 247 | /// `stop_run`: a member stops a run. Marks it stopped and returns where its | |
| 248 | /// sandbox is, for the runner to destroy. A pull request it worked on waits | |
| 249 | /// for a person. Returns `Outcome<StoppedRun>`. | |
| 250 | #[derive(Debug, Serialize, Deserialize)] | |
| 251 | pub struct StopRunArgs { | |
| 252 | pub actor: User, | |
| 253 | pub repo: RepoPath, | |
| 254 | pub id: String, | |
| 255 | } | |
| 256 | ||
| 257 | #[derive(Debug, Serialize, Deserialize)] | |
| 258 | #[serde(rename_all = "camelCase")] | |
| 259 | pub struct StoppedRun { | |
| 260 | pub run: AgentRun, | |
| 261 | pub sandbox: String, | |
| 262 | } | |
| 263 | ||
| 264 | /// `list_runs`: runs in a repository, or with `workspace` instead, in every | |
| 265 | /// repository of a workspace (members only), newest first. Returns | |
| 266 | /// `Outcome<Vec<AgentRun>>`. | |
| 267 | #[derive(Debug, Default, Serialize, Deserialize)] | |
| 268 | #[serde(rename_all = "camelCase", default)] | |
| 269 | pub struct ListRunsArgs { | |
| 270 | pub viewer: Viewer, | |
| 271 | pub repo: Option<RepoPath>, | |
| 272 | pub workspace: Option<String>, | |
| 273 | /// Only those queued or running. | |
| 274 | pub active: bool, | |
| 275 | pub kind: Option<RunKind>, | |
| 276 | pub status: Option<RunStatus>, | |
| 277 | /// Only those on this pull request. | |
| 278 | pub number: Option<u32>, | |
| 279 | /// At most 200; 50 if not given. | |
| 280 | pub limit: Option<u32>, | |
| 281 | } | |
| 282 | ||
| 283 | /// `get_run`: one run with all its steps. Returns `Outcome<AgentRun>`. | |
| 284 | #[derive(Debug, Serialize, Deserialize)] | |
| 285 | pub struct GetRunArgs { | |
| 286 | pub viewer: Viewer, | |
| 287 | pub repo: RepoPath, | |
| 288 | pub id: String, | |
| 289 | } | |
| 290 | ||
| 291 | /// A pull request's recorded session, summed up for a list. | |
| 292 | #[derive(Clone, Debug, Serialize, Deserialize)] | |
| 293 | #[serde(rename_all = "camelCase")] | |
| 294 | pub struct SessionSummary { | |
| 295 | pub number: u32, | |
| 296 | pub title: String, | |
| 297 | pub status: PullStatus, | |
| 298 | /// The agent label on the pull request, such as `g1t-agent`. | |
| 299 | pub agent: String, | |
| 300 | pub entries: u32, | |
| 301 | /// How many tools it called. | |
| 302 | pub tools: u32, | |
| 303 | /// The start of the first prompt. | |
| 304 | pub prompt: Option<String>, | |
| 305 | /// The kinds of the runs g1t made for it. | |
| 306 | pub kinds: Vec<RunKind>, | |
| 307 | pub runs: u32, | |
| 308 | /// What its runs cost together. Members only. | |
| 309 | pub cost_usd: Option<f64>, | |
| 310 | /// Whether one of its runs is under way. | |
| 311 | pub active: bool, | |
| 312 | /// RFC 3339. | |
| 313 | pub started_at: String, | |
| 314 | pub last_at: String, | |
| 315 | } | |
| 316 | ||
| 317 | /// `list_sessions`: the pull requests of a repository that have a session, | |
| 318 | /// most recently active first. Returns `Outcome<Vec<SessionSummary>>`. | |
| 319 | #[derive(Debug, Default, Serialize, Deserialize)] | |
| 320 | #[serde(rename_all = "camelCase", default)] | |
| 321 | pub struct ListSessionsArgs { | |
| 322 | pub viewer: Viewer, | |
| 323 | pub repo: Option<RepoPath>, | |
| 324 | /// Only those with a run of this kind. | |
| 325 | pub kind: Option<RunKind>, | |
| 326 | /// The pull request's status: `draft`, `open`, `merged` or `closed`. | |
| 327 | pub outcome: Option<PullStatus>, | |
| 328 | pub number: Option<u32>, | |
| 329 | } | |
| 330 | ||
| 331 | /// `get_session`: one pull request's session in full, with its runs. | |
| 332 | /// Returns `Outcome<SessionView>`. | |
| 333 | #[derive(Debug, Serialize, Deserialize)] | |
| 334 | pub struct GetSessionArgs { | |
| 335 | pub viewer: Viewer, | |
| 336 | pub repo: RepoPath, | |
| 337 | pub number: u32, | |
| 338 | } | |
| 339 | ||
| 340 | #[derive(Clone, Debug, Serialize, Deserialize)] | |
| 341 | #[serde(rename_all = "camelCase")] | |
| 342 | pub struct SessionView { | |
| 343 | pub pull: Pull, | |
| 344 | /// Oldest first; the first 2000. | |
| 345 | pub entries: Vec<SessionEntry>, | |
| 346 | /// Newest first, with their steps. | |
| 347 | pub runs: Vec<AgentRun>, | |
| 348 | /// Members only. | |
| 349 | pub cost_usd: Option<f64>, | |
| 350 | } | |
| 351 | ||
| 352 | // --- Memory ----------------------------------------------------------------- | |
| 353 | ||
| 354 | /// Whose memory: one project's, or the whole workspace's. | |
| 355 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] | |
| 356 | #[serde(rename_all = "snake_case")] | |
| 357 | pub enum MemoryScope { | |
| 358 | /// About one project's codebase. | |
| 359 | Project, | |
| 360 | /// True across the workspace's projects. | |
| 361 | Workspace, | |
| 362 | } | |
| 363 | ||
| 364 | impl MemoryScope { | |
| 365 | pub fn as_str(self) -> &'static str { | |
| 366 | match self { | |
| 367 | MemoryScope::Project => "project", | |
| 368 | MemoryScope::Workspace => "workspace", | |
| 369 | } | |
| 370 | } | |
| 371 | } | |
| 372 | ||
| 373 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] | |
| 374 | #[serde(rename_all = "snake_case")] | |
| 375 | pub enum MemoryKind { | |
| 376 | /// How something is: "staging lives at staging.example.com". | |
| 377 | #[default] | |
| 378 | Fact, | |
| 379 | /// How things are done here: "we use pnpm everywhere". | |
| 380 | Convention, | |
| 381 | /// Something chosen, and why: "we keep Postgres, not MySQL, for jsonb". | |
| 382 | Decision, | |
| 383 | /// A trap: "the tests need TZ=UTC or the date tests fail". | |
| 384 | Gotcha, | |
| 385 | } | |
| 386 | ||
| 387 | impl MemoryKind { | |
| 388 | pub fn as_str(self) -> &'static str { | |
| 389 | match self { | |
| 390 | MemoryKind::Fact => "fact", | |
| 391 | MemoryKind::Convention => "convention", | |
| 392 | MemoryKind::Decision => "decision", | |
| 393 | MemoryKind::Gotcha => "gotcha", | |
| 394 | } | |
| 395 | } | |
| 396 | ||
| 397 | pub fn parse(value: &str) -> Option<MemoryKind> { | |
| 398 | [ | |
| 399 | MemoryKind::Fact, | |
| 400 | MemoryKind::Convention, | |
| 401 | MemoryKind::Decision, | |
| 402 | MemoryKind::Gotcha, | |
| 403 | ] | |
| 404 | .into_iter() | |
| 405 | .find(|kind| kind.as_str() == value) | |
| 406 | } | |
| 407 | } | |
| 408 | ||
| 409 | /// Where a memory came from. | |
| 410 | #[derive(Clone, Debug, Default, Serialize, Deserialize)] | |
| 411 | #[serde(rename_all = "camelCase")] | |
| 412 | pub struct MemorySource { | |
| 413 | /// `person`, `agent` or `run`. | |
| 414 | pub kind: String, | |
| 415 | /// The agent run that learned it. | |
| 416 | #[serde(default)] | |
| 417 | pub run_id: Option<String>, | |
| 418 | /// The project and pull request it was learned on. | |
| 419 | #[serde(default)] | |
| 420 | pub repo: Option<RepoPath>, | |
| 421 | #[serde(default)] | |
| 422 | pub number: Option<u32>, | |
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 423 | /// What it was captured from: `run:<id>`, `comment:<id>`, |
| 424 | /// `pull:<repo id>#<n>`, `doc:<repo id>:<path>`. See `crate::capture`. | |
| 425 | #[serde(default)] | |
| 426 | pub reference: Option<String>, | |
| 427 | /// What it was learned from, quoted. | |
| 428 | #[serde(default)] | |
| 429 | pub evidence: Option<String>, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 430 | } |
| 431 | ||
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 432 | /// Whether agents are given a memory: `kept` ones are; a `candidate` waits |
| 433 | /// for review (see `crate::capture`); a `dismissed` one is never suggested | |
| 434 | /// again from the same wording. | |
| 435 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] | |
| 436 | #[serde(rename_all = "snake_case")] | |
| 437 | pub enum MemoryStatus { | |
| 438 | Candidate, | |
| 439 | #[default] | |
| 440 | Kept, | |
| 441 | Dismissed, | |
| 442 | } | |
| 443 | ||
| 444 | impl MemoryStatus { | |
| 445 | pub fn as_str(self) -> &'static str { | |
| 446 | match self { | |
| 447 | MemoryStatus::Candidate => "candidate", | |
| 448 | MemoryStatus::Kept => "kept", | |
| 449 | MemoryStatus::Dismissed => "dismissed", | |
| 450 | } | |
| 451 | } | |
| 452 | ||
| 453 | pub fn parse(value: &str) -> Option<MemoryStatus> { | |
| 454 | [MemoryStatus::Candidate, MemoryStatus::Kept, MemoryStatus::Dismissed] | |
| 455 | .into_iter() | |
| 456 | .find(|status| status.as_str() == value) | |
| 457 | } | |
| 458 | } | |
| 459 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 460 | #[derive(Clone, Debug, Serialize, Deserialize)] |
| 461 | #[serde(rename_all = "camelCase")] | |
| 462 | pub struct Memory { | |
| 463 | pub id: String, | |
| 464 | pub scope: MemoryScope, | |
| 465 | /// The workspace's slug. | |
| 466 | pub workspace: String, | |
| 467 | /// For a project's memory, the project's repository. | |
| 468 | pub repo: Option<RepoPath>, | |
| 469 | pub text: String, | |
| 470 | pub kind: MemoryKind, | |
| 471 | pub source: MemorySource, | |
| 472 | /// Who wrote it: a username, or `g1t-agent`. | |
| 473 | pub created_by: String, | |
| 474 | /// Pinned memories are given to every agent first. | |
| 475 | pub pinned: bool, | |
| 476 | /// RFC 3339. | |
| 477 | pub created_at: String, | |
| 478 | pub updated_at: String, | |
| 479 | /// When it was last given to an agent. | |
| 480 | pub last_used_at: Option<String>, | |
| Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API | 481 | /// Kept memories are given to agents; candidates wait for review. |
| 482 | #[serde(default)] | |
| 483 | pub status: MemoryStatus, | |
| 484 | /// 0 to 1: how sure its source was. None for what people wrote. | |
| 485 | #[serde(default)] | |
| 486 | pub confidence: Option<f64>, | |
| 487 | /// How many independent sources said it. | |
| 488 | #[serde(default)] | |
| 489 | pub seen: u32, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 490 | } |
| 491 | ||
| 492 | #[derive(Clone, Debug, Default, Serialize, Deserialize)] | |
| 493 | #[serde(rename_all = "camelCase")] | |
| 494 | pub struct Memories { | |
| 495 | /// The project's own; empty when no project was named. | |
| 496 | pub project: Vec<Memory>, | |
| 497 | pub workspace: Vec<Memory>, | |
| 498 | } | |
| 499 | ||
| 500 | /// `list_memories`: a workspace's memory and, with `repo`, that project's. | |
| 501 | /// Members only. Returns `Outcome<Memories>`. | |
| 502 | #[derive(Debug, Serialize, Deserialize)] | |
| 503 | pub struct ListMemoriesArgs { | |
| 504 | pub viewer: Viewer, | |
| 505 | pub workspace: String, | |
| 506 | #[serde(default)] | |
| 507 | pub repo: Option<RepoPath>, | |
| 508 | } | |
| 509 | ||
| 510 | /// `add_memory`: a member or an agent adds to memory. A project's memory | |
| 511 | /// needs `repo`. Text that looks like a key or a token is refused. | |
| 512 | /// Returns `Outcome<Memory>`. | |
| 513 | #[derive(Debug, Serialize, Deserialize)] | |
| 514 | #[serde(rename_all = "camelCase")] | |
| 515 | pub struct AddMemoryArgs { | |
| 516 | pub actor: User, | |
| 517 | pub workspace: String, | |
| 518 | #[serde(default)] | |
| 519 | pub repo: Option<RepoPath>, | |
| 520 | pub scope: MemoryScope, | |
| 521 | pub text: String, | |
| 522 | #[serde(default)] | |
| 523 | pub kind: MemoryKind, | |
| 524 | #[serde(default)] | |
| 525 | pub pinned: bool, | |
| 526 | /// For an agent: the pull request it is working on. | |
| 527 | #[serde(default)] | |
| 528 | pub from_number: Option<u32>, | |
| 529 | } | |
| 530 | ||
| 531 | /// `update_memory`: changes a memory's text, kind or pin. Members only. | |
| 532 | /// Returns `Outcome<Memory>`. | |
| 533 | #[derive(Debug, Serialize, Deserialize)] | |
| 534 | pub struct UpdateMemoryArgs { | |
| 535 | pub actor: User, | |
| 536 | pub workspace: String, | |
| 537 | pub id: String, | |
| 538 | #[serde(default)] | |
| 539 | pub text: Option<String>, | |
| 540 | #[serde(default)] | |
| 541 | pub kind: Option<MemoryKind>, | |
| 542 | #[serde(default)] | |
| 543 | pub pinned: Option<bool>, | |
| 544 | } | |
| 545 | ||
| 546 | /// `delete_memory`: forgets a memory. Members only. Returns `Outcome<bool>`. | |
| 547 | #[derive(Debug, Serialize, Deserialize)] | |
| 548 | pub struct DeleteMemoryArgs { | |
| 549 | pub actor: User, | |
| 550 | pub workspace: String, | |
| 551 | pub id: String, | |
| 552 | } | |
| 553 | ||
| 554 | /// `recall`: what a project and its workspace remember, matching `query` | |
| 555 | /// when given (every word, in any order), pinned first. Members and g1t's | |
| 556 | /// agents. Returns `Outcome<Memories>`. | |
| 557 | #[derive(Debug, Serialize, Deserialize)] | |
| 558 | pub struct RecallArgs { | |
| 559 | pub viewer: Viewer, | |
| 560 | pub repo: RepoPath, | |
| 561 | #[serde(default)] | |
| 562 | pub query: Option<String>, | |
| 563 | #[serde(default)] | |
| 564 | pub limit: Option<u32>, | |
| 565 | } | |
| 566 | ||
| 567 | /// `memory_context`: what to tell an agent starting work in `repo`, within | |
| 568 | /// `budget` characters: pinned first, then the most recently used, the | |
| 569 | /// workspace's and the project's labelled apart. Marks what it gives as | |
| 570 | /// used. Called by the runner service only. Returns `MemoryContext`. | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 571 | /// |
| 572 | /// `requester` is the person the run acts for. The workspace's memory is | |
| 573 | /// its members': for a requester who is not one (an outside collaborator), | |
| 574 | /// only the project's memory is given. None, as from a runner that does not | |
| 575 | /// say, is the workspace's own step and gets both. | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 576 | #[derive(Debug, Serialize, Deserialize)] |
| 577 | pub struct MemoryContextArgs { | |
| 578 | pub repo: RepoPath, | |
| 579 | #[serde(default)] | |
| 580 | pub budget: Option<u32>, | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 581 | #[serde(default)] |
| 582 | pub requester: Option<User>, | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 583 | } |
| 584 | ||
| 585 | #[derive(Clone, Debug, Default, Serialize, Deserialize)] | |
| 586 | pub struct MemoryContext { | |
| 587 | /// None when there is nothing to tell. | |
| 588 | pub text: Option<String>, | |
| 589 | pub count: u32, | |
| 590 | } | |
| 591 | ||
| 592 | /// The longest a memory may be. | |
| 593 | pub const MAX_MEMORY_CHARS: usize = 1000; | |
| 594 | ||
| 595 | /// Prefixes of credentials that say what they are. | |
| 596 | const SECRET_PREFIXES: [(&str, &str); 20] = [ | |
| 597 | ("sk-ant-", "an Anthropic key"), | |
| 598 | ("sk-proj-", "an OpenAI key"), | |
| 599 | ("sk_live_", "a Stripe key"), | |
| 600 | ("sk_test_", "a Stripe key"), | |
| 601 | ("rk_live_", "a Stripe key"), | |
| 602 | ("whsec_", "a webhook signing secret"), | |
| 603 | ("ghp_", "a GitHub token"), | |
| 604 | ("gho_", "a GitHub token"), | |
| 605 | ("ghs_", "a GitHub token"), | |
| 606 | ("ghu_", "a GitHub token"), | |
| 607 | ("github_pat_", "a GitHub token"), | |
| 608 | ("glpat-", "a GitLab token"), | |
| 609 | ("xoxb-", "a Slack token"), | |
| 610 | ("xoxp-", "a Slack token"), | |
| 611 | ("AKIA", "an AWS access key"), | |
| 612 | ("ASIA", "an AWS access key"), | |
| 613 | ("AIza", "a Google API key"), | |
| 614 | ("g1t_", "a g1t token"), | |
| 615 | ("npm_", "an npm token"), | |
| 616 | ("SG.", "a SendGrid key"), | |
| 617 | ]; | |
| 618 | ||
| 619 | /// Words that, followed by `=` or `:` and a value, set a credential. | |
| 620 | const SECRET_WORDS: [&str; 8] = [ | |
| 621 | "password", | |
| 622 | "passwd", | |
| 623 | "secret", | |
| 624 | "api_key", | |
| 625 | "apikey", | |
| 626 | "api-key", | |
| 627 | "token", | |
| 628 | "private_key", | |
| 629 | ]; | |
| 630 | ||
| 631 | /// Bits of entropy per character of `word`. | |
| 632 | fn entropy(word: &str) -> f64 { | |
| 633 | let mut counts = std::collections::HashMap::new(); | |
| 634 | for c in word.chars() { | |
| 635 | *counts.entry(c).or_insert(0usize) += 1; | |
| 636 | } | |
| 637 | let length = word.chars().count() as f64; | |
| 638 | counts | |
| 639 | .values() | |
| 640 | .map(|&count| { | |
| 641 | let p = count as f64 / length; | |
| 642 | -p * p.log2() | |
| 643 | }) | |
| 644 | .sum() | |
| 645 | } | |
| 646 | ||
| 647 | /// What `text` seems to hold that must never be stored in memory, which | |
| 648 | /// every agent in the workspace reads: a key, a token, a private key or a | |
| 649 | /// password. None when it looks clean. Errs on the side of refusing; a | |
| 650 | /// person can always say where a secret lives instead of what it is. | |
| 651 | pub fn secret_in(text: &str) -> Option<&'static str> { | |
| 652 | if text.contains("-----BEGIN") && text.contains("PRIVATE KEY") { | |
| 653 | return Some("a private key"); | |
| 654 | } | |
| 655 | let lower = text.to_lowercase(); | |
| 656 | for word in SECRET_WORDS { | |
| 657 | let mut rest = lower.as_str(); | |
| 658 | while let Some(at) = rest.find(word) { | |
| 659 | let after = rest[at + word.len()..].trim_start_matches(['"', '\'', ' ']); | |
| 660 | if let Some(value) = after.strip_prefix(['=', ':']) { | |
| 661 | let value: String = value | |
| 662 | .trim_start_matches([' ', '"', '\'']) | |
| 663 | .chars() | |
| 664 | .take_while(|c| !c.is_whitespace() && *c != '"' && *c != '\'' && *c != ',') | |
| 665 | .collect(); | |
| 666 | // "token: see 1Password" names where it is, which is fine. | |
| 667 | if value.chars().count() >= 8 && value.chars().any(|c| c.is_ascii_digit()) { | |
| 668 | return Some("a password or token"); | |
| 669 | } | |
| 670 | } | |
| 671 | rest = &rest[at + word.len()..]; | |
| 672 | } | |
| 673 | } | |
| 674 | let words = text.split(|c: char| { | |
| 675 | c.is_whitespace() || matches!(c, '"' | '\'' | '`' | ',' | ';' | '(' | ')' | '<' | '>' | '[' | ']' | '{' | '}') | |
| 676 | }); | |
| 677 | for word in words { | |
| 678 | let word = word.trim_end_matches(['.', ':']); | |
| 679 | // A key=value pair is judged by its value. | |
| 680 | let word = word.rsplit_once('=').map_or(word, |(_, value)| value); | |
| 681 | for (prefix, what) in SECRET_PREFIXES { | |
| 682 | if let Some(rest) = word.strip_prefix(prefix) { | |
| 683 | let tail = rest.chars().filter(|c| c.is_ascii_alphanumeric()).count(); | |
| 684 | if tail >= 12 { | |
| 685 | return Some(what); | |
| 686 | } | |
| 687 | } | |
| 688 | } | |
| 689 | // A URL with a password in it. | |
| 690 | if let Some((_, rest)) = word.split_once("://") | |
| 691 | && let Some((credentials, _)) = rest.split_once('@') | |
| 692 | && credentials.contains(':') | |
| 693 | { | |
| 694 | return Some("a URL with a password in it"); | |
| 695 | } | |
| 696 | let length = word.chars().count(); | |
| 697 | if length < 32 || word.contains("://") || word.contains('/') && !word.contains('+') { | |
| 698 | continue; | |
| 699 | } | |
| 700 | let token_chars = word | |
| 701 | .chars() | |
| 702 | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '+' | '/' | '=')); | |
| 703 | if !token_chars { | |
| 704 | continue; | |
| 705 | } | |
| 706 | let hex = word.chars().all(|c| c.is_ascii_hexdigit()); | |
| 707 | // A commit's id is 40 hex characters and fine; longer runs of hex | |
| 708 | // are keys and digests of keys. | |
| 709 | if hex { | |
| 710 | if length >= 48 { | |
| 711 | return Some("a key or token"); | |
| 712 | } | |
| 713 | continue; | |
| 714 | } | |
| 715 | let upper = word.chars().any(|c| c.is_ascii_uppercase()); | |
| 716 | let lower = word.chars().any(|c| c.is_ascii_lowercase()); | |
| 717 | let digit = word.chars().any(|c| c.is_ascii_digit()); | |
| 718 | if upper && lower && digit && entropy(word) > 4.0 { | |
| 719 | return Some("a key or token"); | |
| 720 | } | |
| 721 | } | |
| 722 | None | |
| 723 | } | |
| 724 | ||
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 725 | // --- Compute gating --------------------------------------------------------- |
| 726 | // | |
| 727 | // What the runner needs from the work service to apply a workspace's plan | |
| 728 | // caps: how many agents it has at work, what an issue's agents have spent, | |
| 729 | // and somewhere for runs to wait for a free slot. | |
| 730 | ||
| 731 | /// The kinds of run that count against a workspace's agents-at-once cap. | |
| 732 | pub const AGENT_KINDS: [RunKind; 6] = [ | |
| 733 | RunKind::Implement, | |
| 734 | RunKind::Revise, | |
| 735 | RunKind::Review, | |
| 736 | RunKind::Answer, | |
| 737 | RunKind::Update, | |
| 738 | RunKind::Plan, | |
| 739 | ]; | |
| 740 | ||
| 741 | /// `active_agents`: how many agent runs a workspace has queued or running | |
| 742 | /// now. Called by the runner. Returns `u32`. | |
| 743 | #[derive(Debug, Serialize, Deserialize)] | |
| 744 | pub struct ActiveAgentsArgs { | |
| 745 | pub workspace: String, | |
| 746 | } | |
| 747 | ||
| 748 | /// `issue_spend`: what the agents on an issue have cost so far, in all its | |
| 749 | /// pull requests' runs and the runs on the issue itself. `number` may name | |
| 750 | /// the issue or one of its pull requests. Called by the runner. Returns | |
| 751 | /// `Outcome<IssueSpend>`. | |
| 752 | #[derive(Debug, Serialize, Deserialize)] | |
| 753 | pub struct IssueSpendArgs { | |
| 754 | pub repo: RepoPath, | |
| 755 | pub number: u32, | |
| 756 | } | |
| 757 | ||
| 758 | #[derive(Clone, Debug, Serialize, Deserialize)] | |
| 759 | #[serde(rename_all = "camelCase")] | |
| 760 | pub struct IssueSpend { | |
| 761 | /// The issue counted: the one `number` names, or its pull request's. | |
| 762 | /// A pull request with no issue counts as its own. | |
| 763 | pub issue: u32, | |
| 764 | /// What the model providers charged for its runs, in millionths of a | |
| 765 | /// dollar. | |
| 766 | pub spent_micros: i64, | |
| 767 | } | |
| 768 | ||
| 769 | /// `wait_for_slot`: gives back a lifecycle step the runner claimed but | |
| 770 | /// could not start because the workspace's agents were all busy, so the | |
| 771 | /// next sweep takes it again, and says so on the pull request. Returns | |
| 772 | /// `bool`. | |
| 773 | #[derive(Debug, Serialize, Deserialize)] | |
| 774 | #[serde(rename_all = "camelCase")] | |
| 775 | pub struct WaitForSlotArgs { | |
| 776 | pub pull_id: String, | |
| 777 | pub reason: String, | |
| 778 | } | |
| 779 | ||
| 780 | /// `agent_comment`: a comment from g1t-agent on an issue or pull request, | |
| 781 | /// for what it could not do there. Called by the runner. Returns `bool`. | |
| 782 | #[derive(Debug, Serialize, Deserialize)] | |
| 783 | pub struct AgentCommentArgs { | |
| 784 | pub repo: RepoPath, | |
| 785 | pub number: u32, | |
| 786 | pub body: String, | |
| 787 | } | |
| 788 | ||
| 789 | /// `add_wait`: a run a person asked for, waiting for one of the | |
| 790 | /// workspace's agent slots. `payload` is what the runner needs to start it | |
| 791 | /// later; the work service only keeps it. Returns `bool`. | |
| 792 | #[derive(Debug, Serialize, Deserialize)] | |
| 793 | pub struct AddWaitArgs { | |
| 794 | pub workspace: String, | |
| 795 | pub kind: String, | |
| 796 | pub payload: serde_json::Value, | |
| 797 | } | |
| 798 | ||
| 799 | /// `waiting_workspaces`: the workspaces with runs waiting, oldest first. | |
| 800 | /// Returns `Vec<String>`. | |
| 801 | #[derive(Debug, Default, Serialize, Deserialize)] | |
| 802 | pub struct WaitingWorkspacesArgs {} | |
| 803 | ||
| 804 | /// `take_wait`: the oldest run waiting in a workspace, taken out of the | |
| 805 | /// queue in one statement. Returns `Option<AgentWait>`. | |
| 806 | #[derive(Debug, Serialize, Deserialize)] | |
| 807 | pub struct TakeWaitArgs { | |
| 808 | pub workspace: String, | |
| 809 | } | |
| 810 | ||
| 811 | #[derive(Clone, Debug, Serialize, Deserialize)] | |
| 812 | #[serde(rename_all = "camelCase")] | |
| 813 | pub struct AgentWait { | |
| 814 | pub id: String, | |
| 815 | pub workspace: String, | |
| 816 | pub kind: String, | |
| 817 | pub payload: serde_json::Value, | |
| 818 | pub created_at: String, | |
| 819 | } | |
| 820 | ||
| 821 | /// `run_cost`: what a run's model cost, as its sandbox reported it, for | |
| 822 | /// the runner settling the run's reservation. Needs the run's token. | |
| 823 | /// Returns `Option<f64>`, in US dollars. | |
| 824 | #[derive(Debug, Serialize, Deserialize)] | |
| 825 | #[serde(rename_all = "camelCase")] | |
| 826 | pub struct RunCostArgs { | |
| 827 | pub run_id: String, | |
| 828 | pub token: String, | |
| 829 | } | |
| 830 | ||
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 831 | #[cfg(test)] |
| 832 | mod tests { | |
| 833 | use super::*; | |
| 834 | ||
| 835 | #[test] | |
| 836 | fn plain_knowledge_is_kept() { | |
| 837 | for text in [ | |
| 838 | "We use pnpm everywhere, never npm or yarn.", | |
| 839 | "Staging lives at https://staging.example.com and deploys from main.", | |
| 840 | "The tests need TZ=UTC or the date tests fail.", | |
| 841 | "Commit 9f2c4e1a7b3d5f60812a4c6e8b0d2f4a6c8e0b13 introduced the flaky retry.", | |
| 842 | "The API token is in 1Password under 'Deploy'.", | |
| 843 | "token: ask Ana for one", | |
| 844 | "src/components/ui/select.tsx wraps Radix; import from there, not radix-ui.", | |
| 845 | "Run cargo test -p g1t-work before pushing changes to services/work.", | |
| 846 | ] { | |
| 847 | assert_eq!(secret_in(text), None, "{text}"); | |
| 848 | } | |
| 849 | } | |
| 850 | ||
| 851 | #[test] | |
| 852 | fn credentials_are_refused() { | |
| Secret-refusal tests build their key-shaped values at run time | 853 | // Key-shaped values are joined at run time: no whole key sits in the |
| 854 | // source for secret scanners to flag. | |
| 855 | let join = |a: &str, b: &str| format!("{a}{b}"); | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 856 | for text in [ |
| Secret-refusal tests build their key-shaped values at run time | 857 | join("The key is sk-", "ant-api03-abcdefghijklmnopqrstuvwxyz"), |
| 858 | join("use gh", "p_abcdefghijklmnopqrstuvwxyz0123456789 to clone"), | |
| 859 | join("AWS: AK", "IAIOSFODNN7EXAMPLE"), | |
| 860 | join("STRIPE_KEY=sk_l", "ive_51HabcdefghijklmnopQRSTUV"), | |
| 861 | "password = hunter2hunter2".to_owned(), | |
| 862 | "db: postgres://admin:s3cret@db.internal:5432/app".to_owned(), | |
| 863 | "token is 3f9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a".to_owned(), | |
| 864 | "-----BEGIN RSA PRIVATE KEY-----\nMIIE...".to_owned(), | |
| 865 | "secret: Zq8wN3vR7tY2uI5oP1aS6dF4gH9jK0lX".to_owned(), | |
| 866 | "it is xK9mQ2vL8nR4tP7wZ3yB6cF1dG5hJ0sA".to_owned(), | |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 867 | ] { |
| Secret-refusal tests build their key-shaped values at run time | 868 | assert!(secret_in(&text).is_some(), "{text}"); |
| Agents and memory, checks and conflicts, profiles, slug renames, custom domains | 869 | } |
| 870 | } | |
| 871 | ||
| 872 | #[test] | |
| 873 | fn kinds_and_statuses_round_trip() { | |
| 874 | for kind in RunKind::ALL { | |
| 875 | assert_eq!(RunKind::parse(kind.as_str()), Some(kind)); | |
| 876 | } | |
| 877 | assert!(RunKind::Implement.takes_messages() && !RunKind::Review.takes_messages()); | |
| 878 | assert!(!RunKind::Checks.is_agent()); | |
| 879 | assert_eq!(RunStatus::parse("stopped"), Some(RunStatus::Stopped)); | |
| 880 | assert!(RunStatus::Queued.is_active() && !RunStatus::Failed.is_active()); | |
| 881 | assert_eq!(MemoryKind::parse("gotcha"), Some(MemoryKind::Gotcha)); | |
| 882 | } | |
| 883 | } |