hird-server 0.3.1

The central queue: hird served over HTTP for harnesses on other machines.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! `hird-server` — the central queue.
//!
//! The `hird` binary is a local queue: one process per harness session, stdio,
//! no network, and a working tree it can read. This one is the other thing —
//! a process on a host two people reach from two machines, speaking MCP over
//! HTTP, with the queue's SQLite file underneath it.
//!
//! It is a separate binary rather than a flag on the first because a server is
//! a different kind of program. It carries a web stack the local binary must
//! not: `cargo tree -p hird` names no HTTP dependency at all, and that stays
//! true however large this one grows.
//!
//! ## How a connection becomes a session
//!
//! [`hird::mcp::Session`] holds who a connection is; the question a server has
//! to answer is who to believe. The far end of a socket can claim anything, so
//! nothing it says about its identity is taken: a request carries a bearer
//! token, the [`roster`] maps that token to a person, and the session is built
//! from the roster's entry. A client may still name its own harness — §29
//! permits that and never permits the other.
//!
//! Each roster entry gets its own MCP service, so identity is fixed when the
//! service is built rather than re-derived per call. Dispatch is a map lookup
//! on the token, and a request without a known one is refused before any of
//! the queue is touched.

mod factory;
mod quickstart;
mod roster;
mod tour;
mod watch;

#[cfg(test)]
mod tests;

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;

use axum::body::Body;
use axum::extract::State;
use axum::http::{Request, StatusCode};
use axum::response::{IntoResponse, Response};
use clap::{Args, Parser, Subcommand};
use hird::config::{self, Config};
use hird::identity::AgentId;
use hird::mcp::{HirdMcp, Session, Shared};
use hird::Db;
use hird_factory::{FactoryGate, Policy};
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::StreamableHttpService;
use tower_service::Service;

use crate::factory::{FactoryMcp, Membership};
use crate::roster::Roster;

/// One MCP endpoint, already bound to one person.
type Endpoint = StreamableHttpService<FactoryMcp, LocalSessionManager>;

#[derive(Debug, Parser)]
#[command(
    name = "hird-server",
    version,
    about = "Serve a hird queue over HTTP to harnesses on other machines.",
    long_about = "The central queue. Harnesses on other machines reach it over MCP \
                  streamable HTTP, each authenticated by a bearer token that the roster \
                  maps to a person. Every claim is still atomic, because there is still \
                  one SQLite file.\n\n\
                  Terminate TLS in front of this: it speaks plain HTTP, and a bearer \
                  token on an unencrypted connection is a token you have given away.\n\n\
                  New here? `hird-server quickstart --tour` sets up a software factory to \
                  try, walks you through a sample step by step, and serves it.",
    subcommand_negates_reqs = true
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
    /// The roster file: which tokens may connect, and as whom.
    #[arg(long, value_name = "PATH", required = true)]
    roster: Option<PathBuf>,
    /// Address to listen on.
    #[arg(long, default_value = "127.0.0.1", value_name = "ADDR")]
    bind: String,
    /// Port to listen on.
    #[arg(long, default_value_t = 7474)]
    port: u16,
    /// Database file to use. Overrides HIRD_DB and the default location.
    #[arg(long, value_name = "PATH")]
    db: Option<PathBuf>,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Set up a software factory to try, print a step-by-step guide, and serve it.
    ///
    /// Writes everything into one directory: a factory roster with fresh tokens
    /// (you as the human, one builder-reviewer token per agent harness, and CI),
    /// a database, the snippet that connects each harness, `ci` and `human`
    /// scripts for the moves no agent makes, and GUIDE.md. Without --project
    /// the project is a playground git repository with a three-task sample
    /// release already filed. Run it again to come back: the same tokens, the
    /// same board.
    Quickstart(QuickstartArgs),
}

#[derive(Debug, Args)]
struct QuickstartArgs {
    /// Where the factory lives. Created if missing; reused if already set up.
    #[arg(long, default_value = "hird-factory", value_name = "DIR")]
    dir: PathBuf,
    /// An agent harness to give a token: claude-code, codex, copilot,
    /// copilot-cli, gemini, opencode, or any other name. Repeatable. Two or
    /// more, so that each can review what the other built.
    #[arg(
        long = "harness",
        value_name = "NAME",
        default_values_t = ["claude-code".to_string(), "codex".to_string()]
    )]
    harnesses: Vec<String>,
    /// Work on this repository instead of a playground. Nothing is filed for you.
    #[arg(long, value_name = "PATH")]
    project: Option<PathBuf>,
    /// Address to listen on.
    #[arg(long, default_value = "127.0.0.1", value_name = "ADDR")]
    bind: String,
    /// Port to listen on.
    #[arg(long, default_value_t = 7474)]
    port: u16,
    /// Set up and print the guide, but do not start serving.
    #[arg(long, conflicts_with = "tour")]
    no_serve: bool,
    /// Before handing over, walk through the sample step by step: task #1
    /// played from ready to merged by the crew, pausing after each gate to
    /// say what happened and why. #2 and #3 are left for your own agents.
    #[arg(long)]
    tour: bool,
}

/// One roster entry's way in, by lifecycle.
///
/// A client that handshakes with `initialize` gets a protocol session, and
/// each such session is its own agent with its own suffix, as a local `hird
/// mcp` process is. A 2026-07-28 client has no protocol session: rmcp serves
/// each of its requests on a fresh service. Minting a fresh suffix per request
/// would make every call a different agent, unable to update a task it had
/// just claimed. So stateless requests on one token share one session, whose
/// suffix is minted once, when the server starts.
#[derive(Clone)]
struct Door {
    sessions: Endpoint,
    stateless: Endpoint,
}

/// Everything the HTTP layer needs: one door per token.
#[derive(Clone)]
struct Fleet {
    endpoints: Arc<BTreeMap<String, Door>>,
}

impl Fleet {
    /// Build one MCP endpoint per roster entry, all sharing one open database.
    ///
    /// The identity is closed over here rather than read per request, so a
    /// session cannot change who it is halfway through — the same invariant
    /// the local binary gets from having one process per session.
    fn assemble(roster: &Roster, shared: Arc<Shared>, config: &Config) -> anyhow::Result<Fleet> {
        let mut endpoints = BTreeMap::new();
        let policy = roster.factory().cloned().map(Arc::new);
        for (token, worker) in roster.entries() {
            let endpoint = |suffix: Option<String>| {
                let (policy, shared) = (policy.clone(), shared.clone());
                let (config, worker) = (config.clone(), worker.clone());
                StreamableHttpService::new(
                    move || {
                        connect(
                            &worker,
                            policy.clone(),
                            shared.clone(),
                            &config,
                            suffix.as_deref(),
                        )
                        .map_err(std::io::Error::other)
                    },
                    Arc::new(LocalSessionManager::default()),
                    Default::default(),
                )
            };
            // One suffix for this token's stateless session, for as long as
            // this process serves it: the same lifetime a local session has.
            let suffix = AgentId::fresh("").session().to_string();
            let door = Door {
                sessions: endpoint(None),
                stateless: endpoint(Some(suffix)),
            };
            endpoints.insert(token.clone(), door);
        }
        Ok(Fleet {
            endpoints: Arc::new(endpoints),
        })
    }
}

/// One connection for `worker`: its identity, and — in a factory — its roles,
/// stamped on everything it does and enforced on every claim and finish.
/// `suffix` names the session when it outlives a connection (the stateless
/// one); otherwise each connection mints its own.
fn connect(
    worker: &roster::Worker,
    policy: Option<Arc<Policy>>,
    shared: Arc<Shared>,
    config: &Config,
    suffix: Option<&str>,
) -> hird::Result<FactoryMcp> {
    let harness = worker.harness.clone().unwrap_or_default();
    let agent = match suffix {
        Some(suffix) => AgentId::new(harness, suffix),
        None => AgentId::fresh(harness),
    }
    .acting_for(worker.identity.clone())
    .running(worker.model.clone().unwrap_or_default());
    let session = Session::new(
        agent,
        worker.project.clone(),
        worker.capabilities.clone(),
        config,
    )?;
    let Some(policy) = policy else {
        return Ok(FactoryMcp::new(HirdMcp::connect(shared, session), None));
    };
    // Every worker in a factory gets a gate, roles or none: a token with no
    // role may read the board and do nothing else.
    let gate = FactoryGate::new(worker.roles.clone(), (*policy).clone());
    let session = session
        .with_role(worker.roles.to_string())
        .with_gate(Arc::new(gate));
    let member = Membership {
        policy,
        roles: worker.roles.clone(),
    };
    Ok(FactoryMcp::new(
        HirdMcp::connect(shared, session),
        Some(member),
    ))
}

/// The bearer token a request presents, if it presents one properly.
fn bearer(request: &Request<Body>) -> Option<&str> {
    request
        .headers()
        .get(axum::http::header::AUTHORIZATION)?
        .to_str()
        .ok()?
        .strip_prefix("Bearer ")
        .map(str::trim)
        .filter(|token| !token.is_empty())
}

/// Whether a request is a 2026-07-28 one, which has no protocol session.
///
/// The protocol requires such a request to name its version in the
/// `MCP-Protocol-Version` header, and versions are dates, so they compare as
/// strings. A request carrying a session id belongs to a session whatever it
/// says. Getting this wrong costs nothing unsafe: both endpoints serve both
/// lifecycles, and they differ only in how long the agent's suffix lasts.
fn is_stateless(request: &Request<Body>) -> bool {
    let headers = request.headers();
    !headers.contains_key("mcp-session-id")
        && headers
            .get("mcp-protocol-version")
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.trim() >= "2026-07-28")
}

/// Route a request to the endpoint its token names.
///
/// A request with no token, or one the roster does not know, is refused here —
/// before the database is opened, before a session exists, and with the same
/// answer either way, so the response does not say which tokens are real.
async fn route(State(fleet): State<Fleet>, request: Request<Body>) -> Response {
    let Some(door) = bearer(&request).and_then(|token| fleet.endpoints.get(token)) else {
        return (
            StatusCode::UNAUTHORIZED,
            [(
                axum::http::header::WWW_AUTHENTICATE,
                "Bearer realm=\"hird\"",
            )],
            "this queue is not open to unnamed callers\n",
        )
            .into_response();
    };
    let mut endpoint = if is_stateless(&request) {
        door.stateless.clone()
    } else {
        door.sessions.clone()
    };
    match endpoint.call(request).await {
        Ok(response) => response.into_response(),
        Err(never) => match never {},
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    if let Some(Command::Quickstart(args)) = cli.command {
        return quickstart(args).await;
    }
    let roster_path = cli
        .roster
        .expect("clap requires --roster without a subcommand");
    let roster = Roster::load(&roster_path)?;
    let config = Config::load_default()?;
    let db_path = config::resolve_db_path(cli.db.as_deref());
    serve(&roster, &db_path, config, &cli.bind, cli.port).await
}

/// Set a factory up (or find it), say what to do with it, and serve it.
async fn quickstart(args: QuickstartArgs) -> anyhow::Result<()> {
    let ready = quickstart::prepare(&quickstart::Options {
        dir: args.dir.clone(),
        harnesses: args.harnesses,
        project: args.project,
        bind: args.bind.clone(),
        port: args.port,
    })?;
    if !args.tour {
        println!("{}", ready.guide);
    }
    if args.no_serve {
        let roster = ready.roster.display();
        println!(
            "Not serving (--no-serve). Start it with:\n\n    hird-server --roster {roster} --db {} --bind {} --port {}\n",
            ready.db.display(),
            args.bind,
            args.port
        );
        return Ok(());
    }
    let roster = Roster::load(&ready.roster)?;
    // The server reads no one's working tree: the agents may be anywhere.
    let mut config = Config::load_default()?;
    config.witness = false;
    if !args.tour {
        println!("Serving. Leave this running; Ctrl-C stops it.\n");
        return serve(&roster, &ready.db, config, &args.bind, args.port).await;
    }

    let shared = Arc::new(Shared::new(Db::open(&ready.db)?, config.clone()));
    let app = router(&roster, shared, &config)?;
    let Some(playground) = ready.playground.clone() else {
        anyhow::bail!(
            "the tour plays the sample release, which only a playground has: \
             drop --project, or pass a --dir of its own"
        );
    };
    // The directory as it was named, so the commands shown are ones to type.
    let dir = if args.dir.is_relative() && !args.dir.starts_with(".") {
        PathBuf::from(".").join(&args.dir)
    } else {
        args.dir.clone()
    };
    let tour = tour::Tour {
        app: app.clone(),
        host: format!("{}:{}", args.bind, args.port),
        crew: &ready.crew,
        dir: &dir,
        playground,
        pause: true,
    };
    let fresh = tour.can_start().await?;
    let listener = listen(&roster, &ready.db, &config, &args.bind, args.port).await?;
    let server = tokio::spawn(async move {
        axum::serve(listener, app)
            .with_graceful_shutdown(async {
                let _ = tokio::signal::ctrl_c().await;
            })
            .await
    });
    if fresh {
        tokio::select! {
            played = tour.run() => played?,
            _ = tokio::signal::ctrl_c() => {
                // A pause is a blocking read of stdin, which the runtime would
                // wait for on the way out. Every move is already committed.
                println!();
                std::process::exit(0);
            }
        }
    } else {
        println!(
            "\nThe tour starts from a fresh sample, and #1 in {} has moved on already. \
             For the tour again: hird-server quickstart --tour --dir <a new directory>\n\n\
             What to do with this factory is in {}/GUIDE.md.\n",
            dir.display(),
            dir.display()
        );
    }
    println!("Serving. Leave this running; Ctrl-C stops it.\n");
    server.await??;
    Ok(())
}

async fn serve(
    roster: &Roster,
    db_path: &std::path::Path,
    config: Config,
    bind: &str,
    port: u16,
) -> anyhow::Result<()> {
    let shared = Arc::new(Shared::new(Db::open(db_path)?, config.clone()));
    let app = router(roster, shared, &config)?;
    let listener = listen(roster, db_path, &config, bind, port).await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;
    Ok(())
}

/// Every route the server answers: MCP by token, and the floor.
fn router(roster: &Roster, shared: Arc<Shared>, config: &Config) -> anyhow::Result<axum::Router> {
    let fleet = Fleet::assemble(roster, shared.clone(), config)?;
    Ok(axum::Router::new()
        .fallback(axum::routing::any(route))
        .with_state(fleet)
        .merge(watch::Watch::new(roster, shared).router()))
}

/// Bind the port and say what is being served there.
async fn listen(
    roster: &Roster,
    db_path: &std::path::Path,
    config: &Config,
    bind: &str,
    port: u16,
) -> anyhow::Result<tokio::net::TcpListener> {
    let listener = tokio::net::TcpListener::bind((bind, port)).await?;
    let addr = listener.local_addr()?;
    println!(
        "hird-server on http://{addr}  ({} in the roster)",
        roster.len()
    );
    println!("database: {}", db_path.display());
    println!("watch:    http://{addr}/watch  (read-only; asks for a roster token)");
    if let Some(policy) = roster.factory() {
        println!(
            "factory: on (max_attempts {}, CI to merge {}, CI before review {})",
            policy.max_attempts, policy.require_ci_to_merge, policy.require_ci_before_review
        );
    }
    if config.witness {
        println!(
            "note: the witness is on, and it reads this host's working tree — \
             nobody's checkout. Set `witness = false` for a shared queue."
        );
    }
    Ok(listener)
}